:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp): stateless protocol alongside legacy dialect (#72223)
Georgiy Tarasovb9db384b3be7
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a67e3c087398..6ccb80c168f5 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -507,7 +507,7 @@ importers:version: 5.3.0jest-image-snapshot:specifier: ^6.4.0- version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))+ version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))mockdate:specifier: ^3.0.5version: 3.0.5@@ -1928,7 +1928,7 @@ importers:version: 3.6.0jest-image-snapshot:specifier: ^6.4.0- version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))+ version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))storybook:specifier: 'catalog:'version: 10.4.6(@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])@@ -2675,7 +2675,7 @@ importers:version: 8.57.0jest:specifier: '*'- version: 30.0.5([email protected]([email protected]))+ version: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))kea:specifier: 'catalog:'version: 4.0.0-pre.6([email protected])@@ -3499,7 +3499,7 @@ importers:version: 2.1.1jest:specifier: '*'- version: 30.0.5([email protected]([email protected]))+ version: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))kea:specifier: 'catalog:'version: 4.0.0-pre.6([email protected])@@ -4515,7 +4515,7 @@ importers:version: 1.2.1jest:specifier: '*'- version: 30.0.5([email protected]([email protected]))+ version: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))kea:specifier: 'catalog:'version: 4.0.0-pre.6([email protected])@@ -4845,6 +4845,9 @@ importers:'@cloudflare/workers-types':specifier: ^4.20260603.1version: 4.20260608.1+ '@modelcontextprotocol/client':+ specifier: 2.0.0-beta.4+ version: 2.0.0-beta.4'@posthog/openapi-codegen':specifier: workspace:*version: link:../../tools/openapi-codegen@@ -8319,6 +8322,14 @@ packages:'@mistralai/[email protected]':resolution: {integrity: sha512-uKU8CZmL2RzYKmplsU01hii4p3pe4HqJefpWNRWXm1Tcm0Sm4xXfwSLIy4k7ZCPlbETCGcp69E7hZs+WOJ5itQ==}+ '@modelcontextprotocol/[email protected]':+ resolution: {integrity: sha512-VNHA/UXDk7mCpVl+jOg5B4WMRRD2OEl+it360Lhi6HiCbrIB2f6pZ0cqSDKXQVUtZvqnhdQHzZAM9h8EKWhq/A==}+ engines: {node: '>=20'}++ '@modelcontextprotocol/[email protected]':+ resolution: {integrity: sha512-nsMXd4wQBKzmph6r+WOhum+mXjDYljTAqwY/XUg3hLtvNOQ8+JVqBSJOVCMJvx9lXhTpTOPrGZ3BuNiaNPjSvg==}+ engines: {node: '>=20'}+'@modelcontextprotocol/[email protected]':resolution: {integrity: sha512-j80Hv9kSALu7luR+DtoYERlRaehu6cY2wlHEjG3h36C98bbYzA/nxOEvtGhhKd2ssCwC0BG3+gdh7y3sE5m0tQ==}engines: {node: '>=20'}@@ -27086,7 +27097,7 @@ snapshots:- supports-color- ts-node+ '@jest/[email protected]([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))':dependencies:'@jest/console': 30.0.5'@jest/pattern': 30.0.1@@ -27101,7 +27112,7 @@ snapshots:exit-x: 0.2.2graceful-fs: 4.2.11jest-changed-files: 30.0.5+ jest-config: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-haste-map: 30.0.5jest-message-util: 30.0.5jest-regex-util: 30.0.1@@ -27122,7 +27133,7 @@ snapshots:- supports-color- ts-node- '@jest/[email protected]([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))':+ '@jest/[email protected]([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))':dependencies:'@jest/console': 30.0.5'@jest/pattern': 30.0.1@@ -27137,7 +27148,7 @@ snapshots:exit-x: 0.2.2graceful-fs: 4.2.11jest-changed-files: 30.0.5- jest-config: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ jest-config: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-haste-map: 30.0.5jest-message-util: 30.0.5jest-regex-util: 30.0.1@@ -27952,6 +27963,20 @@ snapshots:- bufferutil- utf-8-validate+ '@modelcontextprotocol/[email protected]':+ dependencies:+ '@modelcontextprotocol/core': 2.0.0-beta.4+ cross-spawn: 7.0.6+ eventsource: 3.0.7+ eventsource-parser: 3.0.6+ jose: 6.2.3+ pkce-challenge: 5.0.0+ zod: 4.3.6++ '@modelcontextprotocol/[email protected]':+ dependencies:+ zod: 4.3.6+'@modelcontextprotocol/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected])':dependencies:'@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])@@ -38356,15 +38381,15 @@ snapshots:- supports-color- ts-node- [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:- '@jest/core': 30.0.5([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ '@jest/core': 30.0.5([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))'@jest/test-result': 30.0.5'@jest/types': 30.0.5chalk: 4.1.2exit-x: 0.2.2import-local: 3.2.0- jest-config: 30.0.5(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ jest-config: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-util: 30.0.5jest-validate: 30.0.5yargs: 17.7.2@@ -38375,15 +38400,15 @@ snapshots:- supports-color- ts-node+ [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:- '@jest/core': 30.0.5([email protected]([email protected]))+ '@jest/core': 30.0.5([email protected](@swc/[email protected])(@types/[email protected])([email protected]))'@jest/test-result': 30.0.5'@jest/types': 30.0.5chalk: 4.1.2exit-x: 0.2.2import-local: 3.2.0- jest-config: 30.0.5([email protected]([email protected]))+ jest-config: 30.0.5(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-util: 30.0.5jest-validate: 30.0.5yargs: 17.7.2@@ -38521,7 +38546,7 @@ snapshots:- babel-plugin-macros- supports-color+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@babel/core': 7.29.0'@jest/get-type': 30.0.1@@ -38550,11 +38575,12 @@ snapshots:optionalDependencies:'@types/node': 22.18.8esbuild-register: 3.6.0([email protected])transitivePeerDependencies:- babel-plugin-macros- supports-color- [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@babel/core': 7.29.0'@jest/get-type': 30.0.1@@ -38583,7 +38609,7 @@ snapshots:optionalDependencies:'@types/node': 22.18.8esbuild-register: 3.6.0([email protected])transitivePeerDependencies:- babel-plugin-macros- supports-color@@ -38621,7 +38647,7 @@ snapshots:- babel-plugin-macros- supports-color- [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@babel/core': 7.29.0'@jest/get-type': 30.0.1@@ -38649,12 +38675,13 @@ snapshots:strip-json-comments: 3.1.1optionalDependencies:'@types/node': 25.8.0+ esbuild-register: 3.6.0([email protected])transitivePeerDependencies:- babel-plugin-macros- supports-color+ [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@babel/core': 7.29.0'@jest/get-type': 30.0.1@@ -38681,7 +38708,8 @@ snapshots:slash: 3.0.0strip-json-comments: 3.1.1optionalDependencies:- esbuild-register: 3.6.0([email protected])+ '@types/node': 25.8.0transitivePeerDependencies:- babel-plugin-macros- supports-color@@ -39576,12 +39604,12 @@ snapshots:- supports-color- ts-node- [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:- '@jest/core': 30.0.5([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ '@jest/core': 30.0.5([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))'@jest/types': 30.0.5import-local: 3.2.0- jest-cli: 30.0.5(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ jest-cli: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))transitivePeerDependencies:- '@types/node'- babel-plugin-macros@@ -39589,12 +39617,12 @@ snapshots:- supports-color- ts-node+ [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:- '@jest/core': 30.0.5([email protected]([email protected]))+ '@jest/core': 30.0.5([email protected](@swc/[email protected])(@types/[email protected])([email protected]))'@jest/types': 30.0.5import-local: 3.2.0- jest-cli: 30.0.5([email protected]([email protected]))+ jest-cli: 30.0.5(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))transitivePeerDependencies:- '@types/node'- babel-plugin-macrosdiff --git a/services/mcp/ARCHITECTURE.md b/services/mcp/ARCHITECTURE.mdindex 250854f015cc..3c64b72b8963 100644--- a/services/mcp/ARCHITECTURE.md+++ b/services/mcp/ARCHITECTURE.md@@ -24,6 +24,15 @@ flowchart TBThe Worker no longer serves the protocol itself — an earlier iteration ran a stateful Cloudflare Durable Object (`mcp.ts`) for this, but that has been removed in favor of always proxying to Hono.+### Protocol dialects: legacy stateful and 2026-07-28 stateless++The Hono dispatcher serves both MCP dialects side by side (`src/lib/stateless-protocol.ts` holds the shared constants):++- **Legacy (≤2025-11-25)**: the `initialize` handshake negotiates a protocol version, the server mints an `Mcp-Session-Id`, and clients echo it on subsequent requests. Unchanged wire shape.+- **Stateless (2026-07-28, SEP-2575)**: no handshake and no protocol-level sessions. Each request self-describes via reserved `_meta` keys (`io.modelcontextprotocol/protocolVersion`, `.../clientInfo`, `.../clientCapabilities` — the first is the dialect switch, all three are mandatory and missing ones are rejected with `-32602` + HTTP 400); capability discovery happens through the mandatory `server/discover` RPC (capabilities + `serverInfo` + instructions + `supportedVersions`). Results carry `resultType: "complete"`, the server's identity in `_meta` (`io.modelcontextprotocol/serverInfo`), and — for `CacheableResult` methods (`server/discover`, `tools/list`, `resources/list`, `resources/read`, `prompts/list`) — `ttlMs`/`cacheScope: "private"` freshness hints. The TTL is nonzero in production only — locally `ttlMs: 0` (the spec-compliant "don't cache") keeps SDK client response caches from serving stale results while iterating on tool definitions.++A request's dialect is detected per request from the `_meta` protocol-version key or a modern `MCP-Protocol-Version` header. Only modern versions (2026-07-28+) are valid there — legacy versions are implemented solely behind the `initialize` handshake, so `server/discover` advertises modern versions only, and a legacy or unknown `_meta` version is rejected with `UnsupportedProtocolVersionError` (`-32022` on HTTP 400, with the spec's machine-readable `data.supported`/`data.requested` payload). Modern requests must also carry SEP-2243's operation headers — `MCP-Protocol-Version` (mirroring `_meta`), `Mcp-Method` (mirroring the body `method`), and `Mcp-Name` (mirroring `params.name`/`params.uri` on `tools/call`, `prompts/get`, `resources/read`) — so intermediaries can route without parsing bodies; a missing or contradicting header is rejected with `HeaderMismatch` (`-32020`) + HTTP 400 before dispatch. Modern messages are also barred from JSON-RPC arrays (`-32600` + 400; batching was removed from the protocol in 2025-06-18), and RPCs the modern dialect removed (`initialize`, `ping`) answer method-not-found on HTTP 404. Legacy clients are untouched by all of this: header-free requests — including ones sending a legacy `MCP-Protocol-Version` value such as `2025-06-18` — keep the exact pre-existing wire behavior (HTTP 200 with errors in the JSON-RPC body). Client identity for analytics is read from the `initialize` body for legacy clients and from per-request `_meta` for stateless clients. Stateless requests never mint or echo `Mcp-Session-Id` — cross-request correlation for that traffic relies on `mcpConversationId` (see below).+## File Structure```txtdiff --git a/services/mcp/package.json b/services/mcp/package.jsonindex a7ec62fe00dc..267accef4038 100644--- a/services/mcp/package.json+++ b/services/mcp/package.json@@ -74,6 +74,7 @@"devDependencies": {"@cloudflare/vitest-pool-workers": "^0.16.13","@cloudflare/workers-types": "^4.20260603.1",+ "@modelcontextprotocol/client": "2.0.0-beta.4","@posthog/openapi-codegen": "workspace:*","@tailwindcss/postcss": "^4.1.10","@types/dotenv": "^6.1.1",diff --git a/services/mcp/scripts/stateless-smoke/legacy-smoke.mts b/services/mcp/scripts/stateless-smoke/legacy-smoke.mtsnew file mode 100644index 000000000000..3d2a51344bfc--- /dev/null+++ b/services/mcp/scripts/stateless-smoke/legacy-smoke.mts@@ -0,0 +1,117 @@+// Smoke-tests the PostHog MCP server's legacy dialect (≤2025-11-25) — the+// `initialize`-handshake protocol that every stable client (Claude, Cursor,+// VS Code, ChatGPT) speaks today — using the stable v1 SDK+// (@modelcontextprotocol/sdk, resolved from services/mcp/node_modules).+// The server implements this dialect statelessly, so beyond the SDK round+// trip this also proves requests survive without session affinity and that+// legacy results keep their exact pre-stateless wire shape (no `resultType`,+// no `_meta` server identity leaking across dialects).+//+// Usage: POSTHOG_PERSONAL_API_KEY=phx_... MCP_URL=http://localhost:8787/mcp \+// ../../node_modules/.bin/tsx legacy-smoke.mts+import { Client } from '@modelcontextprotocol/sdk/client/index.js'+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'+import { LATEST_PROTOCOL_VERSION } from '@modelcontextprotocol/sdk/types.js'++const MCP_URL = process.env.MCP_URL ?? 'http://localhost:8787/mcp'+const TOKEN = process.env.POSTHOG_PERSONAL_API_KEY+const STATELESS_VERSION = '2026-07-28'+const META_SERVER_INFO = 'io.modelcontextprotocol/serverInfo'++if (!TOKEN) {+ console.error('POSTHOG_PERSONAL_API_KEY is required')+ process.exit(1)+}++let failures = 0++function check(name: string, ok: boolean, detail?: string): void {+ failures += ok ? 0 : 1+ console.info(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`)+}++interface RpcEnvelope {+ result?: Record<string, unknown> & { _meta?: Record<string, unknown> }+ error?: { code?: number; message?: string }+}++async function rawPost(+ method: string,+ params: Record<string, unknown>+): Promise<{ response: Response; json: RpcEnvelope }> {+ const response = await fetch(MCP_URL, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${TOKEN}`,+ 'Content-Type': 'application/json',+ Accept: 'application/json, text/event-stream',+ 'x-posthog-mcp-mode': 'tools',+ },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),+ })+ return { response, json: (await response.json()) as RpcEnvelope }+}++// 1) Stable-SDK handshake: `initialize` negotiates a legacy version.+const transport = new StreamableHTTPClientTransport(new URL(MCP_URL), {+ requestInit: { headers: { Authorization: `Bearer ${TOKEN}`, 'x-posthog-mcp-mode': 'tools' } },+})+const client = new Client({ name: 'posthog-legacy-smoke', version: '0.0.1' }, { capabilities: {} })+await client.connect(transport)+check(+ 'initialize negotiates a legacy version',+ transport.protocolVersion !== undefined && transport.protocolVersion !== STATELESS_VERSION,+ `negotiated=${transport.protocolVersion}`+)+check(+ 'server identity from initialize',+ client.getServerVersion()?.name !== undefined,+ JSON.stringify(client.getServerVersion())+)++// 2) tools/list + a real tool call over the legacy dialect.+const tools = await client.listTools()+check('tools/list returns tools', tools.tools.length > 0, `${tools.tools.length} tools`)+const orgTool = tools.tools.find((t) => t.name === 'organization-get') ?? tools.tools[0]!+const result = await client.callTool({ name: orgTool.name, arguments: {} })+check(+ `tools/call ${orgTool.name}`,+ !result.isError,+ ((result.content as Array<{ text?: string }> | undefined)?.[0]?.text ?? '').slice(0, 80)+)+await client.close()++// 3) Wire-shape guard: legacy results must keep the pre-stateless shape —+// the 2026-07-28 decoration (`resultType`, `_meta` server identity) must+// not leak into a request that carries no `_meta` protocol version.+const legacyList = await rawPost('tools/list', {})+check(+ 'legacy result carries no stateless decoration',+ legacyList.json.result !== undefined &&+ !('resultType' in legacyList.json.result) &&+ legacyList.json.result._meta?.[META_SERVER_INFO] === undefined+)++// 4) Fallback negotiation: an unknown requested version is answered with the+// newest legacy version, not an error (spec fallback behavior).+const fallback = await rawPost('initialize', {+ protocolVersion: '1999-01-01',+ capabilities: {},+ clientInfo: { name: 'posthog-legacy-smoke', version: '0.0.1' },+})+check(+ 'unknown initialize version falls back to newest legacy version',+ fallback.json.result?.protocolVersion === LATEST_PROTOCOL_VERSION,+ `answered=${String(fallback.json.result?.protocolVersion)}`+)++// 5) Stateless serving of the legacy dialect: a request on a fresh connection+// with no prior initialize and no session id must still be served.+const bare = await rawPost('tools/list', {})+check(+ 'legacy request without handshake or session id is served',+ bare.response.status === 200 && bare.json.error === undefined && Array.isArray(bare.json.result?.tools)+)++console.info(failures === 0 ? '\nAll checks passed' : `\n${failures} check(s) failed`)+process.exit(failures === 0 ? 0 : 1)diff --git a/services/mcp/scripts/stateless-smoke/stateless-smoke.mts b/services/mcp/scripts/stateless-smoke/stateless-smoke.mtsnew file mode 100644index 000000000000..f7ffe6a0e366--- /dev/null+++ b/services/mcp/scripts/stateless-smoke/stateless-smoke.mts@@ -0,0 +1,107 @@+// Smoke-tests the PostHog MCP server's 2026-07-28 stateless dialect using the+// official beta client SDK (@modelcontextprotocol/client v2). The version is+// pinned so the SDK refuses to fall back to the legacy `initialize` handshake:+// every request must carry `_meta` protocol identity and succeed statelessly.+//+// Usage: POSTHOG_PERSONAL_API_KEY=phx_... MCP_URL=http://localhost:8787/mcp \+// ../../node_modules/.bin/tsx stateless-smoke.mts+import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'++const MCP_URL = process.env.MCP_URL ?? 'http://localhost:8787/mcp'+const TOKEN = process.env.POSTHOG_PERSONAL_API_KEY+const STATELESS_VERSION = '2026-07-28'+const META_SERVER_INFO = 'io.modelcontextprotocol/serverInfo'++if (!TOKEN) {+ console.error('POSTHOG_PERSONAL_API_KEY is required')+ process.exit(1)+}++let failures = 0++function check(name: string, ok: boolean, detail?: string): void {+ failures += ok ? 0 : 1+ console.info(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`)+}++function makeTransport(): StreamableHTTPClientTransport {+ return new StreamableHTTPClientTransport(new URL(MCP_URL), {+ authProvider: { token: async () => TOKEN! },+ requestInit: { headers: { 'x-posthog-mcp-mode': 'tools' } },+ })+}++// 1) Pinned stateless connect: the SDK must reach the modern era via+// `server/discover` — no `initialize`, no session id.+const client = new Client(+ { name: 'posthog-stateless-smoke', version: '0.0.1' },+ { versionNegotiation: { mode: { pin: STATELESS_VERSION } } }+)+await client.connect(makeTransport())+check(+ 'connect pinned to 2026-07-28',+ client.getNegotiatedProtocolVersion() === STATELESS_VERSION,+ `negotiated=${client.getNegotiatedProtocolVersion()}`+)++// 2) server/discover: capability discovery without a handshake.+const discovered = await client.discover()+check('server/discover returns capabilities', !!discovered.capabilities?.tools)+check(+ 'server identity in result _meta',+ (discovered._meta?.[META_SERVER_INFO] as { name?: string } | undefined)?.name !== undefined,+ JSON.stringify(discovered._meta?.[META_SERVER_INFO])+)++// 3) tools/list over the stateless dialect.+const tools = await client.listTools()+check('tools/list returns tools', tools.tools.length > 0, `${tools.tools.length} tools`)++// 4) A real tool call round-trip.+const orgTool = tools.tools.find((t) => t.name === 'organization-get') ?? tools.tools[0]!+const result = await client.callTool({ name: orgTool.name, arguments: {} })+check(+ `tools/call ${orgTool.name}`,+ !result.isError,+ (result.content?.[0] as { text?: string } | undefined)?.text?.slice(0, 120)+)+await client.close()++// 5) Statelessness proper: a second, fresh connection (new transport, no+// carried session) must serve a tool call just as well.+const client2 = new Client(+ { name: 'posthog-stateless-smoke-2', version: '0.0.1' },+ { versionNegotiation: { mode: { pin: STATELESS_VERSION } } }+)+await client2.connect(makeTransport())+const result2 = await client2.callTool({ name: orgTool.name, arguments: {} })+check('fresh connection serves tools/call (no session affinity)', !result2.isError)+await client2.close()++// 6) Wire-level negative check the SDK can't express: a legacy version inside+// `_meta` must be rejected with UnsupportedProtocolVersionError (-32022).+const rawResponse = await fetch(MCP_URL, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${TOKEN}`,+ 'Content-Type': 'application/json',+ Accept: 'application/json, text/event-stream',+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 99,+ method: 'tools/list',+ params: { _meta: { 'io.modelcontextprotocol/protocolVersion': '2025-11-25' } },+ }),+})+const rawJson = (await rawResponse.json()) as {+ error?: { code?: number; data?: { supported?: string[] } }+}+check(+ 'legacy version in _meta rejected with -32022',+ rawJson.error?.code === -32022 && rawJson.error.data?.supported?.includes(STATELESS_VERSION) === true,+ JSON.stringify(rawJson.error)+)++console.info(failures === 0 ? '\nAll checks passed' : `\n${failures} check(s) failed`)+process.exit(failures === 0 ? 0 : 1)diff --git a/services/mcp/src/hono/dispatcher.ts b/services/mcp/src/hono/dispatcher.tsindex 3015549e40ae..065fafb05064 100644--- a/services/mcp/src/hono/dispatcher.ts+++ b/services/mcp/src/hono/dispatcher.ts@@ -23,6 +23,16 @@ import { randomUUID } from 'node:crypto'import { mapErrorToAuthResponse } from '@/lib/auth-errors'import { MCP_SERVER_NAME, MCP_SERVER_VERSION } from '@/lib/constants'import type { RequestProperties } from '@/lib/request-properties'+import {+ isModernRequest,+ META_SERVER_INFO,+ MODERN_PROTOCOL_VERSIONS,+ parseRequestProtocolMeta,+ readProtocolHeaders,+ SERVER_DISCOVER_METHOD,+ STATELESS_PROTOCOL_VERSION,+ validateModernRequest,+} from '@/lib/stateless-protocol'import { trackInitEvent } from './analytics'import type { RedisLike } from './cache/RedisCache'@@ -42,6 +52,7 @@ const MAX_BODY_BYTES = 1_048_576const Method = {Initialize: 'initialize' as InitializeRequest['method'],+ Discover: SERVER_DISCOVER_METHOD,ToolsList: 'tools/list' as ListToolsRequest['method'],ToolsCall: 'tools/call' as CallToolRequest['method'],ResourcesList: 'resources/list' as ListResourcesRequest['method'],@@ -51,7 +62,32 @@ const Method = {Ping: 'ping' as PingRequest['method'],} as const-const TRACKED_METHODS: Set<string> = new Set([Method.Initialize, Method.ToolsList, Method.ToolsCall])+const TRACKED_METHODS: Set<string> = new Set([Method.Initialize, Method.Discover, Method.ToolsList, Method.ToolsCall])++// Results the 2026-07-28 spec types as CacheableResult (required ttlMs ++// cacheScope). Everything here varies per token (scopes, flags, staff gating)+// or per user (discover instructions), so shared intermediaries must not cache.+const CACHEABLE_METHODS: Set<string> = new Set([+ Method.Discover,+ Method.ToolsList,+ Method.ResourcesList,+ Method.ResourcesRead,+ Method.PromptsList,+])+// ttlMs: 0 is the spec-compliant "don't serve from cache" (both fields are+// required on CacheableResult). Nonzero TTLs are production-only: SDK clients+// honor the hint with a built-in response cache, so locally it would serve a+// stale tools/list while iterating on tool definitions — and with+// listChanged: false the TTL is the client's only freshness signal.+const CACHEABLE_RESULT_TTL_MS = process.env.NODE_ENV === 'production' ? 60_000 : 0++const METHOD_NOT_FOUND = Symbol('method-not-found')++const SERVER_CAPABILITIES = {+ tools: { listChanged: false },+ resources: { listChanged: false },+ prompts: { listChanged: false },+} as constfunction isRequest(msg: JSONRPCMessage): msg is JSONRPCRequest {return (@@ -66,7 +102,7 @@ type JsonRpcResultResponse = { jsonrpc: typeof JSONRPC_VERSION; id: number | strtype JsonRpcErrorResponse = {jsonrpc: typeof JSONRPC_VERSIONid: number | string- error: { code: number; message: string }+ error: { code: number; message: string; data?: unknown }}type JsonRpcResponse = JsonRpcResultResponse | JsonRpcErrorResponse@@ -74,15 +110,22 @@ function jsonRpcResult(id: number | string, result: unknown): JsonRpcResultResporeturn { jsonrpc: JSONRPC_VERSION, id, result }}-function jsonRpcMethodError(id: number | string, code: number, message: string): JsonRpcErrorResponse {- return { jsonrpc: JSONRPC_VERSION, id, error: { code, message } }+function jsonRpcMethodError(id: number | string, code: number, message: string, data?: unknown): JsonRpcErrorResponse {+ return { jsonrpc: JSONRPC_VERSION, id, error: { code, message, ...(data !== undefined ? { data } : {}) } }}-function jsonRpcErrorResponse(id: unknown, code: number, message: string): Response {- return new Response(JSON.stringify({ jsonrpc: JSONRPC_VERSION, id: id ?? null, error: { code, message } }), {- status: 200,- headers: { 'Content-Type': 'application/json' },- })+function jsonRpcErrorResponse(id: unknown, code: number, message: string, data?: unknown, status = 200): Response {+ return new Response(+ JSON.stringify({+ jsonrpc: JSONRPC_VERSION,+ id: id ?? null,+ error: { code, message, ...(data !== undefined ? { data } : {}) },+ }),+ {+ status,+ headers: { 'Content-Type': 'application/json' },+ }+ )}class McpDispatcher {@@ -133,12 +176,50 @@ class McpDispatcher {return jsonRpcErrorResponse(null, ErrorCode.InvalidRequest, 'Batch too large')}+ // SEP-2243 header validation, before any dispatch: modern messages must+ // carry matching operation headers, and (since JSON-RPC batching was+ // removed in 2025-06-18) can never arrive inside an array. Legacy+ // traffic takes neither branch and keeps its exact wire behavior.+ const protocolHeaders = readProtocolHeaders(req.headers)+ let singleModern = false+ if (wasArray) {+ const batchHasModern = messages.some((m) =>+ isModernRequest(protocolHeaders, parseRequestProtocolMeta((m as { params?: unknown }).params))+ )+ if (batchHasModern) {+ return jsonRpcErrorResponse(+ null,+ ErrorCode.InvalidRequest,+ `JSON-RPC batching is not supported by protocol version ${STATELESS_PROTOCOL_VERSION}`,+ undefined,+ 400+ )+ }+ } else {+ const message = messages[0]! as { id?: number | string; method?: unknown; params?: unknown }+ singleModern = isModernRequest(protocolHeaders, parseRequestProtocolMeta(message.params))+ if (singleModern) {+ const validationError = validateModernRequest(protocolHeaders, message)+ if (validationError) {+ return jsonRpcErrorResponse(+ message.id ?? null,+ validationError.code,+ validationError.message,+ validationError.data,+ 400+ )+ }+ }+ }+const requests = messages.filter(isRequest)if (requests.length === 0) {return new Response(null, { status: 202 })}- const hasInit = requests.some((r) => r.method === Method.Initialize)+ // Only the legacy dialect mints sessions — modern `initialize` is a+ // removed RPC and gets method-not-found in dispatch.+ const hasInit = !singleModern && requests.some((r) => r.method === Method.Initialize)if (hasInit) {props.mcpSessionId = randomUUID()}@@ -167,7 +248,10 @@ class McpDispatcher {if (!wasArray && requests.length === 1) {const result = await this.dispatch(requests[0]!, props, state)- return new Response(JSON.stringify(result), { status: 200, headers })+ // SEP-2575: unsupported RPCs get HTTP 404 in the modern dialect.+ const status =+ singleModern && 'error' in result && result.error.code === ErrorCode.MethodNotFound ? 404 : 200+ return new Response(JSON.stringify(result), { status, headers })}const results = await Promise.all(requests.map((r) => this.dispatch(r, props, state)))@@ -181,45 +265,133 @@ class McpDispatcher {): Promise<JsonRpcResponse> {const { id, method, params } = request+ // Version and header validation for modern requests happens in+ // `handleRequest` before dispatch; here `_meta` only picks the dialect.+ const protocolMeta = parseRequestProtocolMeta(params)+ const stateless = protocolMeta.protocolVersion === STATELESS_PROTOCOL_VERSION+try {- switch (method) {- case Method.Initialize:- return jsonRpcResult(id, await this.handleInitialize(params, props, state!))- case Method.ToolsList:- return jsonRpcResult(id, await this.toolExecutor.handleToolsList(state!))- case Method.ToolsCall:- return jsonRpcResult(id, await this.toolExecutor.handleToolCall(params, state!))- case Method.ResourcesList:- return jsonRpcResult(id, this.resourceCatalog.getResourcesList())- case Method.ResourcesRead:- return jsonRpcResult(id, await this.resourceCatalog.readResource(params))- case Method.PromptsList:- return jsonRpcResult(id, this.resourceCatalog.getPromptsList())- case Method.PromptsGet:- return jsonRpcResult(id, this.resourceCatalog.getPrompt(params))- case Method.Ping:- return jsonRpcResult(id, {})- default:- return jsonRpcMethodError(id, ErrorCode.MethodNotFound, 'Method not found')+ const result = await this.dispatchMethod(method, params, props, state, stateless)+ if (result === METHOD_NOT_FOUND) {+ return jsonRpcMethodError(id, ErrorCode.MethodNotFound, 'Method not found')}+ return jsonRpcResult(id, stateless ? this.decorateStatelessResult(method, result) : result)} catch (error) {console.error('[McpDispatcher] Internal error:', error)return jsonRpcMethodError(id, ErrorCode.InternalError, 'Internal error')}}+ /** Returns the raw result for the method, or `METHOD_NOT_FOUND` for unknown methods. */+ private async dispatchMethod(+ method: string,+ params: Record<string, unknown> | undefined,+ props: RequestProperties,+ state: ResolvedState | undefined,+ stateless: boolean+ ): Promise<unknown> {+ // SEP-2575 removed `initialize` and `ping` from the modern dialect.+ if (stateless && (method === Method.Initialize || method === Method.Ping)) {+ return METHOD_NOT_FOUND+ }+ switch (method) {+ case Method.Initialize:+ return await this.handleInitialize(params, props, state!)+ case Method.Discover:+ return await this.handleDiscover(props, state!)+ case Method.ToolsList:+ return await this.toolExecutor.handleToolsList(state!)+ case Method.ToolsCall:+ return await this.toolExecutor.handleToolCall(params, state!)+ case Method.ResourcesList:+ return this.resourceCatalog.getResourcesList()+ case Method.ResourcesRead:+ return await this.resourceCatalog.readResource(params)+ case Method.PromptsList:+ return this.resourceCatalog.getPromptsList()+ case Method.PromptsGet:+ return this.resourceCatalog.getPrompt(params)+ case Method.Ping:+ return {}+ default:+ return METHOD_NOT_FOUND+ }+ }++ // 2026-07-28 results carry `resultType`, the server's identity in `_meta`,+ // and (for CacheableResult methods) client-cache freshness hints. Legacy+ // requests keep the exact pre-existing wire shape.+ private decorateStatelessResult(method: string, result: unknown): unknown {+ const base = result && typeof result === 'object' ? (result as Record<string, unknown>) : {}+ const existingMeta =+ base._meta && typeof base._meta === 'object' ? (base._meta as Record<string, unknown>) : undefined+ return {+ ...base,+ resultType: 'complete',+ ...(CACHEABLE_METHODS.has(method)+ ? { ttlMs: CACHEABLE_RESULT_TTL_MS, cacheScope: 'private' as const }+ : {}),+ _meta: {+ ...existingMeta,+ [META_SERVER_INFO]: { name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION },+ },+ }+ }+private async handleInitialize(params: Record<string, unknown> | undefined,props: RequestProperties,state: ResolvedState): Promise<InitializeResult> {- try {- const requestedVersion = (params?.protocolVersion as string) ?? LATEST_PROTOCOL_VERSION- const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)- ? requestedVersion- : LATEST_PROTOCOL_VERSION+ // A client that sends `initialize` is speaking the legacy dialect, so+ // negotiation stays within the SDK's pre-stateless version list — a+ // 2026-07-28-capable client falling back here gets the newest legacy+ // version, matching the spec's fallback-negotiation behavior.+ const requestedVersion = (params?.protocolVersion as string) ?? LATEST_PROTOCOL_VERSION+ const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)+ ? requestedVersion+ : LATEST_PROTOCOL_VERSION++ const instructions = await this.recordDiscoveryRequest('initialize', props, state)++ return {+ protocolVersion,+ capabilities: SERVER_CAPABILITIES,+ serverInfo: { name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION },+ ...(instructions ? { instructions } : {}),+ }+ }- await this.resourceCatalog.revalidateContextMillResources('initialize')+ // `server/discover` is the stateless counterpart of `initialize`: same+ // capability/instruction payload, but no version negotiation (each request+ // self-describes) and no session minting. Server identity rides in the+ // result `_meta` via `decorateStatelessResult`.+ private async handleDiscover(props: RequestProperties, state: ResolvedState): Promise<Record<string, unknown>> {+ const instructions = await this.recordDiscoveryRequest('discover', props, state)+ return {+ // Modern versions only: legacy support is reachable solely through+ // the `initialize` fallback, and legacy clients never call discover.+ // Advertising legacy versions here would invite modern clients to+ // select one via `_meta`, which we reject.+ supportedVersions: [...MODERN_PROTOCOL_VERSIONS],+ capabilities: SERVER_CAPABILITIES,+ serverInfo: { name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION },+ ...(instructions ? { instructions } : {}),+ }+ }++ /**+ * Shared side effects of the two discovery entry points (`initialize` and+ * `server/discover`): context-mill revalidation, init metrics, and the+ * `$mcp_initialize` analytics event. Returns the per-user instructions.+ */+ private async recordDiscoveryRequest(+ source: 'initialize' | 'discover',+ props: RequestProperties,+ state: ResolvedState+ ): Promise<string | undefined> {+ try {+ await this.resourceCatalog.revalidateContextMillResources(source)const instructions = this.instructionsBuilder.build(state)initDurationSeconds.observe(props.requestStartTime ? (Date.now() - props.requestStartTime) / 1000 : 0)@@ -227,16 +399,7 @@ class McpDispatcher {void trackInitEvent(state)- return {- protocolVersion,- capabilities: {- tools: { listChanged: false },- resources: { listChanged: false },- prompts: { listChanged: false },- },- serverInfo: { name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION },- ...(instructions ? { instructions } : {}),- }+ return instructions} catch (error) {initTotal.inc({ status: mapErrorToAuthResponse(error) ? 'auth_error' : 'error' })throw errordiff --git a/services/mcp/src/hono/request-utils.ts b/services/mcp/src/hono/request-utils.tsindex da86b5b694b1..6914d01cd174 100644--- a/services/mcp/src/hono/request-utils.ts+++ b/services/mcp/src/hono/request-utils.ts@@ -9,6 +9,7 @@ import {type Transport,} from '@/lib/request-properties'import { getRegionFromRequest } from '@/lib/routing'+import { parseRequestProtocolMeta } from '@/lib/stateless-protocol'import { extractBearerToken, sanitizeHeaderValue } from '@/lib/utils'import { authFailuresTotal } from './metrics'@@ -33,21 +34,38 @@ function parseClientInfo(bodyText: string): ClientInfo {try {const parsed = JSON.parse(bodyText)const messages = Array.isArray(parsed) ? parsed : [parsed]+ // 2026-07-28 stateless clients never send `initialize` — their identity+ // rides in each request's `_meta`. Prefer an initialize payload when+ // present (legacy dialect), else fall back to the first `_meta` match.+ let metaFallback: ClientInfo | undefinedfor (const msg of messages) {const rpc = JsonRpcMessageSchema.safeParse(msg)- if (!rpc.success || rpc.data.method !== 'initialize') {+ if (!rpc.success) {continue}- const params = InitializeParamsSchema.safeParse(rpc.data.params)- if (!params.success) {- continue+ if (rpc.data.method === 'initialize') {+ const params = InitializeParamsSchema.safeParse(rpc.data.params)+ if (!params.success) {+ continue+ }+ return {+ clientName: sanitizeHeaderValue(params.data.clientInfo?.name),+ clientVersion: sanitizeHeaderValue(params.data.clientInfo?.version),+ protocolVersion: sanitizeHeaderValue(params.data.protocolVersion),+ }}- return {- clientName: sanitizeHeaderValue(params.data.clientInfo?.name),- clientVersion: sanitizeHeaderValue(params.data.clientInfo?.version),- protocolVersion: sanitizeHeaderValue(params.data.protocolVersion),+ if (!metaFallback) {+ const meta = parseRequestProtocolMeta(rpc.data.params)+ if (meta.protocolVersion || meta.clientName) {+ metaFallback = {+ clientName: sanitizeHeaderValue(meta.clientName),+ clientVersion: sanitizeHeaderValue(meta.clientVersion),+ protocolVersion: sanitizeHeaderValue(meta.protocolVersion),+ }+ }}}+ return metaFallback ?? {}} catch {}return {}}diff --git a/services/mcp/src/hono/resource-catalog.ts b/services/mcp/src/hono/resource-catalog.tsindex 9bb458e44eb8..aa297f3d6f02 100644--- a/services/mcp/src/hono/resource-catalog.ts+++ b/services/mcp/src/hono/resource-catalog.ts@@ -26,7 +26,7 @@ import {contextMillRevalidationsTotal,} from './metrics'-export type ContextMillRevalidationSource = 'warmup' | 'initialize'+export type ContextMillRevalidationSource = 'warmup' | 'initialize' | 'discover'export class ResourceCatalog {private readonly env: Envdiff --git a/services/mcp/src/lib/mcp-client-info.ts b/services/mcp/src/lib/mcp-client-info.tsindex 554c674ce352..6acde5adcd5a 100644--- a/services/mcp/src/lib/mcp-client-info.ts+++ b/services/mcp/src/lib/mcp-client-info.ts@@ -1,3 +1,4 @@+import { parseRequestProtocolMeta } from '@/lib/stateless-protocol'import { sanitizeHeaderValue } from '@/lib/utils'export interface McpClientInfo {@@ -32,8 +33,11 @@ export async function extractClientInfoFromBody(request: Request): Promise<McpCl}const parsed: unknown = JSON.parse(bodyText)const messages = Array.isArray(parsed) ? parsed : [parsed]+ // 2026-07-28 stateless clients never send `initialize`; their identity+ // rides in each request's `_meta`. Initialize wins when both appear.+ let metaFallback: McpClientInfo | undefinedfor (const msg of messages) {- if (!msg || typeof msg !== 'object' || (msg as { method?: unknown }).method !== 'initialize') {+ if (!msg || typeof msg !== 'object') {continue}const params = (@@ -44,21 +48,36 @@ export async function extractClientInfoFromBody(request: Request): Promise<McpCl}}).params- if (!params) {- continue+ if ((msg as { method?: unknown }).method === 'initialize') {+ if (!params) {+ continue+ }+ return {+ clientName: sanitizeHeaderValue(+ typeof params.clientInfo?.name === 'string' ? params.clientInfo.name : undefined+ ),+ clientVersion: sanitizeHeaderValue(+ typeof params.clientInfo?.version === 'string' ? params.clientInfo.version : undefined+ ),+ protocolVersion: sanitizeHeaderValue(+ typeof params.protocolVersion === 'string' ? params.protocolVersion : undefined+ ),+ }}- return {- clientName: sanitizeHeaderValue(- typeof params.clientInfo?.name === 'string' ? params.clientInfo.name : undefined- ),- clientVersion: sanitizeHeaderValue(- typeof params.clientInfo?.version === 'string' ? params.clientInfo.version : undefined- ),- protocolVersion: sanitizeHeaderValue(- typeof params.protocolVersion === 'string' ? params.protocolVersion : undefined- ),+ if (!metaFallback) {+ const meta = parseRequestProtocolMeta(params)+ if (meta.protocolVersion || meta.clientName) {+ metaFallback = {+ clientName: sanitizeHeaderValue(meta.clientName),+ clientVersion: sanitizeHeaderValue(meta.clientVersion),+ protocolVersion: sanitizeHeaderValue(meta.protocolVersion),+ }+ }}}+ if (metaFallback) {+ return metaFallback+ }} catch {// Malformed body — fall back to the framework's async resolution path.}diff --git a/services/mcp/src/lib/stateless-protocol.ts b/services/mcp/src/lib/stateless-protocol.tsnew file mode 100644index 000000000000..715ebf0379aa--- /dev/null+++ b/services/mcp/src/lib/stateless-protocol.ts@@ -0,0 +1,223 @@+// The 2026-07-28 MCP revision (SEP-2575) removes the `initialize` handshake and+// protocol-level sessions: every request carries its protocol version and client+// identity in `params._meta`, servers answer `server/discover` for capability+// discovery, and results carry `resultType` plus the server's identity in+// `_meta`. Legacy (≤2025-11-25) clients keep the `initialize` path untouched, so+// both dialects are served side by side and a request's dialect is detected from+// the reserved `_meta` protocol-version key or a modern `MCP-Protocol-Version`+// header (SEP-2243 requires the operation headers below on every modern request,+// and requires servers that process the body to reject header/body mismatches).++import { ErrorCode } from '@modelcontextprotocol/sdk/types.js'++export const STATELESS_PROTOCOL_VERSION = '2026-07-28'++/**+ * Versions selectable via per-request `_meta` — the modern era only (the spec+ * scopes per-request metadata to "revision 2026-07-28 and later"). Legacy+ * versions are deliberately absent: they are only reachable through the+ * `initialize` handshake, and advertising them here (or accepting them in+ * `_meta`) would steer a conforming modern client into retrying with a version+ * we cannot serve statelessly. `server/discover` and the+ * UnsupportedProtocolVersionError `data.supported` list both use this set.+ */+export const MODERN_PROTOCOL_VERSIONS: readonly string[] = [STATELESS_PROTOCOL_VERSION]++export const SERVER_DISCOVER_METHOD = 'server/discover'++// Reserved `_meta` keys defined by the 2026-07-28 spec.+export const META_PROTOCOL_VERSION = 'io.modelcontextprotocol/protocolVersion'+export const META_CLIENT_INFO = 'io.modelcontextprotocol/clientInfo'+export const META_CLIENT_CAPABILITIES = 'io.modelcontextprotocol/clientCapabilities'+export const META_SERVER_INFO = 'io.modelcontextprotocol/serverInfo'++// Spec error-code range -32020..-32099 is reserved for MCP; -32022 is+// UnsupportedProtocolVersionError, -32020 is SEP-2243's HeaderMismatch+// (originally -32001, reassigned by spec PR #2907).+export const UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE = -32022+export const HEADER_MISMATCH_ERROR_CODE = -32020++// SEP-2243 operation headers, mandatory on modern-dialect HTTP requests.+export const PROTOCOL_VERSION_HEADER = 'MCP-Protocol-Version'+export const MCP_METHOD_HEADER = 'Mcp-Method'+export const MCP_NAME_HEADER = 'Mcp-Name'++// Methods where `Mcp-Name` is required, and the params field it must mirror.+const NAME_HEADER_PARAM: Record<string, 'name' | 'uri'> = {+ 'tools/call': 'name',+ 'prompts/get': 'name',+ 'resources/read': 'uri',+}++export interface RequestProtocolMeta {+ protocolVersion?: string | undefined+ clientName?: string | undefined+ clientVersion?: string | undefined+}++function requestMetaRecord(params: unknown): Record<string, unknown> | undefined {+ if (!params || typeof params !== 'object') {+ return undefined+ }+ const meta = (params as { _meta?: unknown })._meta+ if (!meta || typeof meta !== 'object') {+ return undefined+ }+ return meta as Record<string, unknown>+}++/**+ * Extract the reserved protocol `_meta` keys from a JSON-RPC request's params.+ * Returns an empty object for legacy requests (no `_meta` protocol version), so+ * callers can use `protocolVersion === STATELESS_PROTOCOL_VERSION` as the+ * dialect switch.+ */+export function parseRequestProtocolMeta(params: unknown): RequestProtocolMeta {+ const metaRecord = requestMetaRecord(params)+ if (!metaRecord) {+ return {}+ }+ const clientInfo = metaRecord[META_CLIENT_INFO]+ const clientInfoRecord =+ clientInfo && typeof clientInfo === 'object' ? (clientInfo as Record<string, unknown>) : undefined+ return {+ protocolVersion:+ typeof metaRecord[META_PROTOCOL_VERSION] === 'string'+ ? (metaRecord[META_PROTOCOL_VERSION] as string)+ : undefined,+ clientName: typeof clientInfoRecord?.name === 'string' ? clientInfoRecord.name : undefined,+ clientVersion: typeof clientInfoRecord?.version === 'string' ? clientInfoRecord.version : undefined,+ }+}++export function isSupportedProtocolVersion(version: string): boolean {+ return MODERN_PROTOCOL_VERSIONS.includes(version)+}++export interface ProtocolHeaders {+ protocolVersion: string | null+ method: string | null+ name: string | null+}++/** Accepts the minimal `Headers` surface so unit tests can pass a plain `new Headers()`. */+export function readProtocolHeaders(headers: Pick<Headers, 'get'>): ProtocolHeaders {+ return {+ protocolVersion: headers.get(PROTOCOL_VERSION_HEADER),+ method: headers.get(MCP_METHOD_HEADER),+ name: headers.get(MCP_NAME_HEADER),+ }+}++/**+ * A message speaks the modern dialect when its `_meta` declares a protocol+ * version (any value — unsupported ones still get the modern error shape) or+ * the `MCP-Protocol-Version` header carries a modern version. A legacy header+ * value (e.g. `2025-06-18`, sent by conforming ≤2025-11-25 clients) is not a+ * modern signal and must not trigger enforcement.+ */+export function isModernRequest(headers: ProtocolHeaders, meta: RequestProtocolMeta): boolean {+ return (+ meta.protocolVersion !== undefined ||+ (headers.protocolVersion !== null && isSupportedProtocolVersion(headers.protocolVersion))+ )+}++export interface ProtocolValidationError {+ code: number+ message: string+ data?: Record<string, unknown>+}++function headerRequired(header: string, context: string): ProtocolValidationError {+ return {+ code: HEADER_MISMATCH_ERROR_CODE,+ message: `Header mismatch: ${header} header is required for ${context}`,+ }+}++function headerMismatch(header: string, headerValue: string, bodyValue: string | undefined): ProtocolValidationError {+ return {+ code: HEADER_MISMATCH_ERROR_CODE,+ message: `Header mismatch: ${header} header value '${headerValue}' does not match body value ${bodyValue === undefined ? '(missing)' : `'${bodyValue}'`}`,+ }+}++function invalidMetaField(field: string, reason: string): ProtocolValidationError {+ return {+ code: ErrorCode.InvalidParams,+ message: `Invalid params: _meta ${reason} ${field}`,+ }+}++/**+ * Full modern-dialect validation for a single JSON-RPC message: the SEP-2243+ * operation headers must be present and mirror the body, and the SEP-2575+ * required `_meta` fields must be present. Returns null when valid. Callers+ * gate on `isModernRequest` first — legacy messages must never reach this.+ */+export function validateModernRequest(+ headers: ProtocolHeaders,+ message: { method?: unknown; params?: unknown }+): ProtocolValidationError | null {+ const meta = parseRequestProtocolMeta(message.params)++ // Unsupported versions win over header errors: -32022 carries the+ // machine-readable `data.supported` retry list, and fixing the version+ // forces a fresh request anyway.+ if (meta.protocolVersion !== undefined && !isSupportedProtocolVersion(meta.protocolVersion)) {+ return {+ code: UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE,+ message: `Unsupported protocol version: ${meta.protocolVersion}`,+ data: { supported: [...MODERN_PROTOCOL_VERSIONS], requested: meta.protocolVersion },+ }+ }++ if (headers.protocolVersion === null) {+ return headerRequired(PROTOCOL_VERSION_HEADER, `protocol version ${STATELESS_PROTOCOL_VERSION}`)+ }+ if (headers.protocolVersion !== meta.protocolVersion) {+ return headerMismatch(PROTOCOL_VERSION_HEADER, headers.protocolVersion, meta.protocolVersion)+ }++ const bodyMethod = typeof message.method === 'string' ? message.method : undefined+ if (headers.method === null) {+ return headerRequired(MCP_METHOD_HEADER, `protocol version ${STATELESS_PROTOCOL_VERSION}`)+ }+ if (headers.method !== bodyMethod) {+ return headerMismatch(MCP_METHOD_HEADER, headers.method, bodyMethod)+ }++ const nameParam = bodyMethod !== undefined ? NAME_HEADER_PARAM[bodyMethod] : undefined+ if (bodyMethod !== undefined && nameParam !== undefined) {+ // Non-ASCII names/URIs can't ride in an HTTP header and inherently+ // mismatch — a property of SEP-2243, not this implementation.+ const paramsRecord =+ message.params && typeof message.params === 'object'+ ? (message.params as Record<string, unknown>)+ : undefined+ const bodyName = typeof paramsRecord?.[nameParam] === 'string' ? (paramsRecord[nameParam] as string) : undefined+ if (headers.name === null) {+ return headerRequired(MCP_NAME_HEADER, bodyMethod)+ }+ if (headers.name !== bodyName) {+ return headerMismatch(MCP_NAME_HEADER, headers.name, bodyName)+ }+ }++ const metaRecord = requestMetaRecord(message.params)+ const clientInfo = metaRecord?.[META_CLIENT_INFO]+ if (!clientInfo || typeof clientInfo !== 'object') {+ return invalidMetaField(META_CLIENT_INFO, 'is missing required field')+ }+ const clientInfoRecord = clientInfo as Record<string, unknown>+ if (typeof clientInfoRecord.name !== 'string' || typeof clientInfoRecord.version !== 'string') {+ return invalidMetaField(META_CLIENT_INFO, 'requires string name and version in field')+ }+ const clientCapabilities = metaRecord?.[META_CLIENT_CAPABILITIES]+ if (!clientCapabilities || typeof clientCapabilities !== 'object') {+ return invalidMetaField(META_CLIENT_CAPABILITIES, 'is missing required field')+ }++ return null+}diff --git a/services/mcp/tests/hono/mcp-protocol.test.ts b/services/mcp/tests/hono/mcp-protocol.test.tsindex 9af093e64ffb..a31963e31d40 100644--- a/services/mcp/tests/hono/mcp-protocol.test.ts+++ b/services/mcp/tests/hono/mcp-protocol.test.ts@@ -15,6 +15,7 @@ import {defineResourceCatalogTests,defineSessionLifecycleTests,defineSessionTrackingTests,+ defineStatelessProtocolTests,type ProtocolTestHarness,} from '../integration/mcp-protocol-suite'import { handlers, contextMillHandler } from '../workers/fixtures/handlers'@@ -87,3 +88,4 @@ defineResourceCatalogTests('Hono', harness)defineCatalogFilterTests('Hono', harness)defineExecModeTests('Hono', harness)defineSessionTrackingTests('Hono', harness)+defineStatelessProtocolTests('Hono', harness)diff --git a/services/mcp/tests/integration/mcp-protocol-suite.ts b/services/mcp/tests/integration/mcp-protocol-suite.tsindex 29a92b8ba0bc..7eea103780d9 100644--- a/services/mcp/tests/integration/mcp-protocol-suite.ts+++ b/services/mcp/tests/integration/mcp-protocol-suite.ts@@ -1672,3 +1672,353 @@ export function defineExecModeTests(})})}++// 2026-07-28 stateless dialect. The official stateless client SDK+// (@modelcontextprotocol/client v2) is still in beta, so these tests speak the+// new wire format directly over fetch: no `initialize` handshake, per-request+// `_meta` carrying the protocol version and client identity, `server/discover`+// for capability discovery, and `resultType` + server identity stamped on+// results. The legacy stateful dialect keeps its coverage in the SDK-client+// suites above — both dialects must pass against the same server.+export function defineStatelessProtocolTests(+ label: string,+ getHarness: () => Promise<ProtocolTestHarness> | ProtocolTestHarness+): void {+ describe(`MCP stateless protocol 2026-07-28 (${label})`, () => {+ const STATELESS_VERSION = '2026-07-28'+ const META_VERSION_KEY = 'io.modelcontextprotocol/protocolVersion'+ const META_CLIENT_INFO_KEY = 'io.modelcontextprotocol/clientInfo'+ const META_CLIENT_CAPABILITIES_KEY = 'io.modelcontextprotocol/clientCapabilities'+ const META_SERVER_INFO_KEY = 'io.modelcontextprotocol/serverInfo'+ const VERSION_HEADER = 'MCP-Protocol-Version'+ const METHOD_HEADER = 'Mcp-Method'+ const NAME_HEADER = 'Mcp-Name'++ function statelessParams(params: Record<string, unknown> = {}): Record<string, unknown> {+ return {+ ...params,+ _meta: {+ [META_VERSION_KEY]: STATELESS_VERSION,+ [META_CLIENT_INFO_KEY]: { name: 'stateless-suite', version: '0.0.1' },+ [META_CLIENT_CAPABILITIES_KEY]: {},+ },+ }+ }++ interface RpcEnvelope {+ jsonrpc?: string+ id?: number | string+ result?: Record<string, unknown> & {+ resultType?: string+ ttlMs?: number+ cacheScope?: string+ _meta?: Record<string, unknown>+ }+ error?: { code?: number; message?: string; data?: { supported?: string[]; requested?: string } }+ }++ // SEP-2243 operation headers, derived from the body the way a conforming+ // modern client sends them. Deriving the version header from `_meta`+ // keeps unsupported-version tests reaching the version check instead of+ // failing on a header/body mismatch. An `extraHeaders` value of `null`+ // deletes the derived default so tests can express "omit this header"+ // (keys must match the literal casing used here).+ function specHeaders(method: string, params: Record<string, unknown>): Record<string, string> {+ const meta = params._meta as Record<string, unknown> | undefined+ const metaVersion = meta?.[META_VERSION_KEY]+ if (typeof metaVersion !== 'string') {+ return {}+ }+ const headers: Record<string, string> = { [VERSION_HEADER]: metaVersion, [METHOD_HEADER]: method }+ const name = params.name ?? params.uri+ if (typeof name === 'string') {+ headers[NAME_HEADER] = name+ }+ return headers+ }++ async function postSingle(+ harness: ProtocolTestHarness,+ method: string,+ params: Record<string, unknown>,+ id: number | string = 1,+ extraHeaders: Record<string, string | null> = {}+ ): Promise<{ response: Response; json: RpcEnvelope }> {+ const headers: Record<string, string> = {+ Authorization: `Bearer ${harness.token}`,+ 'Content-Type': 'application/json',+ Accept: 'application/json, text/event-stream',+ 'x-posthog-mcp-mode': 'tools',+ ...specHeaders(method, params),+ }+ for (const [key, value] of Object.entries(extraHeaders)) {+ if (value === null) {+ delete headers[key]+ } else {+ headers[key] = value+ }+ }+ const response = await harness.fetch(new URL('/mcp', harness.baseUrl), {+ method: 'POST',+ headers,+ body: JSON.stringify({ jsonrpc: '2.0', id, method, params }),+ })+ return { response, json: (await response.json()) as RpcEnvelope }+ }++ function serverInfoOf(envelope: RpcEnvelope): { name?: string; version?: string } | undefined {+ return envelope.result?._meta?.[META_SERVER_INFO_KEY] as { name?: string; version?: string } | undefined+ }++ it('answers server/discover with no prior handshake and no session minting', async () => {+ const harness = await getHarness()+ const { response, json } = await postSingle(harness, 'server/discover', statelessParams())++ expect(response.status).toBe(200)+ expect(json.error).toBeUndefined()++ const result = json.result!+ // Modern versions only — legacy versions are reachable solely via+ // the `initialize` fallback and must not be advertised here, or a+ // conforming modern client would select one via `_meta` and be+ // served a dialect we can't speak statelessly.+ expect(result.supportedVersions).toEqual([STATELESS_VERSION])+ expect(result.capabilities).toMatchObject({ tools: { listChanged: false } })+ // DiscoverResult requires top-level serverInfo (not just result _meta).+ expect(result.serverInfo).toMatchObject({ name: 'PostHog' })+ expect(typeof result.instructions).toBe('string')+ expect((result.instructions as string).length).toBeGreaterThan(0)++ // DiscoverResult is a CacheableResult in the 2026-07-28 schema.+ // Outside production the TTL must be 0 (spec-compliant "don't+ // cache") so SDK client response caches never serve stale results+ // against a locally iterating server.+ expect(result.resultType).toBe('complete')+ expect(result.ttlMs).toBe(0)+ expect(result.cacheScope).toBe('private')+ expect(serverInfoOf(json)?.name).toBe('PostHog')++ // Stateless dialect has no protocol-level sessions — the server+ // must not mint one for discover.+ expect(response.headers.get('mcp-session-id')).toBeNull()+ })++ it('serves a tool call with per-request _meta and no handshake', async () => {+ const harness = await getHarness()+ const { response, json } = await postSingle(+ harness,+ 'tools/call',+ statelessParams({ name: 'organization-get', arguments: {} })+ )++ expect(response.status).toBe(200)+ const result = json.result!+ expect(result.isError).toBeFalsy()+ expect(Array.isArray(result.content)).toBe(true)+ expect(result.resultType).toBe('complete')+ expect(serverInfoOf(json)?.name).toBe('PostHog')+ // tools/call is not a CacheableResult — no freshness hints.+ expect(result.ttlMs).toBeUndefined()+ expect(result.cacheScope).toBeUndefined()+ })++ it('merges server identity into a tool result that carries its own _meta', async () => {+ // Only the exec path with a PostHog Code consumer puts `_meta`+ // (ui.resourceUri) on the call result — the one production shape+ // that would expose serverInfo stamping clobbering a tool's meta.+ const harness = await getHarness()+ const { json } = await postSingle(+ harness,+ 'tools/call',+ statelessParams({ name: 'exec', arguments: { command: 'call debug-mcp-ui-apps {}' } }),+ 1,+ { 'x-posthog-mcp-mode': 'cli', 'x-posthog-mcp-consumer': 'posthog-code' }+ )++ const meta = json.result?._meta ?? {}+ expect(serverInfoOf(json)?.name).toBe('PostHog')+ expect((meta.ui as { resourceUri?: string } | undefined)?.resourceUri).toBeTruthy()+ })++ it('adds cache freshness hints to tools/list for stateless requests', async () => {+ const harness = await getHarness()+ const { json } = await postSingle(harness, 'tools/list', statelessParams())++ const result = json.result!+ expect((result.tools as unknown[]).length).toBeGreaterThan(0)+ expect(result.resultType).toBe('complete')+ expect(result.ttlMs).toBe(0)+ expect(result.cacheScope).toBe('private')+ })++ // A legacy version in `_meta` is just as unsupported as an unknown one:+ // legacy revisions don't define per-request metadata, so they're only+ // implemented behind `initialize`. The `data` payload is spec-required —+ // conforming clients auto-retry from `error.data.supported`.+ it.each(['2099-01-01', '2025-03-26'])(+ 'rejects _meta protocol version %s with UnsupportedProtocolVersionError',+ async (version) => {+ const harness = await getHarness()+ const { response, json } = await postSingle(+ harness,+ 'tools/list',+ { _meta: { [META_VERSION_KEY]: version } },+ 'bad-version'+ )++ // SEP-2575: UnsupportedProtocolVersionError rides on HTTP 400.+ expect(response.status).toBe(400)+ expect(json.id).toBe('bad-version')+ expect(json.error?.code).toBe(-32022)+ expect(json.error?.data?.supported).toEqual([STATELESS_VERSION])+ expect(json.error?.data?.requested).toBe(version)+ }+ )++ // SEP-2243 makes the operation headers mandatory on modern requests and+ // requires body-processing servers to reject missing or mismatched+ // values (HeaderMismatch -32020, HTTP 400) — otherwise a caller could+ // label a tools/call as something innocuous for header-routing+ // intermediaries while executing a different operation. The exhaustive+ // failure matrix is unit-tested against validateModernRequest; these+ // prove the dispatcher wiring and status codes.+ it.each([VERSION_HEADER, METHOD_HEADER, NAME_HEADER])(+ 'rejects a modern tools/call missing the %s header',+ async (header) => {+ const harness = await getHarness()+ const { response, json } = await postSingle(+ harness,+ 'tools/call',+ statelessParams({ name: 'organization-get', arguments: {} }),+ 'no-header',+ { [header]: null }+ )++ expect(response.status).toBe(400)+ expect(json.id).toBe('no-header')+ expect(json.error?.code).toBe(-32020)+ expect(json.error?.message).toContain(header)+ }+ )++ it('rejects a modern request whose Mcp-Method header contradicts the body', async () => {+ const harness = await getHarness()+ const { response, json } = await postSingle(+ harness,+ 'tools/call',+ statelessParams({ name: 'organization-get', arguments: {} }),+ 'mismatch',+ { [METHOD_HEADER]: 'server/discover' }+ )++ expect(response.status).toBe(400)+ expect(json.error?.code).toBe(-32020)+ expect(json.error?.message).toContain("'server/discover'")+ expect(json.error?.message).toContain("'tools/call'")+ })++ it('rejects a modern-header request whose body lacks protocol _meta', async () => {+ const harness = await getHarness()+ const { response, json } = await postSingle(harness, 'tools/list', {}, 'header-only', {+ [VERSION_HEADER]: STATELESS_VERSION,+ [METHOD_HEADER]: 'tools/list',+ })++ expect(response.status).toBe(400)+ expect(json.error?.code).toBe(-32020)+ })++ it('rejects a modern request missing required _meta client fields', async () => {+ const harness = await getHarness()+ const { response, json } = await postSingle(harness, 'tools/list', {+ _meta: {+ [META_VERSION_KEY]: STATELESS_VERSION,+ [META_CLIENT_INFO_KEY]: { name: 'stateless-suite', version: '0.0.1' },+ },+ })++ expect(response.status).toBe(400)+ expect(json.error?.code).toBe(-32602)+ expect(json.error?.message).toContain(META_CLIENT_CAPABILITIES_KEY)+ })++ // Batching was removed from the protocol in 2025-06-18 — arrays exist+ // only for old legacy clients, and a single Mcp-Method header cannot+ // describe a mixed batch.+ it.each([+ ['modern _meta in the batch body', () => statelessParams(), {}],+ [+ 'a modern MCP-Protocol-Version header',+ () => ({}),+ { [VERSION_HEADER]: STATELESS_VERSION, [METHOD_HEADER]: 'tools/list' },+ ],+ ] as Array<[string, () => Record<string, unknown>, Record<string, string>]>)(+ 'rejects a JSON-RPC batch carrying %s',+ async (_label, makeParams, headers) => {+ const harness = await getHarness()+ const response = await harness.fetch(new URL('/mcp', harness.baseUrl), {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${harness.token}`,+ 'Content-Type': 'application/json',+ Accept: 'application/json, text/event-stream',+ 'x-posthog-mcp-mode': 'tools',+ ...headers,+ },+ body: JSON.stringify([+ { jsonrpc: '2.0', id: 'batched', method: 'tools/list', params: makeParams() },+ ]),+ })+ const json = (await response.json()) as RpcEnvelope++ expect(response.status).toBe(400)+ expect(json.error?.code).toBe(-32600)+ }+ )++ // SEP-2575 removed initialize and ping from the modern dialect, and+ // unsupported RPCs ride on HTTP 404 there.+ it.each(['ping', 'initialize'])('answers modern %s with method-not-found and HTTP 404', async (method) => {+ const harness = await getHarness()+ const { response, json } = await postSingle(harness, method, statelessParams(), 'removed-rpc')++ expect(response.status).toBe(404)+ expect(json.error?.code).toBe(-32601)+ // Modern initialize must not mint a session either.+ expect(response.headers.get('mcp-session-id')).toBeNull()+ })++ it('leaves legacy initialize untouched when it carries a legacy MCP-Protocol-Version header', async () => {+ const harness = await getHarness()+ const { response, json } = await postSingle(+ harness,+ 'initialize',+ {+ protocolVersion: '2025-06-18',+ capabilities: {},+ clientInfo: { name: 'legacy-suite', version: '0.0.1' },+ },+ 'legacy-init',+ { [VERSION_HEADER]: '2025-06-18' }+ )++ expect(response.status).toBe(200)+ expect(json.error).toBeUndefined()+ expect(json.result?.protocolVersion).toBe('2025-06-18')+ })++ it('keeps the legacy wire shape for requests without protocol _meta', async () => {+ const harness = await getHarness()+ const { json } = await postSingle(harness, 'tools/list', {})++ const result = json.result!+ expect((result.tools as unknown[]).length).toBeGreaterThan(0)+ // Pre-2026-07-28 clients must see byte-identical result envelopes:+ // no resultType, no cache hints, no injected _meta.+ expect(result.resultType).toBeUndefined()+ expect(result.ttlMs).toBeUndefined()+ expect(result.cacheScope).toBeUndefined()+ expect(result._meta).toBeUndefined()+ })+ })+}diff --git a/services/mcp/tests/unit/mcp-client-info.test.ts b/services/mcp/tests/unit/mcp-client-info.test.tsindex fdf3fcb08fcf..f6b3738e9f2b 100644--- a/services/mcp/tests/unit/mcp-client-info.test.ts+++ b/services/mcp/tests/unit/mcp-client-info.test.ts@@ -51,6 +51,47 @@ describe('extractClientInfoFromBody', () => {expect(info).toEqual({})})+ // 2026-07-28 stateless clients never send `initialize` — identity rides in+ // each request's `_meta`. Without the fallback, all stateless traffic loses+ // client attribution in analytics and wide logs.+ it('extracts clientInfo from per-request _meta on a stateless request', async () => {+ const info = await extractClientInfoFromBody(+ postRequest({+ jsonrpc: '2.0',+ id: 3,+ method: 'tools/call',+ params: {+ name: 'organization-get',+ arguments: {},+ _meta: {+ 'io.modelcontextprotocol/protocolVersion': '2026-07-28',+ 'io.modelcontextprotocol/clientInfo': { name: 'stateless-client', version: '2.0.0' },+ },+ },+ })+ )+ expect(info).toEqual({+ clientName: 'stateless-client',+ clientVersion: '2.0.0',+ protocolVersion: '2026-07-28',+ })+ })++ it('prefers initialize clientInfo over per-request _meta in a mixed batch', async () => {+ const batch = [+ {+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/list',+ params: { _meta: { 'io.modelcontextprotocol/protocolVersion': '2026-07-28' } },+ },+ initializeMessage({ name: 'legacy-client', version: '1.2.3' }, '2025-03-26'),+ ]+ const info = await extractClientInfoFromBody(postRequest(batch))+ expect(info.clientName).toBe('legacy-client')+ expect(info.protocolVersion).toBe('2025-03-26')+ })+it('returns empty object for GET requests (SSE endpoint)', async () => {const req = new Request('https://mcp.example.com/sse', { method: 'GET' })const info = await extractClientInfoFromBody(req)diff --git a/services/mcp/tests/unit/stateless-protocol-headers.test.ts b/services/mcp/tests/unit/stateless-protocol-headers.test.tsnew file mode 100644index 000000000000..4f0cba585458--- /dev/null+++ b/services/mcp/tests/unit/stateless-protocol-headers.test.ts@@ -0,0 +1,185 @@+import { describe, expect, it } from 'vitest'++import {+ isModernRequest,+ MCP_METHOD_HEADER,+ MCP_NAME_HEADER,+ PROTOCOL_VERSION_HEADER,+ type ProtocolHeaders,+ readProtocolHeaders,+ validateModernRequest,+} from '@/lib/stateless-protocol'++const MODERN_VERSION = '2026-07-28'+const META_VERSION_KEY = 'io.modelcontextprotocol/protocolVersion'+const META_CLIENT_INFO_KEY = 'io.modelcontextprotocol/clientInfo'+const META_CLIENT_CAPABILITIES_KEY = 'io.modelcontextprotocol/clientCapabilities'++function headers(overrides: Partial<ProtocolHeaders> = {}): ProtocolHeaders {+ return { protocolVersion: null, method: null, name: null, ...overrides }+}++function modernMeta(overrides: Record<string, unknown> = {}): Record<string, unknown> {+ return {+ [META_VERSION_KEY]: MODERN_VERSION,+ [META_CLIENT_INFO_KEY]: { name: 'unit-suite', version: '0.0.1' },+ [META_CLIENT_CAPABILITIES_KEY]: {},+ ...overrides,+ }+}++function modernMessage(+ method: string,+ params: Record<string, unknown> = {},+ meta: Record<string, unknown> = modernMeta()+): { method: string; params: Record<string, unknown> } {+ return { method, params: { ...params, _meta: meta } }+}++function matchingHeaders(message: { method: string; params: Record<string, unknown> }): ProtocolHeaders {+ const name = message.params.name ?? message.params.uri+ return headers({+ protocolVersion: MODERN_VERSION,+ method: message.method,+ name: typeof name === 'string' ? name : null,+ })+}++describe('stateless protocol operation headers', () => {+ it.each([+ ['modern _meta version', headers(), { protocolVersion: MODERN_VERSION }, true],+ ['legacy _meta version', headers(), { protocolVersion: '2025-03-26' }, true],+ ['garbage _meta version', headers(), { protocolVersion: 'not-a-version' }, true],+ ['modern header, no _meta', headers({ protocolVersion: MODERN_VERSION }), {}, true],+ ['legacy header, no _meta', headers({ protocolVersion: '2025-06-18' }), {}, false],+ ['no signals', headers(), {}, false],+ ])('isModernRequest detects %s as modern=%s', (_label, protocolHeaders, meta, expected) => {+ expect(isModernRequest(protocolHeaders, meta)).toBe(expected)+ })++ it('readProtocolHeaders reads header names case-insensitively', () => {+ const parsed = readProtocolHeaders(+ new Headers({ 'mcp-protocol-version': MODERN_VERSION, 'MCP-METHOD': 'tools/list', 'mcp-name': 'x' })+ )+ expect(parsed).toEqual({ protocolVersion: MODERN_VERSION, method: 'tools/list', name: 'x' })+ })++ it.each([+ ['tools/call with matching name', modernMessage('tools/call', { name: 'get_weather', arguments: {} })],+ ['prompts/get with matching name', modernMessage('prompts/get', { name: 'code_review' })],+ ['resources/read with matching uri', modernMessage('resources/read', { uri: 'file:///a/b.json' })],+ ['tools/list without Mcp-Name', modernMessage('tools/list')],+ ['notification without Mcp-Name', modernMessage('notifications/cancelled', { requestId: 1 })],+ ])('accepts a valid modern %s', (_label, message) => {+ expect(validateModernRequest(matchingHeaders(message), message)).toBeNull()+ })++ it('ignores an extraneous Mcp-Name on methods that do not require it', () => {+ const message = modernMessage('tools/list')+ expect(validateModernRequest({ ...matchingHeaders(message), name: 'stray' }, message)).toBeNull()+ })++ const call = modernMessage('tools/call', { name: 'get_weather', arguments: {} })+ it.each([+ [+ 'missing MCP-Protocol-Version header',+ { ...matchingHeaders(call), protocolVersion: null },+ call,+ -32020,+ PROTOCOL_VERSION_HEADER,+ ],+ [+ 'MCP-Protocol-Version header/_meta mismatch',+ { ...matchingHeaders(call), protocolVersion: '2025-06-18' },+ call,+ -32020,+ "'2025-06-18'",+ ],+ [+ 'modern header with no _meta version',+ headers({ protocolVersion: MODERN_VERSION, method: 'tools/list' }),+ { method: 'tools/list', params: {} },+ -32020,+ '(missing)',+ ],+ ['missing Mcp-Method header', { ...matchingHeaders(call), method: null }, call, -32020, MCP_METHOD_HEADER],+ [+ 'Mcp-Method header/body mismatch',+ { ...matchingHeaders(call), method: 'server/discover' },+ call,+ -32020,+ "'server/discover'",+ ],+ [+ 'Mcp-Method case mismatch (values are case-sensitive)',+ { ...matchingHeaders(call), method: 'Tools/Call' },+ call,+ -32020,+ "'Tools/Call'",+ ],+ [+ 'missing Mcp-Name header on tools/call',+ { ...matchingHeaders(call), name: null },+ call,+ -32020,+ MCP_NAME_HEADER,+ ],+ [+ 'Mcp-Name header/body mismatch',+ { ...matchingHeaders(call), name: 'other_tool' },+ call,+ -32020,+ "'other_tool'",+ ],+ [+ 'Mcp-Name mismatch against resources/read uri',+ headers({ protocolVersion: MODERN_VERSION, method: 'resources/read', name: 'file:///wrong' }),+ modernMessage('resources/read', { uri: 'file:///a/b.json' }),+ -32020,+ "'file:///wrong'",+ ],+ [+ 'unsupported _meta version',+ matchingHeaders(call),+ modernMessage('tools/call', { name: 'get_weather' }, modernMeta({ [META_VERSION_KEY]: '2025-03-26' })),+ -32022,+ 'Unsupported protocol version',+ ],+ [+ 'missing clientInfo',+ matchingHeaders(call),+ modernMessage('tools/call', { name: 'get_weather' }, modernMeta({ [META_CLIENT_INFO_KEY]: undefined })),+ -32602,+ META_CLIENT_INFO_KEY,+ ],+ [+ 'clientInfo without version',+ matchingHeaders(call),+ modernMessage('tools/call', { name: 'get_weather' }, modernMeta({ [META_CLIENT_INFO_KEY]: { name: 'x' } })),+ -32602,+ META_CLIENT_INFO_KEY,+ ],+ [+ 'missing clientCapabilities',+ matchingHeaders(call),+ modernMessage(+ 'tools/call',+ { name: 'get_weather' },+ modernMeta({ [META_CLIENT_CAPABILITIES_KEY]: undefined })+ ),+ -32602,+ META_CLIENT_CAPABILITIES_KEY,+ ],+ ])('rejects %s', (_label, protocolHeaders, message, expectedCode, messageSubstring) => {+ const error = validateModernRequest(protocolHeaders, message)+ expect(error?.code).toBe(expectedCode)+ expect(error?.message).toContain(messageSubstring)+ })++ it('reports the unsupported version (with retry data) before any header errors', () => {+ const message = modernMessage('tools/list', {}, modernMeta({ [META_VERSION_KEY]: '2025-03-26' }))+ const error = validateModernRequest(headers(), message)+ expect(error?.code).toBe(-32022)+ expect(error?.data).toEqual({ supported: [MODERN_VERSION], requested: '2025-03-26' })+ })+})