|
| 1 | +import type { CallToolResult, JSONRPCErrorResponse, JSONRPCMessage } from '@modelcontextprotocol/core'; |
| 2 | +import { McpServer, Server, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server'; |
| 3 | +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; |
| 4 | +import * as z from 'zod/v4'; |
| 5 | + |
| 6 | +const PROTOCOL_VERSION = '2025-11-25'; |
| 7 | + |
| 8 | +const TEST_MESSAGES = { |
| 9 | + initialize: { |
| 10 | + jsonrpc: '2.0', |
| 11 | + method: 'initialize', |
| 12 | + params: { |
| 13 | + clientInfo: { name: 'test-client', version: '1.0' }, |
| 14 | + protocolVersion: PROTOCOL_VERSION, |
| 15 | + capabilities: {} |
| 16 | + }, |
| 17 | + id: 'init-1' |
| 18 | + } as JSONRPCMessage, |
| 19 | + toolsList: { |
| 20 | + jsonrpc: '2.0', |
| 21 | + method: 'tools/list', |
| 22 | + params: {}, |
| 23 | + id: 'tools-1' |
| 24 | + } as JSONRPCMessage |
| 25 | +}; |
| 26 | + |
| 27 | +function createRequest( |
| 28 | + method: string, |
| 29 | + body?: JSONRPCMessage | JSONRPCMessage[], |
| 30 | + options?: { sessionId?: string; extraHeaders?: Record<string, string> } |
| 31 | +): Request { |
| 32 | + const headers: Record<string, string> = {}; |
| 33 | + |
| 34 | + if (method === 'POST') { |
| 35 | + headers.Accept = 'application/json, text/event-stream'; |
| 36 | + } else if (method === 'GET') { |
| 37 | + headers.Accept = 'text/event-stream'; |
| 38 | + } |
| 39 | + |
| 40 | + if (body) { |
| 41 | + headers['Content-Type'] = 'application/json'; |
| 42 | + } |
| 43 | + |
| 44 | + if (options?.sessionId) { |
| 45 | + headers['mcp-session-id'] = options.sessionId; |
| 46 | + headers['mcp-protocol-version'] = PROTOCOL_VERSION; |
| 47 | + } |
| 48 | + |
| 49 | + if (options?.extraHeaders) { |
| 50 | + Object.assign(headers, options.extraHeaders); |
| 51 | + } |
| 52 | + |
| 53 | + return new Request('http://localhost/mcp', { |
| 54 | + method, |
| 55 | + headers, |
| 56 | + body: body ? JSON.stringify(body) : undefined |
| 57 | + }); |
| 58 | +} |
| 59 | + |
| 60 | +async function readSSEEvent(response: Response): Promise<string> { |
| 61 | + const reader = response.body?.getReader(); |
| 62 | + const { value } = await reader!.read(); |
| 63 | + return new TextDecoder().decode(value); |
| 64 | +} |
| 65 | + |
| 66 | +function parseSSEData(text: string): unknown { |
| 67 | + const dataLine = text.split('\n').find(line => line.startsWith('data:')); |
| 68 | + if (!dataLine) throw new Error('No data line found in SSE event'); |
| 69 | + return JSON.parse(dataLine.slice(5).trim()); |
| 70 | +} |
| 71 | + |
| 72 | +function expectErrorResponse(data: unknown, expectedCode: number, expectedMessagePattern: RegExp): void { |
| 73 | + expect(data).toMatchObject({ |
| 74 | + jsonrpc: '2.0', |
| 75 | + error: expect.objectContaining({ |
| 76 | + code: expectedCode, |
| 77 | + message: expect.stringMatching(expectedMessagePattern) |
| 78 | + }) |
| 79 | + }); |
| 80 | +} |
| 81 | + |
| 82 | +describe('WebStandardStreamableHTTPServerTransport session hydration', () => { |
| 83 | + let transport: WebStandardStreamableHTTPServerTransport; |
| 84 | + let mcpServer: McpServer; |
| 85 | + |
| 86 | + beforeEach(() => { |
| 87 | + mcpServer = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: { logging: {} } }); |
| 88 | + |
| 89 | + mcpServer.registerTool( |
| 90 | + 'greet', |
| 91 | + { |
| 92 | + description: 'A simple greeting tool', |
| 93 | + inputSchema: z.object({ name: z.string().describe('Name to greet') }) |
| 94 | + }, |
| 95 | + async ({ name }): Promise<CallToolResult> => ({ |
| 96 | + content: [{ type: 'text', text: `Hello, ${name}!` }] |
| 97 | + }) |
| 98 | + ); |
| 99 | + }); |
| 100 | + |
| 101 | + afterEach(async () => { |
| 102 | + await transport?.close(); |
| 103 | + }); |
| 104 | + |
| 105 | + async function connectTransport(options?: ConstructorParameters<typeof WebStandardStreamableHTTPServerTransport>[0]) { |
| 106 | + transport = new WebStandardStreamableHTTPServerTransport(options); |
| 107 | + await mcpServer.connect(transport); |
| 108 | + } |
| 109 | + |
| 110 | + describe('transport-layer hydration (sessionId option)', () => { |
| 111 | + it('processes requests without initialize when constructed with sessionId', async () => { |
| 112 | + const sessionId = 'persisted-session-id'; |
| 113 | + await connectTransport({ sessionId }); |
| 114 | + |
| 115 | + const response = await transport.handleRequest(createRequest('POST', TEST_MESSAGES.toolsList, { sessionId })); |
| 116 | + |
| 117 | + expect(response.status).toBe(200); |
| 118 | + expect(response.headers.get('mcp-session-id')).toBe(sessionId); |
| 119 | + |
| 120 | + const eventData = parseSSEData(await readSSEEvent(response)); |
| 121 | + expect(eventData).toMatchObject({ |
| 122 | + jsonrpc: '2.0', |
| 123 | + result: expect.objectContaining({ |
| 124 | + tools: expect.arrayContaining([expect.objectContaining({ name: 'greet' })]) |
| 125 | + }), |
| 126 | + id: 'tools-1' |
| 127 | + }); |
| 128 | + }); |
| 129 | + |
| 130 | + it('rejects requests with a mismatched session ID', async () => { |
| 131 | + await connectTransport({ sessionId: 'persisted-session-id' }); |
| 132 | + |
| 133 | + const response = await transport.handleRequest( |
| 134 | + createRequest('POST', TEST_MESSAGES.toolsList, { sessionId: 'wrong-session-id' }) |
| 135 | + ); |
| 136 | + |
| 137 | + expect(response.status).toBe(404); |
| 138 | + expectErrorResponse(await response.json(), -32_001, /Session not found/); |
| 139 | + }); |
| 140 | + |
| 141 | + it('rejects requests without a session ID header', async () => { |
| 142 | + await connectTransport({ sessionId: 'persisted-session-id' }); |
| 143 | + |
| 144 | + const response = await transport.handleRequest(createRequest('POST', TEST_MESSAGES.toolsList)); |
| 145 | + |
| 146 | + expect(response.status).toBe(400); |
| 147 | + const errorData = (await response.json()) as JSONRPCErrorResponse; |
| 148 | + expectErrorResponse(errorData, -32_000, /Mcp-Session-Id header is required/); |
| 149 | + expect(errorData.id).toBeNull(); |
| 150 | + }); |
| 151 | + |
| 152 | + it('rejects re-initialize on a hydrated transport', async () => { |
| 153 | + await connectTransport({ sessionId: 'persisted-session-id' }); |
| 154 | + |
| 155 | + const response = await transport.handleRequest(createRequest('POST', TEST_MESSAGES.initialize)); |
| 156 | + |
| 157 | + expect(response.status).toBe(400); |
| 158 | + expectErrorResponse(await response.json(), -32_600, /Server already initialized/); |
| 159 | + }); |
| 160 | + |
| 161 | + it('leaves default initialize flow unchanged when sessionId is not provided', async () => { |
| 162 | + await connectTransport({ sessionIdGenerator: () => 'generated-session-id' }); |
| 163 | + |
| 164 | + const initResponse = await transport.handleRequest(createRequest('POST', TEST_MESSAGES.initialize)); |
| 165 | + |
| 166 | + expect(initResponse.status).toBe(200); |
| 167 | + expect(initResponse.headers.get('mcp-session-id')).toBe('generated-session-id'); |
| 168 | + |
| 169 | + const toolsResponse = await transport.handleRequest( |
| 170 | + createRequest('POST', TEST_MESSAGES.toolsList, { sessionId: 'generated-session-id' }) |
| 171 | + ); |
| 172 | + |
| 173 | + expect(toolsResponse.status).toBe(200); |
| 174 | + const eventData = parseSSEData(await readSSEEvent(toolsResponse)); |
| 175 | + expect(eventData).toMatchObject({ |
| 176 | + jsonrpc: '2.0', |
| 177 | + result: expect.objectContaining({ |
| 178 | + tools: expect.arrayContaining([expect.objectContaining({ name: 'greet' })]) |
| 179 | + }), |
| 180 | + id: 'tools-1' |
| 181 | + }); |
| 182 | + }); |
| 183 | + }); |
| 184 | + |
| 185 | + describe('Server.restoreInitializeState', () => { |
| 186 | + it('restores client capabilities without an initialize round-trip', () => { |
| 187 | + const server = new Server({ name: 'test', version: '1.0.0' }, { capabilities: {} }); |
| 188 | + |
| 189 | + expect(server.getClientCapabilities()).toBeUndefined(); |
| 190 | + expect(server.getClientVersion()).toBeUndefined(); |
| 191 | + |
| 192 | + server.restoreInitializeState({ |
| 193 | + protocolVersion: PROTOCOL_VERSION, |
| 194 | + capabilities: { sampling: {}, elicitation: { form: {} } }, |
| 195 | + clientInfo: { name: 'persisted-client', version: '2.0.0' } |
| 196 | + }); |
| 197 | + |
| 198 | + expect(server.getClientCapabilities()).toEqual({ sampling: {}, elicitation: { form: {} } }); |
| 199 | + expect(server.getClientVersion()).toEqual({ name: 'persisted-client', version: '2.0.0' }); |
| 200 | + }); |
| 201 | + |
| 202 | + it('enables capability-gated methods after restoration', async () => { |
| 203 | + const server = new Server({ name: 'test', version: '1.0.0' }, { capabilities: {} }); |
| 204 | + |
| 205 | + // Before restoration, server thinks client has no sampling capability |
| 206 | + expect(server.getClientCapabilities()?.sampling).toBeUndefined(); |
| 207 | + |
| 208 | + server.restoreInitializeState({ |
| 209 | + protocolVersion: PROTOCOL_VERSION, |
| 210 | + capabilities: { sampling: {} }, |
| 211 | + clientInfo: { name: 'c', version: '1' } |
| 212 | + }); |
| 213 | + |
| 214 | + // After restoration, sampling capability is visible |
| 215 | + expect(server.getClientCapabilities()?.sampling).toEqual({}); |
| 216 | + }); |
| 217 | + }); |
| 218 | +}); |
0 commit comments