Skip to content

Commit 66d55db

Browse files
committed
fix(server): add re-entrancy guard to close() to prevent stack overflow
When close() is called while cleanup() callbacks are still running (e.g. a cleanup function that triggers onclose which calls close() again), the transport enters infinite recursion causing RangeError: Maximum call stack size exceeded — especially acute when multiple transports close simultaneously. The fix adds a _closed boolean flag checked at the top of close(). If the transport is already closing, subsequent calls return immediately instead of recursing. This is safe because close() is idempotent. Also applies to the idempotent close() contract: calling close() multiple times should have no additional effect after the first call. Fixes modelcontextprotocol#1699.
1 parent 984a27e commit 66d55db

1 file changed

Lines changed: 4 additions & 0 deletions

File tree

‎packages/server/src/server/streamableHttp.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,7 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
230230
private _requestResponseMap: Map<RequestId, JSONRPCMessage> = new Map();
231231
private _initialized: boolean = false;
232232
private _enableJsonResponse: boolean = false;
233+
private _closed: boolean = false;
233234
private _standaloneSseStreamId: string = '_GET_stream';
234235
private _eventStore?: EventStore;
235236
private _onsessioninitialized?: (sessionId: string) => void | Promise<void>;
@@ -900,6 +901,9 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
900901
}
901902

902903
async close(): Promise<void> {
904+
if (this._closed) return;
905+
this._closed = true;
906+
903907
// Close all SSE connections
904908
for (const { cleanup } of this._streamMapping.values()) {
905909
cleanup();

0 commit comments

Comments
 (0)