-
Notifications
You must be signed in to change notification settings - Fork 1.7k
fix: add existingSessionId option to WebStandardStreamableHTTPServerTransport for multi-node session hydration #1668
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Vadaski
wants to merge
5
commits into
modelcontextprotocol:main
from
Vadaski:fix/1658-streamable-http-session-hydration
+225
−2
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
3d7d68f
fix: add existingSessionId option to WebStandardStreamableHTTPServerT…
Vadaski 9691e19
fix: use !== undefined guard for existingSessionId check (#1658)
Vadaski e3ec989
fix: set sessionIdGenerator when existingSessionId is provided
Vadaski 4ea4610
refactor: simplify stateless check back to sessionIdGenerator === und…
Vadaski 7be827d
Merge branch 'main' into fix/1658-streamable-http-session-hydration
felixweinberger File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
195 changes: 195 additions & 0 deletions
195
test/integration/test/server/streamableHttp.sessionHydration.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,195 @@ | ||
| import type { CallToolResult, JSONRPCErrorResponse, JSONRPCMessage } from '@modelcontextprotocol/core'; | ||
| import { McpServer, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server'; | ||
| import { afterEach, beforeEach, describe, expect, it } from 'vitest'; | ||
| import * as z from 'zod/v4'; | ||
|
|
||
| const TEST_MESSAGES = { | ||
| initialize: { | ||
| jsonrpc: '2.0', | ||
| method: 'initialize', | ||
| params: { | ||
| clientInfo: { name: 'test-client', version: '1.0' }, | ||
| protocolVersion: '2025-11-25', | ||
| capabilities: {} | ||
| }, | ||
| id: 'init-1' | ||
| } as JSONRPCMessage, | ||
| toolsList: { | ||
| jsonrpc: '2.0', | ||
| method: 'tools/list', | ||
| params: {}, | ||
| id: 'tools-1' | ||
| } as JSONRPCMessage | ||
| }; | ||
|
|
||
| function createRequest( | ||
| method: string, | ||
| body?: JSONRPCMessage | JSONRPCMessage[], | ||
| options?: { | ||
| sessionId?: string; | ||
| accept?: string; | ||
| contentType?: string; | ||
| extraHeaders?: Record<string, string>; | ||
| } | ||
| ): Request { | ||
| const headers: Record<string, string> = {}; | ||
|
|
||
| if (options?.accept) { | ||
| headers.Accept = options.accept; | ||
| } else if (method === 'POST') { | ||
| headers.Accept = 'application/json, text/event-stream'; | ||
| } else if (method === 'GET') { | ||
| headers.Accept = 'text/event-stream'; | ||
| } | ||
|
|
||
| if (options?.contentType) { | ||
| headers['Content-Type'] = options.contentType; | ||
| } else if (body) { | ||
| headers['Content-Type'] = 'application/json'; | ||
| } | ||
|
|
||
| if (options?.sessionId) { | ||
| headers['mcp-session-id'] = options.sessionId; | ||
| headers['mcp-protocol-version'] = '2025-11-25'; | ||
| } | ||
|
|
||
| if (options?.extraHeaders) { | ||
| Object.assign(headers, options.extraHeaders); | ||
| } | ||
|
|
||
| return new Request('http://localhost/mcp', { | ||
| method, | ||
| headers, | ||
| body: body ? JSON.stringify(body) : undefined | ||
| }); | ||
| } | ||
|
|
||
| async function readSSEEvent(response: Response): Promise<string> { | ||
| const reader = response.body?.getReader(); | ||
| const { value } = await reader!.read(); | ||
| return new TextDecoder().decode(value); | ||
| } | ||
|
|
||
| function parseSSEData(text: string): unknown { | ||
| const eventLines = text.split('\n'); | ||
| const dataLine = eventLines.find(line => line.startsWith('data:')); | ||
| if (!dataLine) { | ||
| throw new Error('No data line found in SSE event'); | ||
| } | ||
| return JSON.parse(dataLine.slice(5).trim()); | ||
| } | ||
|
|
||
| function expectErrorResponse(data: unknown, expectedCode: number, expectedMessagePattern: RegExp): void { | ||
| expect(data).toMatchObject({ | ||
| jsonrpc: '2.0', | ||
| error: expect.objectContaining({ | ||
| code: expectedCode, | ||
| message: expect.stringMatching(expectedMessagePattern) | ||
| }) | ||
| }); | ||
| } | ||
|
|
||
| describe('WebStandardStreamableHTTPServerTransport session hydration', () => { | ||
| let transport: WebStandardStreamableHTTPServerTransport; | ||
| let mcpServer: McpServer; | ||
|
|
||
| beforeEach(() => { | ||
| mcpServer = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: { logging: {} } }); | ||
|
|
||
| mcpServer.registerTool( | ||
| 'greet', | ||
| { | ||
| description: 'A simple greeting tool', | ||
| inputSchema: z.object({ name: z.string().describe('Name to greet') }) | ||
| }, | ||
| async ({ name }): Promise<CallToolResult> => ({ | ||
| content: [{ type: 'text', text: `Hello, ${name}!` }] | ||
| }) | ||
| ); | ||
| }); | ||
|
|
||
| afterEach(async () => { | ||
| await transport?.close(); | ||
| }); | ||
|
|
||
| async function connectTransport(options?: ConstructorParameters<typeof WebStandardStreamableHTTPServerTransport>[0]) { | ||
| transport = new WebStandardStreamableHTTPServerTransport(options); | ||
| await mcpServer.connect(transport); | ||
| } | ||
|
|
||
| it('processes requests without initialize when constructed with existingSessionId', async () => { | ||
| const sessionId = 'persisted-session-id'; | ||
| await connectTransport({ existingSessionId: sessionId }); | ||
|
|
||
| const response = await transport.handleRequest(createRequest('POST', TEST_MESSAGES.toolsList, { sessionId })); | ||
|
|
||
| expect(response.status).toBe(200); | ||
| expect(response.headers.get('mcp-session-id')).toBe(sessionId); | ||
|
|
||
| const eventData = parseSSEData(await readSSEEvent(response)); | ||
| expect(eventData).toMatchObject({ | ||
| jsonrpc: '2.0', | ||
| result: expect.objectContaining({ | ||
| tools: expect.arrayContaining([ | ||
| expect.objectContaining({ | ||
| name: 'greet', | ||
| description: 'A simple greeting tool' | ||
| }) | ||
| ]) | ||
| }), | ||
| id: 'tools-1' | ||
| }); | ||
| }); | ||
|
|
||
| it('rejects requests with the wrong hydrated session ID', async () => { | ||
| await connectTransport({ existingSessionId: 'persisted-session-id' }); | ||
|
|
||
| const response = await transport.handleRequest(createRequest('POST', TEST_MESSAGES.toolsList, { sessionId: 'wrong-session-id' })); | ||
|
|
||
| expect(response.status).toBe(404); | ||
| expectErrorResponse(await response.json(), -32_001, /Session not found/); | ||
| }); | ||
|
|
||
| it('rejects requests with no hydrated session ID header', async () => { | ||
| await connectTransport({ existingSessionId: 'persisted-session-id' }); | ||
|
|
||
| const response = await transport.handleRequest(createRequest('POST', TEST_MESSAGES.toolsList)); | ||
|
|
||
| expect(response.status).toBe(400); | ||
| const errorData = (await response.json()) as JSONRPCErrorResponse; | ||
| expectErrorResponse(errorData, -32_000, /Mcp-Session-Id header is required/); | ||
| expect(errorData.id).toBeNull(); | ||
| }); | ||
|
|
||
| it('rejects a second initialize attempt for hydrated transports', async () => { | ||
| await connectTransport({ existingSessionId: 'persisted-session-id' }); | ||
|
|
||
| const response = await transport.handleRequest(createRequest('POST', TEST_MESSAGES.initialize)); | ||
|
|
||
| expect(response.status).toBe(400); | ||
| expectErrorResponse(await response.json(), -32_600, /Server already initialized/); | ||
| }); | ||
|
|
||
| it('keeps the default transport behavior unchanged without existingSessionId', async () => { | ||
| await connectTransport({ sessionIdGenerator: () => 'generated-session-id' }); | ||
|
|
||
| const initializeResponse = await transport.handleRequest(createRequest('POST', TEST_MESSAGES.initialize)); | ||
|
|
||
| expect(initializeResponse.status).toBe(200); | ||
| expect(initializeResponse.headers.get('mcp-session-id')).toBe('generated-session-id'); | ||
|
|
||
| const toolsResponse = await transport.handleRequest( | ||
| createRequest('POST', TEST_MESSAGES.toolsList, { sessionId: 'generated-session-id' }) | ||
| ); | ||
|
|
||
| expect(toolsResponse.status).toBe(200); | ||
| const eventData = parseSSEData(await readSSEEvent(toolsResponse)); | ||
| expect(eventData).toMatchObject({ | ||
| jsonrpc: '2.0', | ||
| result: expect.objectContaining({ | ||
| tools: expect.arrayContaining([expect.objectContaining({ name: 'greet' })]) | ||
| }), | ||
| id: 'tools-1' | ||
| }); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 Nit: Passing
existingSessionId: ""(empty string) creates an unusable transport — the constructor accepts it (since"" !== undefined), sets_initialized = trueandsessionId = "", butvalidateSession()treats empty string as falsy viaif (!sessionId), rejecting all subsequent requests with 400. This is a pre-existing pattern (the same issue exists ifsessionIdGeneratorreturns""on line 706), but a simple guard likeif (options.existingSessionId !== undefined && !options.existingSessionId) throw ...would fail fast.Extended reasoning...
What the bug is
The new
existingSessionIdoption is checked withoptions.existingSessionId !== undefined(line 274), which means an empty string""passes the check. The constructor then setsthis.sessionId = "",this._initialized = true, and potentiallythis.sessionIdGenerator = () => "". However, invalidateSession()(line ~891), the checkif (!sessionId)treats the empty string header value as falsy, so the transport rejects all requests with "Mcp-Session-Id header is required" (400). Even if a client sendsmcp-session-id: "", the same falsy check rejects it. The transport is effectively dead on arrival.Why this is pre-existing
The exact same vulnerability exists in the pre-existing code path at line 706: if
sessionIdGeneratorreturns an empty string,this.sessionIdis set to""during the initialize handshake, and subsequent requests fail identically invalidateSession(). This PR simply follows the same pattern — it does not introduce a new class of bug.Step-by-step proof
new WebStandardStreamableHTTPServerTransport({ existingSessionId: "" })"" !== undefinedistrue, sothis.sessionId = "",this._initialized = true,this.sessionIdGenerator = () => ""mcp-session-id: ""headervalidateSession():this.sessionIdGeneratoris defined → continues;this._initializedistrue→ continues;const sessionId = req.headers.get("mcp-session-id")returns"";if (!sessionId)— empty string is falsy → returns 400 errormcp-session-idheader:sessionIdisnull, also falsy → returns 400 errorImpact and fix
The impact is minimal because no reasonable developer would pass an empty string as a session ID — the documentation specifies IDs should be "globally unique and cryptographically secure." A simple defensive guard in the constructor would fail fast:
Ideally, the same validation should be added to
sessionIdGenerator's return value for consistency, but that's outside the scope of this PR.