Skip to content

Commit 88db838

Browse files
committed
fix(client): await SSE stream open in connect() to prevent race condition
After sending notifications/initialized, await the GET SSE stream opening so connect() does not resolve until the server can deliver requests (e.g. roots/list) through it. Previously the stream was opened fire-and-forget, meaning the server could attempt to send before the client was listening.
1 parent 3f15a76 commit 88db838

2 files changed

Lines changed: 6 additions & 46 deletions

File tree

‎packages/client/src/client/streamableHttp.ts‎

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,6 @@ export class StreamableHTTPClientTransport implements Transport {
184184
private _serverRetryMs?: number; // Server-provided retry delay from SSE retry field
185185
private readonly _reconnectionScheduler?: ReconnectionScheduler;
186186
private _cancelReconnection?: () => void;
187-
private _sseStreamOpened = false; // Track if SSE stream was successfully opened
188187

189188
onclose?: () => void;
190189
onerror?: (error: Error) => void;
@@ -293,7 +292,6 @@ export class StreamableHTTPClientTransport implements Transport {
293292
});
294293
}
295294

296-
this._sseStreamOpened = true;
297295
this._handleSseStream(response.body, options, true);
298296
} catch (error) {
299297
this.onerror?.(error as Error);
@@ -554,19 +552,10 @@ export class StreamableHTTPClientTransport implements Transport {
554552

555553
// Handle session ID received during initialization
556554
const sessionId = response.headers.get('mcp-session-id');
557-
const hadSessionId = this._sessionId !== undefined;
558555
if (sessionId) {
559556
this._sessionId = sessionId;
560557
}
561558

562-
// If we just received a session ID for the first time and SSE stream is not open,
563-
// try to open it now. This handles the case where the initial SSE connection
564-
// during start() was rejected because the server wasn't initialized yet.
565-
// See: https://github.com/modelcontextprotocol/typescript-sdk/issues/1167
566-
if (sessionId && !hadSessionId && !this._sseStreamOpened) {
567-
this._startOrAuthSse({ resumptionToken: undefined }).catch(error => this.onerror?.(error));
568-
}
569-
570559
if (!response.ok) {
571560
if (response.status === 401 && this._authProvider) {
572561
// Store WWW-Authenticate params for interactive finishAuth() path
@@ -650,8 +639,12 @@ export class StreamableHTTPClientTransport implements Transport {
650639
// if the accepted notification is initialized, we start the SSE stream
651640
// if it's supported by the server
652641
if (isInitializedNotification(message)) {
653-
// Start without a lastEventId since this is a fresh connection
654-
this._startOrAuthSse({ resumptionToken: undefined }).catch(error => this.onerror?.(error));
642+
// Await the SSE stream opening so that connect() does not resolve
643+
// until the GET listener is established. This prevents a race where
644+
// the server sends a request (e.g. roots/list) before the stream is ready.
645+
// Errors are swallowed here because _startOrAuthSse already reports
646+
// them via onerror, and the SSE stream is optional (server may 405).
647+
await this._startOrAuthSse({ resumptionToken: undefined }).catch(() => {});
655648
}
656649
return;
657650
}

‎packages/client/test/client/streamableHttp.test.ts‎

Lines changed: 0 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -104,19 +104,8 @@ describe('StreamableHTTPClientTransport', () => {
104104
headers: new Headers({ 'content-type': 'text/event-stream', 'mcp-session-id': 'test-session-id' })
105105
});
106106

107-
// Mock the SSE stream GET request that happens after receiving session ID
108-
(globalThis.fetch as Mock).mockResolvedValueOnce({
109-
ok: false,
110-
status: 405,
111-
headers: new Headers(),
112-
body: { cancel: vi.fn() }
113-
});
114-
115107
await transport.send(message);
116108

117-
// Allow the async SSE connection attempt to complete
118-
await new Promise(resolve => setTimeout(resolve, 10));
119-
120109
// Send a second message that should include the session ID
121110
(globalThis.fetch as Mock).mockResolvedValueOnce({
122111
ok: true,
@@ -178,19 +167,8 @@ describe('StreamableHTTPClientTransport', () => {
178167
headers: new Headers({ 'content-type': 'text/event-stream', 'mcp-session-id': 'test-session-id' })
179168
});
180169

181-
// Mock the SSE stream GET request that happens after receiving session ID
182-
(globalThis.fetch as Mock).mockResolvedValueOnce({
183-
ok: false,
184-
status: 405,
185-
headers: new Headers(),
186-
body: { cancel: vi.fn() }
187-
});
188-
189170
await transport.send(message);
190171

191-
// Allow the async SSE connection attempt to complete
192-
await new Promise(resolve => setTimeout(resolve, 10));
193-
194172
expect(transport.sessionId).toBe('test-session-id');
195173

196174
// Now terminate the session
@@ -230,19 +208,8 @@ describe('StreamableHTTPClientTransport', () => {
230208
headers: new Headers({ 'content-type': 'text/event-stream', 'mcp-session-id': 'test-session-id' })
231209
});
232210

233-
// Mock the SSE stream GET request that happens after receiving session ID
234-
(globalThis.fetch as Mock).mockResolvedValueOnce({
235-
ok: false,
236-
status: 405,
237-
headers: new Headers(),
238-
body: { cancel: vi.fn() }
239-
});
240-
241211
await transport.send(message);
242212

243-
// Allow the async SSE connection attempt to complete
244-
await new Promise(resolve => setTimeout(resolve, 10));
245-
246213
// Now terminate the session, but server responds with 405
247214
(globalThis.fetch as Mock).mockResolvedValueOnce({
248215
ok: false,

0 commit comments

Comments
 (0)