Skip to content

Commit d0eeff6

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 c7b18a0 commit d0eeff6

2 files changed

Lines changed: 6 additions & 46 deletions

File tree

‎src/client/streamableHttp.ts‎

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,6 @@ export class StreamableHTTPClientTransport implements Transport {
137137
private _lastUpscopingHeader?: string; // Track last upscoping header to prevent infinite upscoping.
138138
private _serverRetryMs?: number; // Server-provided retry delay from SSE retry field
139139
private _reconnectionTimeout?: ReturnType<typeof setTimeout>;
140-
private _sseStreamOpened = false; // Track if SSE stream was successfully opened
141140

142141
onclose?: () => void;
143142
onerror?: (error: Error) => void;
@@ -241,7 +240,6 @@ export class StreamableHTTPClientTransport implements Transport {
241240
throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`);
242241
}
243242

244-
this._sseStreamOpened = true;
245243
this._handleSseStream(response.body, options, true);
246244
} catch (error) {
247245
this.onerror?.(error as Error);
@@ -481,19 +479,10 @@ export class StreamableHTTPClientTransport implements Transport {
481479

482480
// Handle session ID received during initialization
483481
const sessionId = response.headers.get('mcp-session-id');
484-
const hadSessionId = this._sessionId !== undefined;
485482
if (sessionId) {
486483
this._sessionId = sessionId;
487484
}
488485

489-
// If we just received a session ID for the first time and SSE stream is not open,
490-
// try to open it now. This handles the case where the initial SSE connection
491-
// during start() was rejected because the server wasn't initialized yet.
492-
// See: https://github.com/modelcontextprotocol/typescript-sdk/issues/1167
493-
if (sessionId && !hadSessionId && !this._sseStreamOpened) {
494-
this._startOrAuthSse({ resumptionToken: undefined }).catch(err => this.onerror?.(err));
495-
}
496-
497486
if (!response.ok) {
498487
const text = await response.text().catch(() => null);
499488

@@ -572,8 +561,12 @@ export class StreamableHTTPClientTransport implements Transport {
572561
// if the accepted notification is initialized, we start the SSE stream
573562
// if it's supported by the server
574563
if (isInitializedNotification(message)) {
575-
// Start without a lastEventId since this is a fresh connection
576-
this._startOrAuthSse({ resumptionToken: undefined }).catch(err => this.onerror?.(err));
564+
// Await the SSE stream opening so that connect() does not resolve
565+
// until the GET listener is established. This prevents a race where
566+
// the server sends a request (e.g. roots/list) before the stream is ready.
567+
// Errors are swallowed here because _startOrAuthSse already reports
568+
// them via onerror, and the SSE stream is optional (server may 405).
569+
await this._startOrAuthSse({ resumptionToken: undefined }).catch(() => {});
577570
}
578571
return;
579572
}

‎test/client/streamableHttp.test.ts‎

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

104-
// Mock the SSE stream GET request that happens after receiving session ID
105-
(global.fetch as Mock).mockResolvedValueOnce({
106-
ok: false,
107-
status: 405,
108-
headers: new Headers(),
109-
body: { cancel: vi.fn() }
110-
});
111-
112104
await transport.send(message);
113105

114-
// Allow the async SSE connection attempt to complete
115-
await new Promise(resolve => setTimeout(resolve, 10));
116-
117106
// Send a second message that should include the session ID
118107
(global.fetch as Mock).mockResolvedValueOnce({
119108
ok: true,
@@ -148,19 +137,8 @@ describe('StreamableHTTPClientTransport', () => {
148137
headers: new Headers({ 'content-type': 'text/event-stream', 'mcp-session-id': 'test-session-id' })
149138
});
150139

151-
// Mock the SSE stream GET request that happens after receiving session ID
152-
(global.fetch as Mock).mockResolvedValueOnce({
153-
ok: false,
154-
status: 405,
155-
headers: new Headers(),
156-
body: { cancel: vi.fn() }
157-
});
158-
159140
await transport.send(message);
160141

161-
// Allow the async SSE connection attempt to complete
162-
await new Promise(resolve => setTimeout(resolve, 10));
163-
164142
expect(transport.sessionId).toBe('test-session-id');
165143

166144
// Now terminate the session
@@ -200,19 +178,8 @@ describe('StreamableHTTPClientTransport', () => {
200178
headers: new Headers({ 'content-type': 'text/event-stream', 'mcp-session-id': 'test-session-id' })
201179
});
202180

203-
// Mock the SSE stream GET request that happens after receiving session ID
204-
(global.fetch as Mock).mockResolvedValueOnce({
205-
ok: false,
206-
status: 405,
207-
headers: new Headers(),
208-
body: { cancel: vi.fn() }
209-
});
210-
211181
await transport.send(message);
212182

213-
// Allow the async SSE connection attempt to complete
214-
await new Promise(resolve => setTimeout(resolve, 10));
215-
216183
// Now terminate the session, but server responds with 405
217184
(global.fetch as Mock).mockResolvedValueOnce({
218185
ok: false,

0 commit comments

Comments
 (0)