From e85a6ffb9261bf2c89793b0826089e4cc75baf5c Mon Sep 17 00:00:00 2001 From: trustfundkid Date: Mon, 30 Nov 2026 22:50:29 +0600 Subject: [PATCH] feat(server-initialize): add server-version-echo and server-version-negotiate checks Add lifecycle version negotiation checks to the existing `server-initialize` scenario (following AGENTS.md "fewer scenarios, more checks") for stateful initialize revisions (2025-06-18 through 2025-11-25): - `server-version-echo`: sends a raw `initialize` request with `ctx.specVersion` and verifies the server responds with the exact same `protocolVersion` (MUST). - `server-version-negotiate`: sends a raw `initialize` request with unsupported version `1999-01-01` (omitting `MCP-Protocol-Version` header) and verifies the server responds with a different supported `protocolVersion` rather than an HTTP/JSON-RPC error or echoing `1999-01-01` (MUST; WARNING for unrecognized future `YYYY-MM-DD` revisions to avoid false failures on newer spec releases). - Handles both `application/json` and `text/event-stream` responses, cancelling open SSE streams immediately after the first JSON-RPC response and sending `DELETE` to clean up any issued session. - Adds unit tests in `lifecycle.test.ts` and an end-to-end negative fixture (`examples/servers/typescript/version-negotiation-broken.ts`) verified in `negative.test.ts`. Updates #102 --- .../typescript/version-negotiation-broken.ts | 61 ++++ src/scenarios/server/lifecycle.test.ts | 297 ++++++++++++++--- src/scenarios/server/lifecycle.ts | 5 + src/scenarios/server/negative.test.ts | 39 +++ src/scenarios/server/version-negotiation.ts | 302 ++++++++++++++++++ 5 files changed, 663 insertions(+), 41 deletions(-) create mode 100644 examples/servers/typescript/version-negotiation-broken.ts create mode 100644 src/scenarios/server/version-negotiation.ts diff --git a/examples/servers/typescript/version-negotiation-broken.ts b/examples/servers/typescript/version-negotiation-broken.ts new file mode 100644 index 00000000..3194b86e --- /dev/null +++ b/examples/servers/typescript/version-negotiation-broken.ts @@ -0,0 +1,61 @@ +#!/usr/bin/env node + +/** + * MCP Server with Broken Version Negotiation - Negative Test Case + * + * Blindly echoes whatever protocolVersion the client sends in `initialize`, + * including unsupported versions such as `1999-01-01`. + * + * This server should FAIL the `server-version-negotiate` check in the + * `server-initialize` conformance scenario. + */ + +import express from 'express'; + +const app = express(); +app.use(express.json()); + +app.post('/mcp', (req, res) => { + const body = req.body ?? {}; + const id = body.id ?? null; + + if (body.method === 'initialize') { + const requestedVersion = + typeof body.params?.protocolVersion === 'string' + ? body.params.protocolVersion + : '2025-11-25'; + + // Broken behavior: echo any requested version without checking support. + res.status(200).json({ + jsonrpc: '2.0', + id, + result: { + protocolVersion: requestedVersion, + capabilities: {}, + serverInfo: { + name: 'version-negotiation-broken-server', + version: '1.0.0' + } + } + }); + return; + } + + if (body.method === 'notifications/initialized') { + res.status(202).end(); + return; + } + + res.status(200).json({ + jsonrpc: '2.0', + id, + result: {} + }); +}); + +const PORT = parseInt(process.env.PORT || '3010', 10); +app.listen(PORT, '127.0.0.1', () => { + console.log( + `Broken version negotiation server running on http://localhost:${PORT}/mcp` + ); +}); diff --git a/src/scenarios/server/lifecycle.test.ts b/src/scenarios/server/lifecycle.test.ts index 81835167..a4a51224 100644 --- a/src/scenarios/server/lifecycle.test.ts +++ b/src/scenarios/server/lifecycle.test.ts @@ -11,6 +11,65 @@ vi.mock('../../connection/sdk-client', async (importOriginal) => { }; }); +function jsonInitResponse( + protocolVersion: string, + headers: Record = {} +): Response { + return new Response( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + result: { + protocolVersion, + capabilities: {}, + serverInfo: { name: 'test-server', version: '1.0.0' } + } + }), + { + status: 200, + headers: { + 'content-type': 'application/json', + ...headers + } + } + ); +} + +function sseInitResponse( + protocolVersion: string, + headers: Record = {}, + onCancel?: () => void +): Response { + const payload = JSON.stringify({ + jsonrpc: '2.0', + id: 1, + result: { + protocolVersion, + capabilities: {}, + serverInfo: { name: 'test-server', version: '1.0.0' } + } + }); + const encoder = new TextEncoder(); + const body = new ReadableStream({ + start(controller) { + controller.enqueue( + encoder.encode(`event: message\ndata: ${payload}\n\n`) + ); + // Keep stream open to verify the reader cancels after the first message + }, + cancel() { + onCancel?.(); + } + }); + return new Response(body, { + status: 200, + headers: { + 'content-type': 'text/event-stream', + ...headers + } + }); +} + describe('ServerInitializeScenario', () => { const serverUrl = 'http://localhost:3000/mcp'; const closeMock = vi.fn().mockResolvedValue(undefined); @@ -30,7 +89,10 @@ describe('ServerInitializeScenario', () => { }); it('returns INFO when the server does not provide an MCP-Session-Id header', async () => { - fetchMock.mockResolvedValue(new Response(null)); + fetchMock + .mockResolvedValueOnce(new Response(null)) + .mockResolvedValueOnce(jsonInitResponse('2025-11-25')) + .mockResolvedValueOnce(jsonInitResponse('2025-11-25')); const checks = await new ServerInitializeScenario().run( testContext(serverUrl) @@ -49,7 +111,7 @@ describe('ServerInitializeScenario', () => { }) ); - expect(checks).toHaveLength(2); + expect(checks).toHaveLength(4); expect(checks[0]?.id).toBe('server-initialize'); expect(checks[0]?.status).toBe('SUCCESS'); expect(checks[1]).toMatchObject({ @@ -60,16 +122,33 @@ describe('ServerInitializeScenario', () => { 'Server did not provide an MCP-Session-Id header (session ID is optional)' } }); + expect(checks[2]).toMatchObject({ + id: 'server-version-echo', + status: 'SUCCESS', + details: { + requestedVersion: '2025-11-25', + returnedVersion: '2025-11-25' + } + }); + expect(checks[3]).toMatchObject({ + id: 'server-version-negotiate', + status: 'SUCCESS', + details: { + requestedVersion: '1999-01-01', + returnedVersion: '2025-11-25' + } + }); }); it('returns SUCCESS when the server provides a visible ASCII session ID', async () => { - fetchMock.mockResolvedValue( - new Response(null, { - headers: { - 'mcp-session-id': 'session-123_ABC' - } - }) - ); + fetchMock.mockImplementation(async (_url, init) => { + if ((init as RequestInit | undefined)?.method === 'DELETE') { + return new Response(null); + } + return jsonInitResponse('2025-11-25', { + 'mcp-session-id': 'session-123_ABC' + }); + }); const checks = await new ServerInitializeScenario().run( testContext(serverUrl) @@ -85,13 +164,14 @@ describe('ServerInitializeScenario', () => { }); it('returns FAILURE when the server provides a non-ASCII session ID', async () => { - fetchMock.mockResolvedValue( - new Response(null, { - headers: { - 'mcp-session-id': 'session-123-é' - } - }) - ); + fetchMock.mockImplementation(async (_url, init) => { + if ((init as RequestInit | undefined)?.method === 'DELETE') { + return new Response(null); + } + return jsonInitResponse('2025-11-25', { + 'mcp-session-id': 'session-123-é' + }); + }); const checks = await new ServerInitializeScenario().run( testContext(serverUrl) @@ -108,17 +188,22 @@ describe('ServerInitializeScenario', () => { }); }); - it('sends an HTTP DELETE with the issued session ID to terminate the raw session', async () => { - fetchMock.mockResolvedValue( - new Response(null, { - headers: { - 'mcp-session-id': 'session-123_ABC' - } - }) - ); + it('sends an HTTP DELETE with the issued session ID to terminate raw sessions', async () => { + fetchMock.mockImplementation(async (_url, init) => { + if ((init as RequestInit | undefined)?.method === 'DELETE') { + return new Response(null); + } + return jsonInitResponse('2025-11-25', { + 'mcp-session-id': 'session-123_ABC' + }); + }); await new ServerInitializeScenario().run(testContext(serverUrl)); + const deleteCalls = fetchMock.mock.calls.filter( + ([, init]) => (init as RequestInit | undefined)?.method === 'DELETE' + ); + expect(deleteCalls).toHaveLength(3); expect(fetchMock).toHaveBeenCalledWith( serverUrl, expect.objectContaining({ @@ -131,7 +216,10 @@ describe('ServerInitializeScenario', () => { }); it('does not send DELETE when the server did not assign a session ID', async () => { - fetchMock.mockResolvedValue(new Response(null)); + fetchMock + .mockResolvedValueOnce(new Response(null)) + .mockResolvedValueOnce(jsonInitResponse('2025-11-25')) + .mockResolvedValueOnce(jsonInitResponse('2025-11-25')); await new ServerInitializeScenario().run(testContext(serverUrl)); @@ -141,47 +229,174 @@ describe('ServerInitializeScenario', () => { expect(deleteCalls).toHaveLength(0); }); - it('bounds the session-id probe so a server that never answers cannot hang it', async () => { - fetchMock.mockResolvedValue(new Response(null)); + it('bounds all raw initialize probes with AbortSignal timeouts', async () => { + fetchMock + .mockResolvedValueOnce(new Response(null)) + .mockResolvedValueOnce(jsonInitResponse('2025-11-25')) + .mockResolvedValueOnce(jsonInitResponse('2025-11-25')); await new ServerInitializeScenario().run(testContext(serverUrl)); - const probe = fetchMock.mock.calls.find( + const postCalls = fetchMock.mock.calls.filter( ([, init]) => (init as RequestInit | undefined)?.method === 'POST' ); - expect(probe?.[1]?.signal).toBeInstanceOf(AbortSignal); + expect(postCalls).toHaveLength(3); + for (const [, init] of postCalls) { + expect((init as RequestInit).signal).toBeInstanceOf(AbortSignal); + } }); it('cancels the probe response body so an SSE answer does not leak the connection', async () => { // `Accept` on the probe includes `text/event-stream`, so a server is free // to answer with a stream that stays open. Only the header is read, so the // body has to be released explicitly. - const cancel = vi.fn().mockResolvedValue(undefined); + const cancelSessionProbe = vi.fn().mockResolvedValue(undefined); const body = new ReadableStream({ start() { // Never enqueue, never close: an SSE stream awaiting its first event. }, - cancel + cancel: cancelSessionProbe }); + const cancelEchoStream = vi.fn(); + const cancelNegotiateStream = vi.fn(); - fetchMock.mockResolvedValueOnce( - new Response(body, { - headers: { - 'content-type': 'text/event-stream', - 'mcp-session-id': 'session-123_ABC' - } - }) - ); - fetchMock.mockResolvedValue(new Response(null)); + fetchMock + .mockResolvedValueOnce( + new Response(body, { + headers: { + 'content-type': 'text/event-stream', + 'mcp-session-id': 'session-123_ABC' + } + }) + ) + .mockResolvedValueOnce(new Response(null)) // DELETE for session probe + .mockResolvedValueOnce( + sseInitResponse('2025-11-25', {}, cancelEchoStream) + ) + .mockResolvedValueOnce( + sseInitResponse('2025-11-25', {}, cancelNegotiateStream) + ); const checks = await new ServerInitializeScenario().run( testContext(serverUrl) ); - expect(cancel).toHaveBeenCalled(); + expect(cancelSessionProbe).toHaveBeenCalled(); + expect(cancelEchoStream).toHaveBeenCalled(); + expect(cancelNegotiateStream).toHaveBeenCalled(); expect(checks[1]).toMatchObject({ id: 'server-session-id-visible-ascii', status: 'SUCCESS' }); + expect(checks[2]).toMatchObject({ + id: 'server-version-echo', + status: 'SUCCESS' + }); + expect(checks[3]).toMatchObject({ + id: 'server-version-negotiate', + status: 'SUCCESS' + }); + }); + + it('fails server-version-echo when the server responds with a different version', async () => { + fetchMock + .mockResolvedValueOnce(new Response(null)) + .mockResolvedValueOnce(jsonInitResponse('2025-03-26')) + .mockResolvedValueOnce(jsonInitResponse('2025-11-25')); + + const checks = await new ServerInitializeScenario().run( + testContext(serverUrl, '2025-11-25') + ); + + expect(checks.find((c) => c.id === 'server-version-echo')).toMatchObject({ + status: 'FAILURE', + errorMessage: expect.stringContaining('2025-03-26') + }); + }); + + it('fails server-version-negotiate when the server echoes the unsupported version', async () => { + fetchMock + .mockResolvedValueOnce(new Response(null)) + .mockResolvedValueOnce(jsonInitResponse('2025-11-25')) + .mockResolvedValueOnce(jsonInitResponse('1999-01-01')); + + const checks = await new ServerInitializeScenario().run( + testContext(serverUrl, '2025-11-25') + ); + + expect( + checks.find((c) => c.id === 'server-version-negotiate') + ).toMatchObject({ + status: 'FAILURE', + errorMessage: expect.stringContaining( + 'echoed unsupported protocolVersion' + ) + }); + }); + + it('fails server-version-negotiate when the server returns a JSON-RPC error', async () => { + fetchMock + .mockResolvedValueOnce(new Response(null)) + .mockResolvedValueOnce(jsonInitResponse('2025-11-25')) + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + jsonrpc: '2.0', + id: 3, + error: { code: -32602, message: 'Unsupported protocol version' } + }), + { status: 200, headers: { 'content-type': 'application/json' } } + ) + ); + + const checks = await new ServerInitializeScenario().run( + testContext(serverUrl, '2025-11-25') + ); + + expect( + checks.find((c) => c.id === 'server-version-negotiate') + ).toMatchObject({ + status: 'FAILURE', + errorMessage: expect.stringContaining('JSON-RPC error') + }); + }); + + it('warns on server-version-negotiate when the server returns an unrecognized future YYYY-MM-DD version', async () => { + fetchMock + .mockResolvedValueOnce(new Response(null)) + .mockResolvedValueOnce(jsonInitResponse('2025-11-25')) + .mockResolvedValueOnce(jsonInitResponse('2027-01-15')); + + const checks = await new ServerInitializeScenario().run( + testContext(serverUrl, '2025-11-25') + ); + + expect( + checks.find((c) => c.id === 'server-version-negotiate') + ).toMatchObject({ + status: 'WARNING', + details: { + requestedVersion: '1999-01-01', + returnedVersion: '2027-01-15' + } + }); + }); + + it('fails server-version-negotiate when the server returns a non-date version string', async () => { + fetchMock + .mockResolvedValueOnce(new Response(null)) + .mockResolvedValueOnce(jsonInitResponse('2025-11-25')) + .mockResolvedValueOnce(jsonInitResponse('not-a-version')); + + const checks = await new ServerInitializeScenario().run( + testContext(serverUrl, '2025-11-25') + ); + + expect( + checks.find((c) => c.id === 'server-version-negotiate') + ).toMatchObject({ + status: 'FAILURE', + errorMessage: expect.stringContaining('invalid protocolVersion') + }); }); }); diff --git a/src/scenarios/server/lifecycle.ts b/src/scenarios/server/lifecycle.ts index 85101b22..c0e129ba 100644 --- a/src/scenarios/server/lifecycle.ts +++ b/src/scenarios/server/lifecycle.ts @@ -12,6 +12,7 @@ import { connectToServer, terminateSessionRaw } from '../../connection/sdk-client'; +import { runVersionNegotiationChecks } from './version-negotiation'; const VISIBLE_ASCII_REGEX = /^[\x21-\x7E]+$/; @@ -192,6 +193,10 @@ and validates session ID format if one is assigned.`; } } + checks.push( + ...(await runVersionNegotiationChecks(serverUrl, ctx.specVersion, fetch)) + ); + return checks; } } diff --git a/src/scenarios/server/negative.test.ts b/src/scenarios/server/negative.test.ts index 746cf9ce..9fda9e14 100644 --- a/src/scenarios/server/negative.test.ts +++ b/src/scenarios/server/negative.test.ts @@ -4,6 +4,7 @@ import { createServer, type IncomingMessage, type Server } from 'http'; import type { AddressInfo } from 'net'; import path from 'path'; import { DNSRebindingProtectionScenario } from './dns-rebinding'; +import { ServerInitializeScenario } from './lifecycle'; import { ResourcesNotFoundErrorScenario } from './resources'; import { CachingScenario } from './caching'; import { ToolsListScenario } from './tools'; @@ -519,4 +520,42 @@ describe('Server scenario negative tests', () => { ); }); }); + + describe('server-initialize version negotiation', () => { + let serverProcess: ChildProcess | null = null; + const PORT = 3010; + + beforeAll(async () => { + serverProcess = await startServer( + path.join( + process.cwd(), + 'examples/servers/typescript/version-negotiation-broken.ts' + ), + PORT + ); + }, 35000); + + afterAll(async () => { + await stopServer(serverProcess); + }); + + it('emits FAILURE for server-version-negotiate against a server that blindly echoes unsupported versions', async () => { + const scenario = new ServerInitializeScenario(); + const checks = await scenario.run( + testContext(`http://localhost:${PORT}/mcp`, LATEST_SPEC_VERSION) + ); + + expect(checks.find((c) => c.id === 'server-initialize')?.status).toBe( + 'SUCCESS' + ); + expect(checks.find((c) => c.id === 'server-version-echo')?.status).toBe( + 'SUCCESS' + ); + const negotiate = checks.find((c) => c.id === 'server-version-negotiate'); + expect(negotiate?.status).toBe('FAILURE'); + expect(negotiate?.errorMessage).toContain( + 'echoed unsupported protocolVersion' + ); + }, 10000); + }); }); diff --git a/src/scenarios/server/version-negotiation.ts b/src/scenarios/server/version-negotiation.ts new file mode 100644 index 00000000..31323aa2 --- /dev/null +++ b/src/scenarios/server/version-negotiation.ts @@ -0,0 +1,302 @@ +import { EventSourceParserStream } from 'eventsource-parser/stream'; +import { + ConformanceCheck, + SPEC_VERSION_TIMELINE, + type SpecVersion +} from '../../types'; +import { terminateSessionRaw } from '../../connection/sdk-client'; + +const DATE_VERSION_REGEX = /^\d{4}-\d{2}-\d{2}$/; +const UNSUPPORTED_PROTOCOL_VERSION = '1999-01-01'; +const PROBE_TIMEOUT_MS = 5000; + +const KNOWN_PROTOCOL_VERSIONS: ReadonlySet = new Set([ + '2024-11-05', + ...SPEC_VERSION_TIMELINE +]); + +const VERSION_NEGOTIATION_SPEC_REFERENCES = [ + { + id: 'MCP-Version-Negotiation', + url: 'https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle#version-negotiation' + } +]; + +interface JsonRpcResponse { + result?: Record; + error?: { code?: number; message?: string; data?: unknown }; +} + +function tryParseJsonRpc(raw: string): JsonRpcResponse | null { + const trimmed = raw.trim(); + if (!trimmed) return null; + try { + const parsed: unknown = JSON.parse(trimmed); + if ( + parsed && + typeof parsed === 'object' && + ('result' in parsed || 'error' in parsed) + ) { + return parsed as JsonRpcResponse; + } + } catch { + // Ignore non-JSON payloads (e.g., SSE priming events) + } + return null; +} + +async function readFirstJsonRpcMessage( + response: Response +): Promise { + const contentType = response.headers.get('content-type') ?? ''; + if (contentType.includes('text/event-stream')) { + if (!response.body) return null; + const reader = response.body + .pipeThrough(new TextDecoderStream()) + .pipeThrough(new EventSourceParserStream()) + .getReader(); + try { + while (true) { + const next = await reader['read'](); + if (next.done) return null; + if (!next.value?.data) continue; + const msg = tryParseJsonRpc(next.value.data); + if (msg) return msg; + } + } finally { + await reader.cancel().catch(() => {}); + } + } + + return tryParseJsonRpc(await response.text()); +} + +type FetchFn = (input: string, init?: RequestInit) => Promise; + +function makeCheck( + id: 'server-version-echo' | 'server-version-negotiate', + status: ConformanceCheck['status'], + errorMessage?: string, + details?: Record +): ConformanceCheck { + const isEcho = id === 'server-version-echo'; + return { + id, + name: isEcho ? 'ServerVersionEcho' : 'ServerVersionNegotiate', + description: isEcho + ? 'Server responds with the same protocolVersion when it supports the requested version' + : 'Server responds with a supported protocolVersion when an unsupported version is requested', + status, + timestamp: new Date().toISOString(), + errorMessage, + specReferences: VERSION_NEGOTIATION_SPEC_REFERENCES, + details + }; +} + +function buildInitRequest( + id: number, + protocolVersion: string, + clientName: string +): RequestInit { + return { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream' + }, + body: JSON.stringify({ + jsonrpc: '2.0', + id, + method: 'initialize', + params: { + protocolVersion, + capabilities: {}, + clientInfo: { name: clientName, version: '1.0.0' } + } + }), + signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) + }; +} + +async function checkVersionEcho( + serverUrl: string, + specVersion: SpecVersion, + httpRequest: FetchFn +): Promise { + let sessionId: string | null = null; + try { + const response = await httpRequest( + serverUrl, + buildInitRequest(2, specVersion, 'conformance-version-echo-test') + ); + sessionId = response.headers.get('mcp-session-id'); + + if (!response.ok) { + await response.body?.cancel(); + return makeCheck( + 'server-version-echo', + 'FAILURE', + `Initialize returned HTTP ${response.status} for supported version '${specVersion}'`, + { requestedVersion: specVersion, httpStatus: response.status } + ); + } + + const message = await readFirstJsonRpcMessage(response); + if (message?.error) { + return makeCheck( + 'server-version-echo', + 'FAILURE', + `Server returned JSON-RPC error (${message.error.code ?? 'unknown'}): ${message.error.message ?? 'unknown error'}`, + { requestedVersion: specVersion, error: message.error } + ); + } + + const returnedVersion = + typeof message?.result?.protocolVersion === 'string' + ? message.result.protocolVersion + : undefined; + + if (returnedVersion === specVersion) { + return makeCheck('server-version-echo', 'SUCCESS', undefined, { + requestedVersion: specVersion, + returnedVersion + }); + } + + return makeCheck( + 'server-version-echo', + 'FAILURE', + returnedVersion + ? `Requested protocolVersion '${specVersion}', but server responded with '${returnedVersion}'` + : 'Initialize response did not include a string protocolVersion', + { requestedVersion: specVersion, returnedVersion } + ); + } catch (error) { + return makeCheck( + 'server-version-echo', + 'FAILURE', + `Failed to verify version echo: ${error instanceof Error ? error.message : String(error)}` + ); + } finally { + if (sessionId) { + await terminateSessionRaw(serverUrl, sessionId, specVersion); + } + } +} + +async function checkVersionNegotiate( + serverUrl: string, + specVersion: SpecVersion, + httpRequest: FetchFn +): Promise { + let sessionId: string | null = null; + let cleanupVersion: string = specVersion; + try { + const response = await httpRequest( + serverUrl, + buildInitRequest( + 3, + UNSUPPORTED_PROTOCOL_VERSION, + 'conformance-version-negotiate-test' + ) + ); + sessionId = response.headers.get('mcp-session-id'); + + if (!response.ok) { + await response.body?.cancel(); + return makeCheck( + 'server-version-negotiate', + 'FAILURE', + `Server rejected unsupported protocolVersion '${UNSUPPORTED_PROTOCOL_VERSION}' with HTTP ${response.status} instead of negotiating a supported version`, + { + requestedVersion: UNSUPPORTED_PROTOCOL_VERSION, + httpStatus: response.status + } + ); + } + + const message = await readFirstJsonRpcMessage(response); + if (message?.error) { + return makeCheck( + 'server-version-negotiate', + 'FAILURE', + `Server returned JSON-RPC error (${message.error.code ?? 'unknown'}) instead of negotiating a supported version: ${message.error.message ?? 'unknown error'}`, + { + requestedVersion: UNSUPPORTED_PROTOCOL_VERSION, + error: message.error + } + ); + } + + const returnedVersion = + typeof message?.result?.protocolVersion === 'string' + ? message.result.protocolVersion + : undefined; + if (returnedVersion) { + cleanupVersion = returnedVersion; + } + + if (!returnedVersion) { + return makeCheck( + 'server-version-negotiate', + 'FAILURE', + 'Initialize response did not include a string protocolVersion', + { requestedVersion: UNSUPPORTED_PROTOCOL_VERSION } + ); + } + + if (returnedVersion === UNSUPPORTED_PROTOCOL_VERSION) { + return makeCheck( + 'server-version-negotiate', + 'FAILURE', + `Server echoed unsupported protocolVersion '${UNSUPPORTED_PROTOCOL_VERSION}' instead of responding with a version it supports`, + { requestedVersion: UNSUPPORTED_PROTOCOL_VERSION, returnedVersion } + ); + } + + if (KNOWN_PROTOCOL_VERSIONS.has(returnedVersion)) { + return makeCheck('server-version-negotiate', 'SUCCESS', undefined, { + requestedVersion: UNSUPPORTED_PROTOCOL_VERSION, + returnedVersion + }); + } + + if (DATE_VERSION_REGEX.test(returnedVersion)) { + return makeCheck( + 'server-version-negotiate', + 'WARNING', + `Server negotiated unrecognized date-formatted protocolVersion '${returnedVersion}' (may be a newer spec revision not yet known to this harness)`, + { requestedVersion: UNSUPPORTED_PROTOCOL_VERSION, returnedVersion } + ); + } + + return makeCheck( + 'server-version-negotiate', + 'FAILURE', + `Server returned invalid protocolVersion '${returnedVersion}' during version negotiation`, + { requestedVersion: UNSUPPORTED_PROTOCOL_VERSION, returnedVersion } + ); + } catch (error) { + return makeCheck( + 'server-version-negotiate', + 'FAILURE', + `Failed to verify version negotiation: ${error instanceof Error ? error.message : String(error)}` + ); + } finally { + if (sessionId) { + await terminateSessionRaw(serverUrl, sessionId, cleanupVersion); + } + } +} + +export async function runVersionNegotiationChecks( + serverUrl: string, + specVersion: SpecVersion, + httpRequest: FetchFn +): Promise { + return [ + await checkVersionEcho(serverUrl, specVersion, httpRequest), + await checkVersionNegotiate(serverUrl, specVersion, httpRequest) + ]; +}