diff --git a/src/scenarios/client/initialize.test.ts b/src/scenarios/client/initialize.test.ts new file mode 100644 index 00000000..33c0f7a7 --- /dev/null +++ b/src/scenarios/client/initialize.test.ts @@ -0,0 +1,164 @@ +import { describe, it, expect } from 'vitest'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import { testScenarioContext } from '../../mock-server/testing'; +import { InitializeScenario } from './initialize'; +import { LATEST_SPEC_VERSION } from '../../types'; + +async function postJson( + url: string, + body: object, + headers: Record = {} +): Promise { + return fetch(url, { + method: 'POST', + headers: { + 'content-type': 'application/json', + accept: 'application/json, text/event-stream', + ...headers + }, + body: JSON.stringify(body) + }); +} + +describe('initialize client scenario', () => { + it('passes http-protocol-version-header for a conformant SDK client and is idempotent', async () => { + const scenario = new InitializeScenario(); + const { serverUrl } = await scenario.start(testScenarioContext()); + + try { + const client = new Client( + { name: 'test-client', version: '1.0.0' }, + { capabilities: {} } + ); + const transport = new StreamableHTTPClientTransport(new URL(serverUrl)); + await client.connect(transport); + await client.listTools(); + await transport.close(); + + const first = scenario.getChecks(); + const headerCheck = first.find( + (c) => c.id === 'http-protocol-version-header' + ); + expect(headerCheck).toMatchObject({ + id: 'http-protocol-version-header', + status: 'SUCCESS', + details: { + expectedVersion: LATEST_SPEC_VERSION + } + }); + + const second = scenario.getChecks(); + expect(second).toHaveLength(first.length); + } finally { + await scenario.stop(); + } + }); + + it('fails http-protocol-version-header when a subsequent request omits the header', async () => { + const scenario = new InitializeScenario(); + const { serverUrl } = await scenario.start(testScenarioContext()); + + try { + const initRes = await postJson(serverUrl, { + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: LATEST_SPEC_VERSION, + capabilities: {}, + clientInfo: { name: 'broken-client', version: '1.0.0' } + } + }); + expect(initRes.status).toBe(200); + + const notifyRes = await postJson(serverUrl, { + jsonrpc: '2.0', + method: 'notifications/initialized' + }); + expect(notifyRes.status).toBe(202); + + const headerCheck = scenario + .getChecks() + .find((c) => c.id === 'http-protocol-version-header'); + expect(headerCheck).toMatchObject({ + status: 'FAILURE', + errorMessage: expect.stringContaining( + 'missing MCP-Protocol-Version header' + ) + }); + } finally { + await scenario.stop(); + } + }); + + it('fails http-protocol-version-header when a subsequent request sends the wrong version', async () => { + const scenario = new InitializeScenario(); + const { serverUrl } = await scenario.start(testScenarioContext()); + + try { + await postJson(serverUrl, { + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: LATEST_SPEC_VERSION, + capabilities: {}, + clientInfo: { name: 'mismatch-client', version: '1.0.0' } + } + }); + + await postJson( + serverUrl, + { + jsonrpc: '2.0', + id: 2, + method: 'tools/list', + params: {} + }, + { 'mcp-protocol-version': '2025-03-26' } + ); + + const headerCheck = scenario + .getChecks() + .find((c) => c.id === 'http-protocol-version-header'); + expect(headerCheck).toMatchObject({ + status: 'FAILURE', + errorMessage: expect.stringContaining( + `expected '${LATEST_SPEC_VERSION}', got '2025-03-26'` + ) + }); + } finally { + await scenario.stop(); + } + }); + + it('fails as untestable when no subsequent HTTP request arrives after initialize', async () => { + const scenario = new InitializeScenario(); + const { serverUrl } = await scenario.start(testScenarioContext()); + + try { + await postJson(serverUrl, { + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: LATEST_SPEC_VERSION, + capabilities: {}, + clientInfo: { name: 'early-exit-client', version: '1.0.0' } + } + }); + + const headerCheck = scenario + .getChecks() + .find((c) => c.id === 'http-protocol-version-header'); + expect(headerCheck).toMatchObject({ + status: 'FAILURE', + details: { untestable: true } + }); + expect(headerCheck?.errorMessage).toMatch(/^Not testable: /); + } finally { + await scenario.stop(); + } + }); +}); diff --git a/src/scenarios/client/initialize.ts b/src/scenarios/client/initialize.ts index 99066220..ed7b5f05 100644 --- a/src/scenarios/client/initialize.ts +++ b/src/scenarios/client/initialize.ts @@ -9,6 +9,20 @@ import { DRAFT_PROTOCOL_VERSION } from '../../types'; import { clientChecks } from '../../checks/index'; +import { untestableCheck } from '../untestable'; + +const PROTOCOL_VERSION_HEADER_SPEC_REFS = [ + { + id: 'MCP-Protocol-Version-Header', + url: 'https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#protocol-version-header' + } +]; + +interface PostInitRequestRecord { + httpMethod: string; + rpcMethod?: string; + headerValue: string | undefined; +} export class InitializeScenario implements Scenario { name = 'initialize'; @@ -16,13 +30,20 @@ export class InitializeScenario implements Scenario { introducedIn: '2025-06-18', removedIn: DRAFT_PROTOCOL_VERSION } as const; - description = 'Tests MCP client initialization handshake'; + description = + 'Tests MCP client initialization handshake and MCP-Protocol-Version header on subsequent HTTP requests'; private server: http.Server | null = null; private checks: ConformanceCheck[] = []; + private negotiatedVersion: string | null = null; + private postInitRequests: PostInitRequestRecord[] = []; private port: number = 0; async start(_ctx: ScenarioContext): Promise { + this.checks = []; + this.negotiatedVersion = null; + this.postInitRequests = []; + return new Promise((resolve, reject) => { this.server = http.createServer((req, res) => { this.handleRequest(req, res); @@ -62,13 +83,83 @@ export class InitializeScenario implements Scenario { } getChecks(): ConformanceCheck[] { - return this.checks; + if (!this.negotiatedVersion) { + return [...this.checks]; + } + + return [...this.checks, this.buildProtocolVersionHeaderCheck()]; + } + + private buildProtocolVersionHeaderCheck(): ConformanceCheck { + const expectedVersion = this.negotiatedVersion!; + + if (this.postInitRequests.length === 0) { + return untestableCheck( + 'http-protocol-version-header', + 'HttpProtocolVersionHeader', + 'Client includes MCP-Protocol-Version HTTP header on all subsequent requests after initialization', + 'no subsequent HTTP requests were received after initialize', + PROTOCOL_VERSION_HEADER_SPEC_REFS, + 'FAILURE' + ); + } + + const violations: string[] = []; + for (const record of this.postInitRequests) { + const label = record.rpcMethod + ? `${record.httpMethod} ${record.rpcMethod}` + : record.httpMethod; + if (!record.headerValue) { + violations.push(`${label}: missing MCP-Protocol-Version header`); + } else if (record.headerValue !== expectedVersion) { + violations.push( + `${label}: expected '${expectedVersion}', got '${record.headerValue}'` + ); + } + } + + return { + id: 'http-protocol-version-header', + name: 'HttpProtocolVersionHeader', + description: + 'Client includes MCP-Protocol-Version HTTP header on all subsequent requests after initialization', + status: violations.length === 0 ? 'SUCCESS' : 'FAILURE', + timestamp: new Date().toISOString(), + errorMessage: violations.length > 0 ? violations.join('; ') : undefined, + specReferences: PROTOCOL_VERSION_HEADER_SPEC_REFS, + details: { + expectedVersion, + checkedRequests: this.postInitRequests.length, + ...(violations.length > 0 ? { violations } : {}) + } + }; + } + + private recordPostInitHeader( + req: http.IncomingMessage, + rpcMethod?: string + ): void { + if (!this.negotiatedVersion) return; + const rawHeader = req.headers['mcp-protocol-version']; + const headerValue = Array.isArray(rawHeader) ? rawHeader[0] : rawHeader; + this.postInitRequests.push({ + httpMethod: req.method ?? 'POST', + rpcMethod, + headerValue + }); } private handleRequest( req: http.IncomingMessage, res: http.ServerResponse ): void { + if (req.method === 'GET' || req.method === 'DELETE') { + this.recordPostInitHeader(req); + res.writeHead(405); + res.end(); + return; + } + let body = ''; req.on('data', (chunk) => { @@ -82,14 +173,20 @@ export class InitializeScenario implements Scenario { if (request.method === 'initialize') { this.handleInitialize(request, res); } else if (request.method === 'tools/list') { + this.recordPostInitHeader(req, request.method); this.handleToolsList(request, res); } else if (request.method === 'notifications/initialized') { + this.recordPostInitHeader(req, request.method); // Per MCP spec 2025-11-25 section 2.1 (Sending Messages to the Server), // point 4: "If the input is a JSON-RPC response or notification ... // the server MUST return HTTP status code 202 Accepted with no body." res.writeHead(202); res.end(); } else { + this.recordPostInitHeader( + req, + typeof request.method === 'string' ? request.method : undefined + ); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end( JSON.stringify({ @@ -134,6 +231,8 @@ export class InitializeScenario implements Scenario { ? clientVersion : LATEST_SPEC_VERSION; + this.negotiatedVersion = responseVersion; + const response = { jsonrpc: '2.0', id: request.id,