From 7feab86e08f4415bf5023ab019f6ced559ef3f75 Mon Sep 17 00:00:00 2001 From: Aniket <40296077+aniket-r2Dev2@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:23:23 +0530 Subject: [PATCH] fix(examples): share draft protocol handling across SDK fixtures Fixes modelcontextprotocol/conformance#568 --- .../servers/typescript/everything-server.ts | 110 ++------------ .../typescript/helpers/draft-protocol.test.ts | 142 ++++++++++++++++++ .../typescript/helpers/draft-protocol.ts | 126 ++++++++++++++++ .../servers/typescript/invalid-tool-names.ts | 53 +++++-- .../typescript/no-dns-rebinding-protection.ts | 33 ++++ .../typescript/sep-2106-stripped-schema.ts | 70 ++++++--- src/scenarios/server/negative.test.ts | 59 ++++++++ 7 files changed, 462 insertions(+), 131 deletions(-) create mode 100644 examples/servers/typescript/helpers/draft-protocol.test.ts create mode 100644 examples/servers/typescript/helpers/draft-protocol.ts diff --git a/examples/servers/typescript/everything-server.ts b/examples/servers/typescript/everything-server.ts index c76c1f56..858b11bc 100644 --- a/examples/servers/typescript/everything-server.ts +++ b/examples/servers/typescript/everything-server.ts @@ -37,6 +37,7 @@ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import cors from 'cors'; import { randomUUID, createHmac } from 'crypto'; +import { inspectDraftRequest, sendDraftDiscovery } from './helpers/draft-protocol.js'; // Server state const resourceSubscriptions = new Set(); @@ -1225,16 +1226,6 @@ app.use( }) ); -// Protocol revisions that use the initialize/session lifecycle. The -// per-request `_meta` and header/body validation requirements apply to -// 2026-07-28 and later, not to traffic from these revisions. -const LEGACY_SESSION_PROTOCOL_VERSIONS = [ - '2024-11-05', - '2025-03-26', - '2025-06-18', - '2025-11-25' -]; - // Stateless (draft) operations whose results MUST carry the SEP-2549 caching // hints (`ttlMs`, `cacheScope`). const STATELESS_CACHEABLE_METHODS: ReadonlySet = new Set([ @@ -1276,79 +1267,15 @@ function sendStatelessJson( // Handle POST requests - stateful mode app.post('/mcp', async (req, res) => { const sessionId = req.headers['mcp-session-id'] as string | undefined; - const reqVersion = req.headers['mcp-protocol-version'] as string | undefined; const body = req.body || {}; const method = body.method; const id = body.id ?? null; const params = body.params || {}; const meta = params._meta; - const metaVersion = meta?.['io.modelcontextprotocol/protocolVersion']; - - // A request that carries no `_meta` and names a legacy session-era revision - // in the header is legacy traffic; it is served by the session path below - // instead of being rejected for missing per-request metadata. - const isLegacySessionEraRequest = - meta === undefined && - reqVersion !== undefined && - LEGACY_SESSION_PROTOCOL_VERSIONS.includes(reqVersion); - - if (!sessionId && (reqVersion || meta) && !isLegacySessionEraRequest) { - // Missing Transport Header Validation Check - if (!reqVersion) { - return res.status(400).json({ - jsonrpc: '2.0', - id, - error: { code: -32020, message: 'Missing MCP-Protocol-Version header' } - }); - } - - // Per-Request Metadata Integrity Checks (Fields verification). - // A request missing any required `_meta` field is malformed: -32602 and, - // on HTTP, status 400 Bad Request. `clientInfo` is a SHOULD since spec - // PR #3002 and is never required. - if ( - !meta || - !meta['io.modelcontextprotocol/protocolVersion'] || - !meta['io.modelcontextprotocol/clientCapabilities'] - ) { - return res.status(400).json({ - jsonrpc: '2.0', - id, - error: { - code: -32602, - message: 'Invalid params: missing _meta or required fields' - } - }); - } - - // Header Mismatch Verification (-32020, HTTP 400) - if (reqVersion !== metaVersion) { - return res.status(400).json({ - jsonrpc: '2.0', - id, - error: { - code: -32020, - message: 'Mismatched MCP-Protocol-Version header' - } - }); - } - - // Protocol Version Negotiation Matrix (-32022, HTTP 400) - if (metaVersion !== '2026-07-28') { - return res.status(400).json({ - jsonrpc: '2.0', - id, - error: { - code: -32022, - message: 'UnsupportedProtocolVersionError', - data: { - supported: ['2026-07-28'], - requested: String(metaVersion) - } - } - }); - } + const draftRequest = inspectDraftRequest(req, res); + if (draftRequest.kind === 'rejected') return; + if (draftRequest.kind === 'draft') { // Subscriptions Listening Endpoint Stream Handler (SSE/Chunked Line) if (method === 'subscriptions/listen') { res.writeHead(200, { @@ -1398,27 +1325,18 @@ app.post('/mcp', async (req, res) => { } if (method === 'server/discover') { - return sendStatelessJson(res, method, { - jsonrpc: '2.0', + return sendDraftDiscovery( + res, id, - result: { - supportedVersions: ['2026-07-28'], - capabilities: { - tools: { listChanged: true }, // Explicitly announce dynamic capabilities matching Section 7 expectations - prompts: { listChanged: true }, - // resources/list, resources/templates/list and resources/read are - // served on this path, so the capability must be declared too. - resources: {} - }, - // Spec PR #3002: server identity lives in the result `_meta`. - _meta: { - 'io.modelcontextprotocol/serverInfo': { - name: 'everything-stateless-server', - version: '1.0.0' - } - } + { name: 'everything-stateless-server', version: '1.0.0' }, + { + tools: { listChanged: true }, + prompts: { listChanged: true }, + // resources/list, resources/templates/list and resources/read are + // served on this path, so the capability must be declared too. + resources: {} } - }); + ); } if (method === 'tools/list') { diff --git a/examples/servers/typescript/helpers/draft-protocol.test.ts b/examples/servers/typescript/helpers/draft-protocol.test.ts new file mode 100644 index 00000000..8fefb933 --- /dev/null +++ b/examples/servers/typescript/helpers/draft-protocol.test.ts @@ -0,0 +1,142 @@ +import { describe, expect, it } from 'vitest'; +import type { Request, Response } from 'express'; +import { + inspectDraftRequest, + sendDraftDiscovery, + sendDraftResult +} from './draft-protocol.js'; + +type Sent = { + status: number; + payload?: { + id?: unknown; + result?: Record; + error?: { code: number }; + }; +}; + +function mockRequest( + version: string | undefined, + meta: Record | undefined, + method = 'server/discover', + sessionId?: string +): Request { + return { + headers: { + ...(version ? { 'mcp-protocol-version': version } : {}), + ...(sessionId ? { 'mcp-session-id': sessionId } : {}) + }, + body: { + jsonrpc: '2.0', + id: 7, + method, + params: { ...(meta && { _meta: meta }) } + } + } as unknown as Request; +} + +function mockResponse(): { res: Response; sent: Sent } { + const sent: Sent = { status: 200 }; + const res = { + status(code: number) { + sent.status = code; + return this; + }, + json(payload: Record) { + sent.payload = payload as Sent['payload']; + return this; + } + } as unknown as Response; + return { res, sent }; +} + +const validMeta = { + 'io.modelcontextprotocol/protocolVersion': '2026-07-28', + 'io.modelcontextprotocol/clientCapabilities': {} +}; + +describe('example draft protocol preflight', () => { + it('preserves session-era requests for the official SDK', () => { + expect( + inspectDraftRequest(mockRequest(undefined, undefined), mockResponse().res) + .kind + ).toBe('legacy'); + expect( + inspectDraftRequest( + mockRequest('2025-11-25', undefined), + mockResponse().res + ).kind + ).toBe('legacy'); + expect( + inspectDraftRequest( + mockRequest('2026-07-28', validMeta, 'tools/list', 'session-123'), + mockResponse().res + ).kind + ).toBe('legacy'); + }); + + it('accepts a valid draft request without forwarding it to the v1 SDK', () => { + const { res, sent } = mockResponse(); + expect( + inspectDraftRequest(mockRequest('2026-07-28', validMeta), res) + ).toEqual({ + kind: 'draft', + method: 'server/discover', + id: 7 + }); + expect(sent.payload).toBeUndefined(); + }); + + it.each([ + [undefined, validMeta, -32020], + ['2026-07-28', undefined, -32602], + ['2025-11-25', validMeta, -32020], + [ + '2027-01-01', + { ...validMeta, 'io.modelcontextprotocol/protocolVersion': '2027-01-01' }, + -32022 + ] + ])( + 'rejects invalid draft request with expected JSON-RPC code', + (version, meta, code) => { + const { res, sent } = mockResponse(); + expect(inspectDraftRequest(mockRequest(version, meta), res).kind).toBe( + 'rejected' + ); + expect(sent.status).toBe(400); + expect(sent.payload?.error?.code).toBe(code); + expect(sent.payload?.id).toBe(7); + } + ); + + it('advertises draft version and expected server identity in discover', () => { + const { res, sent } = mockResponse(); + sendDraftDiscovery( + res, + 42, + { name: 'fixture', version: '1.0.0' }, + { tools: {} } + ); + expect(sent.payload?.result).toMatchObject({ + resultType: 'complete', + ttlMs: 0, + cacheScope: 'private', + supportedVersions: ['2026-07-28'], + capabilities: { tools: {} }, + _meta: { + 'io.modelcontextprotocol/serverInfo': { name: 'fixture', version: '1.0.0' } + } + }); + }); + + it('adds required result fields to tools/list responses', () => { + const { res, sent } = mockResponse(); + sendDraftResult(res, 1, { tools: [{ name: 'broken-tool-name' }] }); + expect(sent.payload?.result).toMatchObject({ + resultType: 'complete', + ttlMs: 0, + cacheScope: 'private', + tools: [{ name: 'broken-tool-name' }] + }); + }); +}); diff --git a/examples/servers/typescript/helpers/draft-protocol.ts b/examples/servers/typescript/helpers/draft-protocol.ts new file mode 100644 index 00000000..21b12eea --- /dev/null +++ b/examples/servers/typescript/helpers/draft-protocol.ts @@ -0,0 +1,126 @@ +/** + * Pre-transport support for the draft stateless wire protocol in example servers. + * + * The published v1 SDK is intentionally unaware of 2026-07-28. Detect those + * requests before handing anything to its session-based HTTP transport. + * Keep this aligned with the draft version in src/types.ts. + */ +import type { Request, Response } from 'express'; + +const DRAFT_VERSION = '2026-07-28'; +const LEGACY_VERSIONS = new Set([ + '2024-11-05', + '2025-03-26', + '2025-06-18', + '2025-11-25' +]); + +type DraftRequest = { kind: 'draft'; method: string; id: unknown }; +type RequestClassification = + | DraftRequest + | { kind: 'legacy' } + | { kind: 'rejected' }; + +function reject( + res: Response, + id: unknown, + code: number, + message: string, + data?: Record +): { kind: 'rejected' } { + res.status(400).json({ + jsonrpc: '2.0', + id, + error: { code, message, ...(data ? { data } : {}) } + }); + return { kind: 'rejected' }; +} + +/** + * Classify and validate a POST /mcp request before the SDK transport sees it. + * A legacy request must continue through the normal SDK session path. + * Invalid draft requests are answered here and must not reach the transport. + */ +export function inspectDraftRequest( + req: Request, + res: Response +): RequestClassification { + const body = (req.body ?? {}) as Record; + const id = body.id ?? null; + const method = typeof body.method === 'string' ? body.method : ''; + const params = (body.params ?? {}) as Record; + const meta = params._meta as Record | undefined; + const rawVersion = req.headers['mcp-protocol-version']; + const reqVersion = typeof rawVersion === 'string' ? rawVersion : undefined; + + // An initialized session or a known pre-2026 request uses the SDK's own path. + if (req.headers['mcp-session-id']) return { kind: 'legacy' }; + if (meta === undefined && (!reqVersion || LEGACY_VERSIONS.has(reqVersion))) { + return { kind: 'legacy' }; + } + + if (!reqVersion) { + return reject(res, id, -32020, 'Missing MCP-Protocol-Version header'); + } + const metaVersion = meta?.['io.modelcontextprotocol/protocolVersion']; + if (!metaVersion || !meta?.['io.modelcontextprotocol/clientCapabilities']) { + return reject( + res, + id, + -32602, + 'Invalid params: missing _meta or required fields' + ); + } + if (reqVersion !== metaVersion) { + return reject(res, id, -32020, 'Mismatched MCP-Protocol-Version header'); + } + if (metaVersion !== DRAFT_VERSION) { + return reject(res, id, -32022, 'UnsupportedProtocolVersionError', { + supported: [DRAFT_VERSION], + requested: String(metaVersion) + }); + } + return { kind: 'draft', id, method }; +} + +/** Send a draft result with its result envelope and private, zero-TTL hints. */ +export function sendDraftResult( + res: Response, + id: unknown, + result: Record +): Response { + return res.json({ + jsonrpc: '2.0', + id, + result: { + ...result, + resultType: 'complete', + ttlMs: 0, + cacheScope: 'private' + } + }); +} + +export function sendDraftDiscovery( + res: Response, + id: unknown, + serverInfo: { name: string; version: string }, + capabilities: Record +): Response { + return sendDraftResult(res, id, { + supportedVersions: [DRAFT_VERSION], + capabilities, + _meta: { 'io.modelcontextprotocol/serverInfo': serverInfo } + }); +} + +/** + * Minimal negative fixtures do not implement other draft methods. + */ +export function sendDraftMethodNotFound(res: Response, id: unknown): Response { + return res.status(404).json({ + jsonrpc: '2.0', + id, + error: { code: -32601, message: 'Method not found' } + }); +} diff --git a/examples/servers/typescript/invalid-tool-names.ts b/examples/servers/typescript/invalid-tool-names.ts index a71925d9..14473c52 100644 --- a/examples/servers/typescript/invalid-tool-names.ts +++ b/examples/servers/typescript/invalid-tool-names.ts @@ -8,8 +8,30 @@ import { Server } from '@modelcontextprotocol/sdk/server/index.js'; import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; -import { ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'; +import { + ListToolsRequestSchema, + type ListToolsResult +} from '@modelcontextprotocol/sdk/types.js'; import express from 'express'; +import { + inspectDraftRequest, + sendDraftDiscovery, + sendDraftMethodNotFound, + sendDraftResult +} from './helpers/draft-protocol.js'; + +const TOOL_CATALOG: ListToolsResult['tools'] = [ + { + name: 'bad tool name', + description: 'Deliberately invalid tool name for conformance testing', + inputSchema: { type: 'object' } + }, + { + name: 'valid_tool', + description: 'A conformant tool name', + inputSchema: { type: 'object' } + } +]; function createServer() { const server = new Server( @@ -18,18 +40,7 @@ function createServer() { ); server.setRequestHandler(ListToolsRequestSchema, async () => ({ - tools: [ - { - name: 'bad tool name', - description: 'Deliberately invalid tool name for conformance testing', - inputSchema: { type: 'object' } - }, - { - name: 'valid_tool', - description: 'A conformant tool name', - inputSchema: { type: 'object' } - } - ] + tools: TOOL_CATALOG })); return server; @@ -40,6 +51,22 @@ app.use(express.json()); app.post('/mcp', async (req, res) => { try { + const draft = inspectDraftRequest(req, res); + if (draft.kind === 'rejected') return; + if (draft.kind === 'draft') { + if (draft.method === 'server/discover') { + return sendDraftDiscovery( + res, + draft.id, + { name: 'invalid-tool-names', version: '1.0.0' }, + { tools: {} } + ); + } + if (draft.method === 'tools/list') { + return sendDraftResult(res, draft.id, { tools: TOOL_CATALOG }); + } + return sendDraftMethodNotFound(res, draft.id); + } const server = createServer(); const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined diff --git a/examples/servers/typescript/no-dns-rebinding-protection.ts b/examples/servers/typescript/no-dns-rebinding-protection.ts index 1e0fc3c6..d9f021c1 100644 --- a/examples/servers/typescript/no-dns-rebinding-protection.ts +++ b/examples/servers/typescript/no-dns-rebinding-protection.ts @@ -12,6 +12,12 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; import express from 'express'; +import { + inspectDraftRequest, + sendDraftDiscovery, + sendDraftMethodNotFound, + sendDraftResult +} from './helpers/draft-protocol.js'; // Create a fresh MCP server per request to avoid "Already connected" errors // after the v1.26.0 security fix (GHSA-345p-7cg4-v4c7) @@ -43,6 +49,33 @@ app.use(express.json()); app.post('/mcp', async (req, res) => { try { + const draft = inspectDraftRequest(req, res); + if (draft.kind === 'rejected') return; + if (draft.kind === 'draft') { + if (draft.method === 'server/discover') { + return sendDraftDiscovery( + res, + draft.id, + { name: 'no-dns-rebinding-protection-server', version: '1.0.0' }, + { tools: {} } + ); + } + if (draft.method === 'tools/list') { + return sendDraftResult(res, draft.id, { + tools: [ + { + name: 'echo', + description: 'Echo the input back', + inputSchema: { + type: 'object', + properties: { message: { type: 'string' } } + } + } + ] + }); + } + return sendDraftMethodNotFound(res, draft.id); + } const server = createMcpServer(); // Stateless: no session ID const transport = new StreamableHTTPServerTransport({ diff --git a/examples/servers/typescript/sep-2106-stripped-schema.ts b/examples/servers/typescript/sep-2106-stripped-schema.ts index 30da6241..fbc33d2b 100644 --- a/examples/servers/typescript/sep-2106-stripped-schema.ts +++ b/examples/servers/typescript/sep-2106-stripped-schema.ts @@ -15,8 +15,38 @@ import { Server } from '@modelcontextprotocol/sdk/server/index.js'; import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; -import { ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'; +import { + ListToolsRequestSchema, + type ListToolsResult +} from '@modelcontextprotocol/sdk/types.js'; import express from 'express'; +import { + inspectDraftRequest, + sendDraftDiscovery, + sendDraftMethodNotFound, + sendDraftResult +} from './helpers/draft-protocol.js'; + +const TOOL_CATALOG: ListToolsResult['tools'] = [ + { + name: 'json_schema_2020_12_tool', + description: 'Tool whose JSON Schema 2020-12 keywords have been stripped', + // Stripped: only type + plain properties survive. + inputSchema: { + type: 'object', + properties: { + name: { type: 'string' }, + address: { + type: 'object', + properties: { + street: { type: 'string' }, + city: { type: 'string' } + } + } + } + } + } +]; function createServer() { const server = new Server( @@ -25,27 +55,7 @@ function createServer() { ); server.setRequestHandler(ListToolsRequestSchema, async () => ({ - tools: [ - { - name: 'json_schema_2020_12_tool', - description: - 'Tool whose JSON Schema 2020-12 keywords have been stripped', - // Stripped: only type + plain properties survive. - inputSchema: { - type: 'object', - properties: { - name: { type: 'string' }, - address: { - type: 'object', - properties: { - street: { type: 'string' }, - city: { type: 'string' } - } - } - } - } - } - ] + tools: TOOL_CATALOG })); return server; @@ -56,6 +66,22 @@ app.use(express.json()); app.post('/mcp', async (req, res) => { try { + const draft = inspectDraftRequest(req, res); + if (draft.kind === 'rejected') return; + if (draft.kind === 'draft') { + if (draft.method === 'server/discover') { + return sendDraftDiscovery( + res, + draft.id, + { name: 'sep-2106-stripped-schema', version: '1.0.0' }, + { tools: {} } + ); + } + if (draft.method === 'tools/list') { + return sendDraftResult(res, draft.id, { tools: TOOL_CATALOG }); + } + return sendDraftMethodNotFound(res, draft.id); + } const server = createServer(); const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined diff --git a/src/scenarios/server/negative.test.ts b/src/scenarios/server/negative.test.ts index 746cf9ce..b5955376 100644 --- a/src/scenarios/server/negative.test.ts +++ b/src/scenarios/server/negative.test.ts @@ -118,6 +118,30 @@ describe('Server scenario negative tests', () => { await stopServer(serverProcess); }); + it('speaks draft discover and tools/list without adding DNS protection', async () => { + const conn = await testContext( + `http://localhost:${PORT}/mcp`, + DRAFT_PROTOCOL_VERSION + ).connect(); + try { + const discovery = await conn.discover(); + expect(discovery.supportedVersions).toContain(DRAFT_PROTOCOL_VERSION); + const result = await conn.request<{ tools: Array<{ name: string }> }>( + 'tools/list' + ); + expect(result.tools.map((tool) => tool.name)).toContain('echo'); + } finally { + await conn.close(); + } + const checks = await new DNSRebindingProtectionScenario().run( + testContext(`http://localhost:${PORT}/mcp`, DRAFT_PROTOCOL_VERSION) + ); + expect( + checks.find((check) => check.id === 'localhost-host-rebinding-rejected') + ?.status + ).toBe('FAILURE'); + }, 10000); + it('emits FAILURE against a server without rebinding protection', async () => { const scenario = new DNSRebindingProtectionScenario(); const checks = await scenario.run( @@ -396,6 +420,24 @@ describe('Server scenario negative tests', () => { await stopServer(serverProcess); }); + it('speaks draft discover and preserves the intentionally stripped schema', async () => { + const conn = await testContext( + `http://localhost:${PORT}/mcp`, + DRAFT_PROTOCOL_VERSION + ).connect(); + try { + const discovery = await conn.discover(); + expect(discovery.supportedVersions).toContain(DRAFT_PROTOCOL_VERSION); + const result = await conn.request<{ + tools: Array<{ name: string; inputSchema: Record }>; + }>('tools/list'); + expect(result.tools[0]?.name).toBe('json_schema_2020_12_tool'); + expect(result.tools[0]?.inputSchema).not.toHaveProperty('$schema'); + } finally { + await conn.close(); + } + }, 10000); + it('flags SEP-2106 keyword-preservation checks against a server that strips the 2020-12 vocabulary', async () => { const scenario = new JsonSchema2020_12Scenario(); const checks = await scenario.run( @@ -483,6 +525,23 @@ describe('Server scenario negative tests', () => { await stopServer(serverProcess); }); + it('speaks draft discover and still advertises invalid tool names', async () => { + const conn = await testContext( + `http://localhost:${PORT}/mcp`, + DRAFT_PROTOCOL_VERSION + ).connect(); + try { + const discovery = await conn.discover(); + expect(discovery.supportedVersions).toContain(DRAFT_PROTOCOL_VERSION); + const result = await conn.request<{ tools: Array<{ name: string }> }>( + 'tools/list' + ); + expect(result.tools.map((tool) => tool.name)).toContain('bad tool name'); + } finally { + await conn.close(); + } + }, 10000); + it('emits WARNING for tools-name-format against a server advertising invalid tool names', async () => { const scenario = new ToolsListScenario(); const checks = await scenario.run(