-
Notifications
You must be signed in to change notification settings - Fork 1.8k
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 1 commit
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
Some comments aren't visible on the classic Files Changed page.
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.
Uh oh!
There was an error while loading. Please reload this page.
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.
using sessionIdGenerator to tell if it's a stateful transport was fine before but its semantic of undefined is bit ambigious now as a transport instance could be created with sessionId set.
I don't have a good idea on top of my head but at least it could be set to () -> sessionId when a sessionId is provided in the constructor.
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.
Good catch — done in the latest commit. When
existingSessionIdis provided and nosessionIdGeneratoris given, we now setthis.sessionIdGenerator = () => existingSessionIdso the stateless check (sessionIdGenerator === undefined) continues to unambiguously distinguish stateful from stateless mode.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.
Thanks! Since the generator is guarenteed in the constructor for stateful semantics, then we should be able to revert this if check back to what it was
if (this.sessionIdGenerator === undefined) {...}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.
Done — reverted to
if (this.sessionIdGenerator === undefined)in the latest commit. Since the constructor now guaranteessessionIdGeneratoris always set whenexistingSessionIdis provided, the single check is sufficient and the extra guard is no longer needed.