Skip to content

Commit c65e3d1

Browse files
committed
fix(client): retry SSE stream after receiving session ID
Fixes server-initiated requests (roots/list, sampling, elicitation) hanging over HTTP transport. The client now retries opening the GET SSE stream after receiving a session ID during initialization. Fixes: modelcontextprotocol#1167
1 parent 328becc commit c65e3d1

3 files changed

Lines changed: 92 additions & 0 deletions

File tree

‎src/client/streamableHttp.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@ 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
140141

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

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

480482
// Handle session ID received during initialization
481483
const sessionId = response.headers.get('mcp-session-id');
484+
const hadSessionId = this._sessionId !== undefined;
482485
if (sessionId) {
483486
this._sessionId = sessionId;
484487
}
485488

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+
486497
if (!response.ok) {
487498
const text = await response.text().catch(() => null);
488499

‎test/client/streamableHttp.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,19 @@ 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+
104112
await transport.send(message);
105113

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

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+
140159
await transport.send(message);
160+
161+
// Allow the async SSE connection attempt to complete
162+
await new Promise(resolve => setTimeout(resolve, 10));
163+
141164
expect(transport.sessionId).toBe('test-session-id');
142165

143166
// Now terminate the session
@@ -177,8 +200,19 @@ describe('StreamableHTTPClientTransport', () => {
177200
headers: new Headers({ 'content-type': 'text/event-stream', 'mcp-session-id': 'test-session-id' })
178201
});
179202

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+
180211
await transport.send(message);
181212

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

‎test/integration-tests/stateManagementStreamableHttp.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
ListToolsResultSchema,
1010
ListResourcesResultSchema,
1111
ListPromptsResultSchema,
12+
ListRootsRequestSchema,
1213
LATEST_PROTOCOL_VERSION
1314
} from '../../src/types.js';
1415
import { zodTestMatrix, type ZodMatrixEntry } from '../../src/__fixtures__/zodTestMatrix.js';
@@ -376,6 +377,52 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => {
376377
// Clean up
377378
await transport.close();
378379
});
380+
381+
it('should support server-initiated roots/list request', async () => {
382+
// This test reproduces GitHub issue #1167
383+
// https://github.com/modelcontextprotocol/typescript-sdk/issues/1167
384+
//
385+
// The bug: server.listRoots() hangs when using HTTP transport because:
386+
// 1. Client tries to open GET SSE stream before initialization
387+
// 2. Server rejects with 400 "Server not initialized"
388+
// 3. Client never retries opening SSE stream after initialization
389+
// 4. Server's send() silently returns when no SSE stream exists
390+
// 5. listRoots() promise never resolves
391+
392+
// Create client with roots capability
393+
const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { roots: { listChanged: true } } });
394+
395+
// Register handler for roots/list requests from server
396+
client.setRequestHandler(ListRootsRequestSchema, async () => {
397+
return {
398+
roots: [{ uri: 'file:///home/user/project', name: 'Test Project' }]
399+
};
400+
});
401+
402+
const transport = new StreamableHTTPClientTransport(baseUrl);
403+
await client.connect(transport);
404+
405+
// Verify client has session ID (stateful mode)
406+
expect(transport.sessionId).toBeDefined();
407+
408+
// Now try to call listRoots from the server
409+
const rootsPromise = mcpServer!.server.listRoots();
410+
411+
// Use a short timeout to detect the hang
412+
const timeoutPromise = new Promise<never>((_, reject) => {
413+
setTimeout(() => reject(new Error('listRoots() timed out - SSE stream not working')), 2000);
414+
});
415+
416+
const result = await Promise.race([rootsPromise, timeoutPromise]);
417+
418+
expect(result.roots).toHaveLength(1);
419+
expect(result.roots[0]).toEqual({
420+
uri: 'file:///home/user/project',
421+
name: 'Test Project'
422+
});
423+
424+
await transport.close();
425+
});
379426
});
380427
});
381428
});

0 commit comments

Comments
 (0)