Merged
20 changes: 20 additions & 0 deletions test/e2e/CLAUDE.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,6 +58,26 @@ note: 'stateless hosting has no server→client back-channel'
`addedInSpecVersion` / `removedInSpecVersion` bound the spec versions a requirement applies to. A behavior changed by a spec release gets a sibling entry: the new entry lists every retired id it replaces in `supersedes` (an array, requires `addedInSpecVersion`), and each retired
entry points back via `supersededBy` (requires `removedInSpecVersion`). A coverage gate enforces that the links resolve and are exactly symmetric.

## The createMcpHandler entry arms (entryStateless / entryModern)

Two transport arms host the dual-era HTTP entry (`createMcpHandler`) in process via an injected fetch, exactly like the other HTTP arms. They are era-fixed (`TRANSPORT_SPEC_VERSIONS`), so each registers cells on exactly one spec-version axis:

- `entryStateless` — the entry with the `legacy: 'stateless'` slot; the scenario's plain client is served per request through the slot. Cells run on the 2025-11-25 axis only.
- `entryModern` — the entry modern-only strict (no legacy slot); the scenario's client is put into pinned 2026-07-28 negotiation by the arm and the per-request `_meta` envelope is attached to every outgoing request/notification by the arm (a harness stop-gap until the client
emits it itself). Cells run on the 2026-07-28 axis only.

Both arms are part of the default transport list, so unrestricted requirements run through the entry automatically. When a requirement cannot run on an entry arm, annotate it with a machine-readable reason instead of bending the test:

```ts
entryExclusions: [{ arm: 'entryModern', reason: 'method-not-in-modern-registry' /* optional note */ }];
```

Omitting `arm` excludes both arms. The reasons (`EntryExclusionReason` in types.ts) are the acceptance checklist for re-admitting cells when the corresponding entry feature lands; a coverage gate rejects annotations that would never have an effect. Requirement families that the
per-request entry structurally cannot serve at all (server→client requests, sessions/resumability, standalone GET streams, subscriptions) are already expressed through their `transports` restrictions and need no annotation.

Arm-specific helpers: `wire()`'s fourth argument also accepts `entry` (createMcpHandler hosting overrides — e.g. a `responseMode` or a bring-your-own `legacy` slot value), the returned `Wired.httpLog` records every HTTP exchange (request body, status, content-type, a readable
response clone) for raw wire assertions, factories may accept the optional per-request context (`EntryServerFactory`), and `modernEnvelopeMeta()` builds the envelope for bodies that POST raw 2026-era requests through `wired.fetch`.

## Running

From the repo root (the suite is the `@modelcontextprotocol/test-e2e` workspace package):
Expand Down
29 changes: 29 additions & 0 deletions test/e2e/coverage.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,7 @@ import { fileURLToPath } from 'node:url';
import { expect, test } from 'vitest';

import { REQUIREMENTS } from './requirements.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS, ENTRY_TRANSPORTS, TRANSPORT_SPEC_VERSIONS } from './types.js';

const E2E_DIR = path.dirname(fileURLToPath(import.meta.url));

Expand DownExpand Up@@ -88,6 +89,34 @@ test('every transport-restricted requirement explains why in note', () => {
expect(missing).toEqual([]);
});

test('every entryExclusions annotation targets an entry arm the requirement would otherwise run on', () => {
const bad: string[] = [];
for (const [id, r] of Object.entries(REQUIREMENTS)) {
for (const exclusion of r.entryExclusions ?? []) {
const arms = exclusion.arm === undefined ? ENTRY_TRANSPORTS : [exclusion.arm];
for (const arm of arms) {
const transports = r.transports ?? ALL_TRANSPORTS;
if (!transports.includes(arm)) {
bad.push(`${id}: entryExclusions targets '${arm}', which the requirement's transports never include`);
continue;
}
const versions = ALL_SPEC_VERSIONS.filter(
v =>
(r.addedInSpecVersion === undefined || v >= r.addedInSpecVersion) &&
(r.removedInSpecVersion === undefined || v < r.removedInSpecVersion) &&
(TRANSPORT_SPEC_VERSIONS[arm]?.includes(v) ?? true)
);
if (versions.length === 0) {
bad.push(
`${id}: entryExclusions targets '${arm}', which registers no cells within the requirement's spec-version bounds`
);
}
}
}
}
expect(bad).toEqual([]);
});

test('supersedes/supersededBy links are symmetric and resolve', () => {
const bad: string[] = [];
for (const [id, req] of Object.entries(REQUIREMENTS)) {
Expand Down
29 changes: 29 additions & 0 deletions test/e2e/fixtures/dual-era-stdio-server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
/**
* Runnable dual-era stdio MCP server fixture for the dual-era stdio e2e cells.
*
* `eraSupport: 'dual-era'` is the single declared act on an otherwise ordinary
* hand-constructed McpServer connected to the unchanged StdioServerTransport.
* Spawned as a real child process (via tsx) by
* test/e2e/scenarios/stdio-dual-era.test.ts; exits when its stdin reaches EOF.
*/

import { McpServer } from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
import { z } from 'zod/v4';

const server = new McpServer(
{ name: 'dual-era-stdio-e2e-fixture', version: '1.0.0' },
{ capabilities: { tools: {} }, eraSupport: 'dual-era' }
);

server.registerTool(
'echo',
{
description: 'Echoes the input text back as a text content block.',
inputSchema: z.object({ text: z.string() })
},
({ text }) => ({ content: [{ type: 'text', text }] })
);

await server.connect(new StdioServerTransport());
process.stderr.write('[dual-era-stdio-server] ready\n');
194 changes: 185 additions & 9 deletions test/e2e/helpers/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,30 +15,93 @@ import { PassThrough } from 'node:stream';

import type { Client } from '@modelcontextprotocol/client';
import { SSEClientTransport, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
import type { EventStore, JSONRPCMessage, McpServer, Server } from '@modelcontextprotocol/server';
import { InMemoryTransport, ReadBuffer, serializeMessage, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server';
import { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, PROTOCOL_VERSION_META_KEY } from '@modelcontextprotocol/core';
import type {
CreateMcpHandlerOptions,
EventStore,
Implementation,
JSONRPCMessage,
McpRequestContext,
McpServer,
Server,
Transport as SdkTransport
} from '@modelcontextprotocol/server';
import {
createMcpHandler,
InMemoryTransport,
ReadBuffer,
serializeMessage,
WebStandardStreamableHTTPServerTransport
} from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';

import type { Transport } from '../types.js';
import type { SpecVersion, Transport } from '../types.js';
import { startLegacySseHost } from './sse-host.js';
import type { SnifferOptions } from './wire-sniffer.js';
import { sniffTransport } from './wire-sniffer.js';

export type ServerFactory = () => McpServer | Server;

/**
* A factory that optionally consumes the createMcpHandler per-request context.
* The context is only supplied on the entry arms (where the entry constructs a
* fresh instance per request); on every other arm the factory is called with no
* arguments, so declare the parameter optional.
*/
export type EntryServerFactory = (ctx?: McpRequestContext) => McpServer | Server;

/** One HTTP exchange recorded by the entry arms (see {@linkcode Wired.httpLog}). */
export interface RecordedHttpExchange {
/** HTTP request method (GET/POST/DELETE). */
method: string;
/** The request body text, when one was sent as a string. */
requestBody?: string;
/** HTTP response status. */
status: number;
/** Response content-type header (empty string when absent). */
contentType: string;
/** An unread clone of the HTTP response, for byte-level assertions (`await exchange.response.text()`). */
response: Response;
}

export interface Wired extends AsyncDisposable {
readonly fetch?: (url: URL | string, init?: RequestInit) => Promise<Response>;
readonly url?: URL;
/**
* Every HTTP exchange the wired client performed, in order, including the
* connect-time negotiation. Recorded by the createMcpHandler entry arms
* only — scenarios on those arms use it to assert raw wire facts (request
* bodies, response status/content-type/bytes) that the typed client API
* does not expose.
*/
readonly httpLog?: readonly RecordedHttpExchange[];
}

/**
* The fourth argument controls the wire-format sniffer (see wire-sniffer.ts):
* every message the client sends or receives is validated against the SDK's
* spec-anchored Zod schemas. Tests that intentionally use vendor-extension
* methods pass `{ allowCustomMethods: true }`; tests that deliberately put
* malformed MCP on the wire pass `{ strictValidation: false }`.
* The fourth argument's sniffer options control the wire-format sniffer (see
* wire-sniffer.ts): every message the client sends or receives is validated
* against the SDK's spec-anchored Zod schemas. Tests that intentionally use
* vendor-extension methods pass `{ allowCustomMethods: true }`; tests that
* deliberately put malformed MCP on the wire pass `{ strictValidation: false }`.
* `entry` overrides the hosting options of the createMcpHandler entry arms
* (ignored by every other transport).
*/
export async function wire(transport: Transport, makeServer: ServerFactory, client: Client, sniff: SnifferOptions = {}): Promise<Wired> {
export interface WireOptions extends SnifferOptions {
/**
* createMcpHandler hosting overrides for the entry arms. Defaults:
* `{ legacy: 'stateless' }` on entryStateless (the canonical slot value) and
* modern-only strict (no legacy slot) on entryModern. `onerror` and
* `responseMode` pass through unchanged.
*/
entry?: CreateMcpHandlerOptions;
}

export async function wire(
transport: Transport,
makeServer: ServerFactory | EntryServerFactory,
client: Client,
sniff: WireOptions = {}
): Promise<Wired> {
switch (transport) {
case 'inMemory': {
const server = makeServer();
Expand DownExpand Up@@ -67,6 +130,47 @@ export async function wire(transport: Transport, makeServer: ServerFactory, clie
[Symbol.asyncDispose]: () => Promise.all([client.close(), handle.close()]).then(() => {})
};
}
case 'entryStateless':
case 'entryModern': {
// The dual-era HTTP entry (`createMcpHandler`) hosted in process via an
// injected fetch, exactly like the other HTTP arms. The scenario factory
// backs the entry directly (the entry calls it once per request with its
// per-request context). `entryStateless` serves the scenario's plain
// client through the entry's `legacy: 'stateless'` slot; `entryModern`
// keeps the endpoint modern-only strict and connects the client on the
// 2026-07-28 revision (pin-mode negotiation + the per-request envelope
// stop-gap). Every HTTP exchange is recorded on `httpLog`.
const handler = createMcpHandler(
makeServer,
transport === 'entryStateless' ? { legacy: 'stateless', ...sniff.entry } : { ...sniff.entry }
);
const url = new URL('http://in-process/mcp');
const httpLog: RecordedHttpExchange[] = [];
const fetch = async (u: URL | string, init?: RequestInit) => {
const request = new Request(u, init);
const response = await handler.fetch(request);
httpLog.push({
method: request.method.toUpperCase(),
...(typeof init?.body === 'string' && { requestBody: init.body }),
status: response.status,
contentType: response.headers.get('content-type') ?? '',
response: response.clone()
});
return response;
};
let clientTx = new StreamableHTTPClientTransport(url, { fetch });
if (transport === 'entryModern') {
pinModernNegotiation(client);
clientTx = attachModernEnvelope(clientTx);
}
await client.connect(sniffTransport(clientTx, 'client', sniff));
return {
fetch,
url,
httpLog,
[Symbol.asyncDispose]: () => Promise.all([client.close(), handler.close()]).then(() => {})
};
}
case 'sse': {
// The legacy SSE transport needs a real socket: the factory's server is hosted on the
// shipped SSEServerTransport (@modelcontextprotocol/server-legacy/sse) behind a loopback
Expand DownExpand Up@@ -212,6 +316,78 @@ export function hostStateless(makeServer: ServerFactory): { handleRequest: HttpH
};
}

// ───────────────────────────────────────────────────────────────────────────────
// createMcpHandler entry arms (entryStateless / entryModern) — client-side shims
// ───────────────────────────────────────────────────────────────────────────────

/** The protocol revision the entryModern arm negotiates and claims per request. */
const MODERN_REVISION: SpecVersion = '2026-07-28';

/**
* The per-request `_meta` envelope of a 2026-07-28 request, for scenario bodies
* that put raw HTTP requests on the wire (via `wired.fetch`) rather than going
* through the wired client. Typed calls through the wired client never need
* this — the entryModern arm attaches the envelope itself (see
* {@linkcode attachModernEnvelope}).
*/
export function modernEnvelopeMeta(clientInfo?: Implementation): Record<string, unknown> {
return {
[PROTOCOL_VERSION_META_KEY]: MODERN_REVISION,
[CLIENT_INFO_META_KEY]: clientInfo ?? { name: 'e2e-entry-client', version: '1.0.0' },
[CLIENT_CAPABILITIES_META_KEY]: {}
};
}

/**
* Put the (already constructed) scenario client into pinned 2026-07-28
* negotiation. Version negotiation is a constructor-only option and the
* scenario corpus constructs era-agnostic clients, so the entryModern arm flips
* the option on the instance before `connect()` — a harness stop-gap, not a
* public API. Clients that already opted into a negotiation mode are left
* untouched (their cells deliberately exercise that mode).
*/
function pinModernNegotiation(client: Client): void {
const internals = client as unknown as { _versionNegotiation?: { mode?: unknown } };
internals._versionNegotiation ??= { mode: { pin: MODERN_REVISION } };
}

/**
* The per-request `_meta` envelope stop-gap for the entryModern arm: the
* negotiating client only attaches the envelope to its `server/discover` probe
* today (automatic per-request emission is a client-side follow-up), so the
* harness re-attaches the same envelope to every later request and notification
* the scenario's typed calls put on the wire. The envelope is captured from the
* probe itself, so it always matches what the client actually claimed; messages
* that already carry a protocol-version claim (the probe, or a scenario's
* explicitly enveloped request) pass through untouched.
*
* Applied beneath the wire sniffer and `tapWire`, so recorded traffic shows the
* messages exactly as the scenario sent them while the wire carries the
* envelope the entry requires.
*/
function attachModernEnvelope<T extends SdkTransport>(transport: T): T {
let envelope: Record<string, unknown> | undefined;
const origSend = transport.send.bind(transport);
transport.send = async (message, opts) => {
let outbound = message;
if ('method' in message) {
const params = (message.params ?? {}) as { _meta?: Record<string, unknown> };
const meta = params._meta;
if (meta?.[PROTOCOL_VERSION_META_KEY] !== undefined) {
envelope ??= {
[PROTOCOL_VERSION_META_KEY]: meta[PROTOCOL_VERSION_META_KEY],
[CLIENT_INFO_META_KEY]: meta[CLIENT_INFO_META_KEY],
[CLIENT_CAPABILITIES_META_KEY]: meta[CLIENT_CAPABILITIES_META_KEY]
};
} else if (envelope !== undefined) {
outbound = { ...message, params: { ...params, _meta: { ...envelope, ...meta } } };
}
}
return origSend(outbound, opts);
};
return transport;
}

// ───────────────────────────────────────────────────────────────────────────────
// In-process stdio client — TEST-ONLY
//
Expand Down
20 changes: 16 additions & 4 deletions test/e2e/helpers/verifies.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,11 +18,23 @@
import { describe, test } from 'vitest';

import { REQUIREMENTS } from '../requirements.js';
import type { TestArgs } from '../types.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS } from '../types.js';
import type { Requirement, SpecVersion, TestArgs, Transport } from '../types.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS, ENTRY_TRANSPORTS, TRANSPORT_SPEC_VERSIONS } from '../types.js';

type TestBody = (args: TestArgs) => Promise<void>;

/** Whether a requirement's `entryExclusions` keep the given entry arm out of its cells. */
function excludedFromEntryArm(req: Requirement, transport: Transport): boolean {
if (!(ENTRY_TRANSPORTS as readonly Transport[]).includes(transport)) return false;
return (req.entryExclusions ?? []).some(x => x.arm === undefined || x.arm === transport);
}

/** Whether a transport arm serves the given spec version (era-fixed arms serve exactly one). */
function transportServesVersion(transport: Transport, version: SpecVersion): boolean {
const versions = TRANSPORT_SPEC_VERSIONS[transport];
return versions === undefined || versions.includes(version);
}

export function verifies(id: string | readonly string[], fn: TestBody, opts?: { title?: string }): void {
const ids = Array.isArray(id) ? id : [id];
for (const rid of ids) registerOne(rid, fn, opts);
Expand All@@ -33,13 +45,13 @@ function registerOne(id: string, fn: TestBody, opts?: { title?: string }): void
if (!req) throw new Error(`verifies('${id}'): unknown requirement id`);
if (req.deferred) throw new Error(`verifies('${id}'): requirement is deferred — drop the deferral or the test`);

const transports = req.transports ?? ALL_TRANSPORTS;
const transports = (req.transports ?? ALL_TRANSPORTS).filter(t => !excludedFromEntryArm(req, t));
const versions = ALL_SPEC_VERSIONS.filter(
v =>
(req.addedInSpecVersion === undefined || v >= req.addedInSpecVersion) &&
(req.removedInSpecVersion === undefined || v < req.removedInSpecVersion)
);
const cells = versions.flatMap(v => transports.map(t => [t, v] as const));
const cells = versions.flatMap(v => transports.filter(t => transportServesVersion(t, v)).map(t => [t, v] as const));

describe.each(cells)(`${id} [%s %s]`, (transport, protocolVersion) => {
const kf = req.knownFailures?.find(
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
20 changes: 20 additions & 0 deletions test/e2e/CLAUDE.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,6 +58,26 @@ note: 'stateless hosting has no server→client back-channel'
`addedInSpecVersion` / `removedInSpecVersion` bound the spec versions a requirement applies to. A behavior changed by a spec release gets a sibling entry: the new entry lists every retired id it replaces in `supersedes` (an array, requires `addedInSpecVersion`), and each retired
entry points back via `supersededBy` (requires `removedInSpecVersion`). A coverage gate enforces that the links resolve and are exactly symmetric.

## The createMcpHandler entry arms (entryStateless / entryModern)

Two transport arms host the dual-era HTTP entry (`createMcpHandler`) in process via an injected fetch, exactly like the other HTTP arms. They are era-fixed (`TRANSPORT_SPEC_VERSIONS`), so each registers cells on exactly one spec-version axis:

- `entryStateless` — the entry with the `legacy: 'stateless'` slot; the scenario's plain client is served per request through the slot. Cells run on the 2025-11-25 axis only.
- `entryModern` — the entry modern-only strict (no legacy slot); the scenario's client is put into pinned 2026-07-28 negotiation by the arm and the per-request `_meta` envelope is attached to every outgoing request/notification by the arm (a harness stop-gap until the client
emits it itself). Cells run on the 2026-07-28 axis only.

Both arms are part of the default transport list, so unrestricted requirements run through the entry automatically. When a requirement cannot run on an entry arm, annotate it with a machine-readable reason instead of bending the test:

```ts
entryExclusions: [{ arm: 'entryModern', reason: 'method-not-in-modern-registry' /* optional note */ }];
```

Omitting `arm` excludes both arms. The reasons (`EntryExclusionReason` in types.ts) are the acceptance checklist for re-admitting cells when the corresponding entry feature lands; a coverage gate rejects annotations that would never have an effect. Requirement families that the
per-request entry structurally cannot serve at all (server→client requests, sessions/resumability, standalone GET streams, subscriptions) are already expressed through their `transports` restrictions and need no annotation.

Arm-specific helpers: `wire()`'s fourth argument also accepts `entry` (createMcpHandler hosting overrides — e.g. a `responseMode` or a bring-your-own `legacy` slot value), the returned `Wired.httpLog` records every HTTP exchange (request body, status, content-type, a readable
response clone) for raw wire assertions, factories may accept the optional per-request context (`EntryServerFactory`), and `modernEnvelopeMeta()` builds the envelope for bodies that POST raw 2026-era requests through `wired.fetch`.

## Running

From the repo root (the suite is the `@modelcontextprotocol/test-e2e` workspace package):
Expand Down
29 changes: 29 additions & 0 deletions test/e2e/coverage.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,7 @@ import { fileURLToPath } from 'node:url';
import { expect, test } from 'vitest';

import { REQUIREMENTS } from './requirements.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS, ENTRY_TRANSPORTS, TRANSPORT_SPEC_VERSIONS } from './types.js';

const E2E_DIR = path.dirname(fileURLToPath(import.meta.url));

Expand DownExpand Up@@ -88,6 +89,34 @@ test('every transport-restricted requirement explains why in note', () => {
expect(missing).toEqual([]);
});

test('every entryExclusions annotation targets an entry arm the requirement would otherwise run on', () => {
const bad: string[] = [];
for (const [id, r] of Object.entries(REQUIREMENTS)) {
for (const exclusion of r.entryExclusions ?? []) {
const arms = exclusion.arm === undefined ? ENTRY_TRANSPORTS : [exclusion.arm];
for (const arm of arms) {
const transports = r.transports ?? ALL_TRANSPORTS;
if (!transports.includes(arm)) {
bad.push(`${id}: entryExclusions targets '${arm}', which the requirement's transports never include`);
continue;
}
const versions = ALL_SPEC_VERSIONS.filter(
v =>
(r.addedInSpecVersion === undefined || v >= r.addedInSpecVersion) &&
(r.removedInSpecVersion === undefined || v < r.removedInSpecVersion) &&
(TRANSPORT_SPEC_VERSIONS[arm]?.includes(v) ?? true)
);
if (versions.length === 0) {
bad.push(
`${id}: entryExclusions targets '${arm}', which registers no cells within the requirement's spec-version bounds`
);
}
}
}
}
expect(bad).toEqual([]);
});

test('supersedes/supersededBy links are symmetric and resolve', () => {
const bad: string[] = [];
for (const [id, req] of Object.entries(REQUIREMENTS)) {
Expand Down
29 changes: 29 additions & 0 deletions test/e2e/fixtures/dual-era-stdio-server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
/**
* Runnable dual-era stdio MCP server fixture for the dual-era stdio e2e cells.
*
* `eraSupport: 'dual-era'` is the single declared act on an otherwise ordinary
* hand-constructed McpServer connected to the unchanged StdioServerTransport.
* Spawned as a real child process (via tsx) by
* test/e2e/scenarios/stdio-dual-era.test.ts; exits when its stdin reaches EOF.
*/

import { McpServer } from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
import { z } from 'zod/v4';

const server = new McpServer(
{ name: 'dual-era-stdio-e2e-fixture', version: '1.0.0' },
{ capabilities: { tools: {} }, eraSupport: 'dual-era' }
);

server.registerTool(
'echo',
{
description: 'Echoes the input text back as a text content block.',
inputSchema: z.object({ text: z.string() })
},
({ text }) => ({ content: [{ type: 'text', text }] })
);

await server.connect(new StdioServerTransport());
process.stderr.write('[dual-era-stdio-server] ready\n');
194 changes: 185 additions & 9 deletions test/e2e/helpers/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,30 +15,93 @@ import { PassThrough } from 'node:stream';

import type { Client } from '@modelcontextprotocol/client';
import { SSEClientTransport, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
import type { EventStore, JSONRPCMessage, McpServer, Server } from '@modelcontextprotocol/server';
import { InMemoryTransport, ReadBuffer, serializeMessage, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server';
import { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, PROTOCOL_VERSION_META_KEY } from '@modelcontextprotocol/core';
import type {
CreateMcpHandlerOptions,
EventStore,
Implementation,
JSONRPCMessage,
McpRequestContext,
McpServer,
Server,
Transport as SdkTransport
} from '@modelcontextprotocol/server';
import {
createMcpHandler,
InMemoryTransport,
ReadBuffer,
serializeMessage,
WebStandardStreamableHTTPServerTransport
} from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';

import type { Transport } from '../types.js';
import type { SpecVersion, Transport } from '../types.js';
import { startLegacySseHost } from './sse-host.js';
import type { SnifferOptions } from './wire-sniffer.js';
import { sniffTransport } from './wire-sniffer.js';

export type ServerFactory = () => McpServer | Server;

/**
* A factory that optionally consumes the createMcpHandler per-request context.
* The context is only supplied on the entry arms (where the entry constructs a
* fresh instance per request); on every other arm the factory is called with no
* arguments, so declare the parameter optional.
*/
export type EntryServerFactory = (ctx?: McpRequestContext) => McpServer | Server;

/** One HTTP exchange recorded by the entry arms (see {@linkcode Wired.httpLog}). */
export interface RecordedHttpExchange {
/** HTTP request method (GET/POST/DELETE). */
method: string;
/** The request body text, when one was sent as a string. */
requestBody?: string;
/** HTTP response status. */
status: number;
/** Response content-type header (empty string when absent). */
contentType: string;
/** An unread clone of the HTTP response, for byte-level assertions (`await exchange.response.text()`). */
response: Response;
}

export interface Wired extends AsyncDisposable {
readonly fetch?: (url: URL | string, init?: RequestInit) => Promise<Response>;
readonly url?: URL;
/**
* Every HTTP exchange the wired client performed, in order, including the
* connect-time negotiation. Recorded by the createMcpHandler entry arms
* only — scenarios on those arms use it to assert raw wire facts (request
* bodies, response status/content-type/bytes) that the typed client API
* does not expose.
*/
readonly httpLog?: readonly RecordedHttpExchange[];
}

/**
* The fourth argument controls the wire-format sniffer (see wire-sniffer.ts):
* every message the client sends or receives is validated against the SDK's
* spec-anchored Zod schemas. Tests that intentionally use vendor-extension
* methods pass `{ allowCustomMethods: true }`; tests that deliberately put
* malformed MCP on the wire pass `{ strictValidation: false }`.
* The fourth argument's sniffer options control the wire-format sniffer (see
* wire-sniffer.ts): every message the client sends or receives is validated
* against the SDK's spec-anchored Zod schemas. Tests that intentionally use
* vendor-extension methods pass `{ allowCustomMethods: true }`; tests that
* deliberately put malformed MCP on the wire pass `{ strictValidation: false }`.
* `entry` overrides the hosting options of the createMcpHandler entry arms
* (ignored by every other transport).
*/
export async function wire(transport: Transport, makeServer: ServerFactory, client: Client, sniff: SnifferOptions = {}): Promise<Wired> {
export interface WireOptions extends SnifferOptions {
/**
* createMcpHandler hosting overrides for the entry arms. Defaults:
* `{ legacy: 'stateless' }` on entryStateless (the canonical slot value) and
* modern-only strict (no legacy slot) on entryModern. `onerror` and
* `responseMode` pass through unchanged.
*/
entry?: CreateMcpHandlerOptions;
}

export async function wire(
transport: Transport,
makeServer: ServerFactory | EntryServerFactory,
client: Client,
sniff: WireOptions = {}
): Promise<Wired> {
switch (transport) {
case 'inMemory': {
const server = makeServer();
Expand DownExpand Up@@ -67,6 +130,47 @@ export async function wire(transport: Transport, makeServer: ServerFactory, clie
[Symbol.asyncDispose]: () => Promise.all([client.close(), handle.close()]).then(() => {})
};
}
case 'entryStateless':
case 'entryModern': {
// The dual-era HTTP entry (`createMcpHandler`) hosted in process via an
// injected fetch, exactly like the other HTTP arms. The scenario factory
// backs the entry directly (the entry calls it once per request with its
// per-request context). `entryStateless` serves the scenario's plain
// client through the entry's `legacy: 'stateless'` slot; `entryModern`
// keeps the endpoint modern-only strict and connects the client on the
// 2026-07-28 revision (pin-mode negotiation + the per-request envelope
// stop-gap). Every HTTP exchange is recorded on `httpLog`.
const handler = createMcpHandler(
makeServer,
transport === 'entryStateless' ? { legacy: 'stateless', ...sniff.entry } : { ...sniff.entry }
);
const url = new URL('http://in-process/mcp');
const httpLog: RecordedHttpExchange[] = [];
const fetch = async (u: URL | string, init?: RequestInit) => {
const request = new Request(u, init);
const response = await handler.fetch(request);
httpLog.push({
method: request.method.toUpperCase(),
...(typeof init?.body === 'string' && { requestBody: init.body }),
status: response.status,
contentType: response.headers.get('content-type') ?? '',
response: response.clone()
});
return response;
};
let clientTx = new StreamableHTTPClientTransport(url, { fetch });
if (transport === 'entryModern') {
pinModernNegotiation(client);
clientTx = attachModernEnvelope(clientTx);
}
await client.connect(sniffTransport(clientTx, 'client', sniff));
return {
fetch,
url,
httpLog,
[Symbol.asyncDispose]: () => Promise.all([client.close(), handler.close()]).then(() => {})
};
}
case 'sse': {
// The legacy SSE transport needs a real socket: the factory's server is hosted on the
// shipped SSEServerTransport (@modelcontextprotocol/server-legacy/sse) behind a loopback
Expand DownExpand Up@@ -212,6 +316,78 @@ export function hostStateless(makeServer: ServerFactory): { handleRequest: HttpH
};
}

// ───────────────────────────────────────────────────────────────────────────────
// createMcpHandler entry arms (entryStateless / entryModern) — client-side shims
// ───────────────────────────────────────────────────────────────────────────────

/** The protocol revision the entryModern arm negotiates and claims per request. */
const MODERN_REVISION: SpecVersion = '2026-07-28';

/**
* The per-request `_meta` envelope of a 2026-07-28 request, for scenario bodies
* that put raw HTTP requests on the wire (via `wired.fetch`) rather than going
* through the wired client. Typed calls through the wired client never need
* this — the entryModern arm attaches the envelope itself (see
* {@linkcode attachModernEnvelope}).
*/
export function modernEnvelopeMeta(clientInfo?: Implementation): Record<string, unknown> {
return {
[PROTOCOL_VERSION_META_KEY]: MODERN_REVISION,
[CLIENT_INFO_META_KEY]: clientInfo ?? { name: 'e2e-entry-client', version: '1.0.0' },
[CLIENT_CAPABILITIES_META_KEY]: {}
};
}

/**
* Put the (already constructed) scenario client into pinned 2026-07-28
* negotiation. Version negotiation is a constructor-only option and the
* scenario corpus constructs era-agnostic clients, so the entryModern arm flips
* the option on the instance before `connect()` — a harness stop-gap, not a
* public API. Clients that already opted into a negotiation mode are left
* untouched (their cells deliberately exercise that mode).
*/
function pinModernNegotiation(client: Client): void {
const internals = client as unknown as { _versionNegotiation?: { mode?: unknown } };
internals._versionNegotiation ??= { mode: { pin: MODERN_REVISION } };
}

/**
* The per-request `_meta` envelope stop-gap for the entryModern arm: the
* negotiating client only attaches the envelope to its `server/discover` probe
* today (automatic per-request emission is a client-side follow-up), so the
* harness re-attaches the same envelope to every later request and notification
* the scenario's typed calls put on the wire. The envelope is captured from the
* probe itself, so it always matches what the client actually claimed; messages
* that already carry a protocol-version claim (the probe, or a scenario's
* explicitly enveloped request) pass through untouched.
*
* Applied beneath the wire sniffer and `tapWire`, so recorded traffic shows the
* messages exactly as the scenario sent them while the wire carries the
* envelope the entry requires.
*/
function attachModernEnvelope<T extends SdkTransport>(transport: T): T {
let envelope: Record<string, unknown> | undefined;
const origSend = transport.send.bind(transport);
transport.send = async (message, opts) => {
let outbound = message;
if ('method' in message) {
const params = (message.params ?? {}) as { _meta?: Record<string, unknown> };
const meta = params._meta;
if (meta?.[PROTOCOL_VERSION_META_KEY] !== undefined) {
envelope ??= {
[PROTOCOL_VERSION_META_KEY]: meta[PROTOCOL_VERSION_META_KEY],
[CLIENT_INFO_META_KEY]: meta[CLIENT_INFO_META_KEY],
[CLIENT_CAPABILITIES_META_KEY]: meta[CLIENT_CAPABILITIES_META_KEY]
};
} else if (envelope !== undefined) {
outbound = { ...message, params: { ...params, _meta: { ...envelope, ...meta } } };
}
}
return origSend(outbound, opts);
};
return transport;
}

// ───────────────────────────────────────────────────────────────────────────────
// In-process stdio client — TEST-ONLY
//
Expand Down
20 changes: 16 additions & 4 deletions test/e2e/helpers/verifies.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,11 +18,23 @@
import { describe, test } from 'vitest';

import { REQUIREMENTS } from '../requirements.js';
import type { TestArgs } from '../types.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS } from '../types.js';
import type { Requirement, SpecVersion, TestArgs, Transport } from '../types.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS, ENTRY_TRANSPORTS, TRANSPORT_SPEC_VERSIONS } from '../types.js';

type TestBody = (args: TestArgs) => Promise<void>;

/** Whether a requirement's `entryExclusions` keep the given entry arm out of its cells. */
function excludedFromEntryArm(req: Requirement, transport: Transport): boolean {
if (!(ENTRY_TRANSPORTS as readonly Transport[]).includes(transport)) return false;
return (req.entryExclusions ?? []).some(x => x.arm === undefined || x.arm === transport);
}

/** Whether a transport arm serves the given spec version (era-fixed arms serve exactly one). */
function transportServesVersion(transport: Transport, version: SpecVersion): boolean {
const versions = TRANSPORT_SPEC_VERSIONS[transport];
return versions === undefined || versions.includes(version);
}

export function verifies(id: string | readonly string[], fn: TestBody, opts?: { title?: string }): void {
const ids = Array.isArray(id) ? id : [id];
for (const rid of ids) registerOne(rid, fn, opts);
Expand All@@ -33,13 +45,13 @@ function registerOne(id: string, fn: TestBody, opts?: { title?: string }): void
if (!req) throw new Error(`verifies('${id}'): unknown requirement id`);
if (req.deferred) throw new Error(`verifies('${id}'): requirement is deferred — drop the deferral or the test`);

const transports = req.transports ?? ALL_TRANSPORTS;
const transports = (req.transports ?? ALL_TRANSPORTS).filter(t => !excludedFromEntryArm(req, t));
const versions = ALL_SPEC_VERSIONS.filter(
v =>
(req.addedInSpecVersion === undefined || v >= req.addedInSpecVersion) &&
(req.removedInSpecVersion === undefined || v < req.removedInSpecVersion)
);
const cells = versions.flatMap(v => transports.map(t => [t, v] as const));
const cells = versions.flatMap(v => transports.filter(t => transportServesVersion(t, v)).map(t => [t, v] as const));

describe.each(cells)(`${id} [%s %s]`, (transport, protocolVersion) => {
const kf = req.knownFailures?.find(
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
20 changes: 20 additions & 0 deletions test/e2e/CLAUDE.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,6 +58,26 @@ note: 'stateless hosting has no server→client back-channel'
`addedInSpecVersion` / `removedInSpecVersion` bound the spec versions a requirement applies to. A behavior changed by a spec release gets a sibling entry: the new entry lists every retired id it replaces in `supersedes` (an array, requires `addedInSpecVersion`), and each retired
entry points back via `supersededBy` (requires `removedInSpecVersion`). A coverage gate enforces that the links resolve and are exactly symmetric.

## The createMcpHandler entry arms (entryStateless / entryModern)

Two transport arms host the dual-era HTTP entry (`createMcpHandler`) in process via an injected fetch, exactly like the other HTTP arms. They are era-fixed (`TRANSPORT_SPEC_VERSIONS`), so each registers cells on exactly one spec-version axis:

- `entryStateless` — the entry with the `legacy: 'stateless'` slot; the scenario's plain client is served per request through the slot. Cells run on the 2025-11-25 axis only.
- `entryModern` — the entry modern-only strict (no legacy slot); the scenario's client is put into pinned 2026-07-28 negotiation by the arm and the per-request `_meta` envelope is attached to every outgoing request/notification by the arm (a harness stop-gap until the client
emits it itself). Cells run on the 2026-07-28 axis only.

Both arms are part of the default transport list, so unrestricted requirements run through the entry automatically. When a requirement cannot run on an entry arm, annotate it with a machine-readable reason instead of bending the test:

```ts
entryExclusions: [{ arm: 'entryModern', reason: 'method-not-in-modern-registry' /* optional note */ }];
```

Omitting `arm` excludes both arms. The reasons (`EntryExclusionReason` in types.ts) are the acceptance checklist for re-admitting cells when the corresponding entry feature lands; a coverage gate rejects annotations that would never have an effect. Requirement families that the
per-request entry structurally cannot serve at all (server→client requests, sessions/resumability, standalone GET streams, subscriptions) are already expressed through their `transports` restrictions and need no annotation.

Arm-specific helpers: `wire()`'s fourth argument also accepts `entry` (createMcpHandler hosting overrides — e.g. a `responseMode` or a bring-your-own `legacy` slot value), the returned `Wired.httpLog` records every HTTP exchange (request body, status, content-type, a readable
response clone) for raw wire assertions, factories may accept the optional per-request context (`EntryServerFactory`), and `modernEnvelopeMeta()` builds the envelope for bodies that POST raw 2026-era requests through `wired.fetch`.

## Running

From the repo root (the suite is the `@modelcontextprotocol/test-e2e` workspace package):
Expand Down
29 changes: 29 additions & 0 deletions test/e2e/coverage.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,7 @@ import { fileURLToPath } from 'node:url';
import { expect, test } from 'vitest';

import { REQUIREMENTS } from './requirements.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS, ENTRY_TRANSPORTS, TRANSPORT_SPEC_VERSIONS } from './types.js';

const E2E_DIR = path.dirname(fileURLToPath(import.meta.url));

Expand DownExpand Up@@ -88,6 +89,34 @@ test('every transport-restricted requirement explains why in note', () => {
expect(missing).toEqual([]);
});

test('every entryExclusions annotation targets an entry arm the requirement would otherwise run on', () => {
const bad: string[] = [];
for (const [id, r] of Object.entries(REQUIREMENTS)) {
for (const exclusion of r.entryExclusions ?? []) {
const arms = exclusion.arm === undefined ? ENTRY_TRANSPORTS : [exclusion.arm];
for (const arm of arms) {
const transports = r.transports ?? ALL_TRANSPORTS;
if (!transports.includes(arm)) {
bad.push(`${id}: entryExclusions targets '${arm}', which the requirement's transports never include`);
continue;
}
const versions = ALL_SPEC_VERSIONS.filter(
v =>
(r.addedInSpecVersion === undefined || v >= r.addedInSpecVersion) &&
(r.removedInSpecVersion === undefined || v < r.removedInSpecVersion) &&
(TRANSPORT_SPEC_VERSIONS[arm]?.includes(v) ?? true)
);
if (versions.length === 0) {
bad.push(
`${id}: entryExclusions targets '${arm}', which registers no cells within the requirement's spec-version bounds`
);
}
}
}
}
expect(bad).toEqual([]);
});

test('supersedes/supersededBy links are symmetric and resolve', () => {
const bad: string[] = [];
for (const [id, req] of Object.entries(REQUIREMENTS)) {
Expand Down
29 changes: 29 additions & 0 deletions test/e2e/fixtures/dual-era-stdio-server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
/**
* Runnable dual-era stdio MCP server fixture for the dual-era stdio e2e cells.
*
* `eraSupport: 'dual-era'` is the single declared act on an otherwise ordinary
* hand-constructed McpServer connected to the unchanged StdioServerTransport.
* Spawned as a real child process (via tsx) by
* test/e2e/scenarios/stdio-dual-era.test.ts; exits when its stdin reaches EOF.
*/

import { McpServer } from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
import { z } from 'zod/v4';

const server = new McpServer(
{ name: 'dual-era-stdio-e2e-fixture', version: '1.0.0' },
{ capabilities: { tools: {} }, eraSupport: 'dual-era' }
);

server.registerTool(
'echo',
{
description: 'Echoes the input text back as a text content block.',
inputSchema: z.object({ text: z.string() })
},
({ text }) => ({ content: [{ type: 'text', text }] })
);

await server.connect(new StdioServerTransport());
process.stderr.write('[dual-era-stdio-server] ready\n');
194 changes: 185 additions & 9 deletions test/e2e/helpers/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,30 +15,93 @@ import { PassThrough } from 'node:stream';

import type { Client } from '@modelcontextprotocol/client';
import { SSEClientTransport, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
import type { EventStore, JSONRPCMessage, McpServer, Server } from '@modelcontextprotocol/server';
import { InMemoryTransport, ReadBuffer, serializeMessage, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server';
import { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, PROTOCOL_VERSION_META_KEY } from '@modelcontextprotocol/core';
import type {
CreateMcpHandlerOptions,
EventStore,
Implementation,
JSONRPCMessage,
McpRequestContext,
McpServer,
Server,
Transport as SdkTransport
} from '@modelcontextprotocol/server';
import {
createMcpHandler,
InMemoryTransport,
ReadBuffer,
serializeMessage,
WebStandardStreamableHTTPServerTransport
} from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';

import type { Transport } from '../types.js';
import type { SpecVersion, Transport } from '../types.js';
import { startLegacySseHost } from './sse-host.js';
import type { SnifferOptions } from './wire-sniffer.js';
import { sniffTransport } from './wire-sniffer.js';

export type ServerFactory = () => McpServer | Server;

/**
* A factory that optionally consumes the createMcpHandler per-request context.
* The context is only supplied on the entry arms (where the entry constructs a
* fresh instance per request); on every other arm the factory is called with no
* arguments, so declare the parameter optional.
*/
export type EntryServerFactory = (ctx?: McpRequestContext) => McpServer | Server;

/** One HTTP exchange recorded by the entry arms (see {@linkcode Wired.httpLog}). */
export interface RecordedHttpExchange {
/** HTTP request method (GET/POST/DELETE). */
method: string;
/** The request body text, when one was sent as a string. */
requestBody?: string;
/** HTTP response status. */
status: number;
/** Response content-type header (empty string when absent). */
contentType: string;
/** An unread clone of the HTTP response, for byte-level assertions (`await exchange.response.text()`). */
response: Response;
}

export interface Wired extends AsyncDisposable {
readonly fetch?: (url: URL | string, init?: RequestInit) => Promise<Response>;
readonly url?: URL;
/**
* Every HTTP exchange the wired client performed, in order, including the
* connect-time negotiation. Recorded by the createMcpHandler entry arms
* only — scenarios on those arms use it to assert raw wire facts (request
* bodies, response status/content-type/bytes) that the typed client API
* does not expose.
*/
readonly httpLog?: readonly RecordedHttpExchange[];
}

/**
* The fourth argument controls the wire-format sniffer (see wire-sniffer.ts):
* every message the client sends or receives is validated against the SDK's
* spec-anchored Zod schemas. Tests that intentionally use vendor-extension
* methods pass `{ allowCustomMethods: true }`; tests that deliberately put
* malformed MCP on the wire pass `{ strictValidation: false }`.
* The fourth argument's sniffer options control the wire-format sniffer (see
* wire-sniffer.ts): every message the client sends or receives is validated
* against the SDK's spec-anchored Zod schemas. Tests that intentionally use
* vendor-extension methods pass `{ allowCustomMethods: true }`; tests that
* deliberately put malformed MCP on the wire pass `{ strictValidation: false }`.
* `entry` overrides the hosting options of the createMcpHandler entry arms
* (ignored by every other transport).
*/
export async function wire(transport: Transport, makeServer: ServerFactory, client: Client, sniff: SnifferOptions = {}): Promise<Wired> {
export interface WireOptions extends SnifferOptions {
/**
* createMcpHandler hosting overrides for the entry arms. Defaults:
* `{ legacy: 'stateless' }` on entryStateless (the canonical slot value) and
* modern-only strict (no legacy slot) on entryModern. `onerror` and
* `responseMode` pass through unchanged.
*/
entry?: CreateMcpHandlerOptions;
}

export async function wire(
transport: Transport,
makeServer: ServerFactory | EntryServerFactory,
client: Client,
sniff: WireOptions = {}
): Promise<Wired> {
switch (transport) {
case 'inMemory': {
const server = makeServer();
Expand DownExpand Up@@ -67,6 +130,47 @@ export async function wire(transport: Transport, makeServer: ServerFactory, clie
[Symbol.asyncDispose]: () => Promise.all([client.close(), handle.close()]).then(() => {})
};
}
case 'entryStateless':
case 'entryModern': {
// The dual-era HTTP entry (`createMcpHandler`) hosted in process via an
// injected fetch, exactly like the other HTTP arms. The scenario factory
// backs the entry directly (the entry calls it once per request with its
// per-request context). `entryStateless` serves the scenario's plain
// client through the entry's `legacy: 'stateless'` slot; `entryModern`
// keeps the endpoint modern-only strict and connects the client on the
// 2026-07-28 revision (pin-mode negotiation + the per-request envelope
// stop-gap). Every HTTP exchange is recorded on `httpLog`.
const handler = createMcpHandler(
makeServer,
transport === 'entryStateless' ? { legacy: 'stateless', ...sniff.entry } : { ...sniff.entry }
);
const url = new URL('http://in-process/mcp');
const httpLog: RecordedHttpExchange[] = [];
const fetch = async (u: URL | string, init?: RequestInit) => {
const request = new Request(u, init);
const response = await handler.fetch(request);
httpLog.push({
method: request.method.toUpperCase(),
...(typeof init?.body === 'string' && { requestBody: init.body }),
status: response.status,
contentType: response.headers.get('content-type') ?? '',
response: response.clone()
});
return response;
};
let clientTx = new StreamableHTTPClientTransport(url, { fetch });
if (transport === 'entryModern') {
pinModernNegotiation(client);
clientTx = attachModernEnvelope(clientTx);
}
await client.connect(sniffTransport(clientTx, 'client', sniff));
return {
fetch,
url,
httpLog,
[Symbol.asyncDispose]: () => Promise.all([client.close(), handler.close()]).then(() => {})
};
}
case 'sse': {
// The legacy SSE transport needs a real socket: the factory's server is hosted on the
// shipped SSEServerTransport (@modelcontextprotocol/server-legacy/sse) behind a loopback
Expand DownExpand Up@@ -212,6 +316,78 @@ export function hostStateless(makeServer: ServerFactory): { handleRequest: HttpH
};
}

// ───────────────────────────────────────────────────────────────────────────────
// createMcpHandler entry arms (entryStateless / entryModern) — client-side shims
// ───────────────────────────────────────────────────────────────────────────────

/** The protocol revision the entryModern arm negotiates and claims per request. */
const MODERN_REVISION: SpecVersion = '2026-07-28';

/**
* The per-request `_meta` envelope of a 2026-07-28 request, for scenario bodies
* that put raw HTTP requests on the wire (via `wired.fetch`) rather than going
* through the wired client. Typed calls through the wired client never need
* this — the entryModern arm attaches the envelope itself (see
* {@linkcode attachModernEnvelope}).
*/
export function modernEnvelopeMeta(clientInfo?: Implementation): Record<string, unknown> {
return {
[PROTOCOL_VERSION_META_KEY]: MODERN_REVISION,
[CLIENT_INFO_META_KEY]: clientInfo ?? { name: 'e2e-entry-client', version: '1.0.0' },
[CLIENT_CAPABILITIES_META_KEY]: {}
};
}

/**
* Put the (already constructed) scenario client into pinned 2026-07-28
* negotiation. Version negotiation is a constructor-only option and the
* scenario corpus constructs era-agnostic clients, so the entryModern arm flips
* the option on the instance before `connect()` — a harness stop-gap, not a
* public API. Clients that already opted into a negotiation mode are left
* untouched (their cells deliberately exercise that mode).
*/
function pinModernNegotiation(client: Client): void {
const internals = client as unknown as { _versionNegotiation?: { mode?: unknown } };
internals._versionNegotiation ??= { mode: { pin: MODERN_REVISION } };
}

/**
* The per-request `_meta` envelope stop-gap for the entryModern arm: the
* negotiating client only attaches the envelope to its `server/discover` probe
* today (automatic per-request emission is a client-side follow-up), so the
* harness re-attaches the same envelope to every later request and notification
* the scenario's typed calls put on the wire. The envelope is captured from the
* probe itself, so it always matches what the client actually claimed; messages
* that already carry a protocol-version claim (the probe, or a scenario's
* explicitly enveloped request) pass through untouched.
*
* Applied beneath the wire sniffer and `tapWire`, so recorded traffic shows the
* messages exactly as the scenario sent them while the wire carries the
* envelope the entry requires.
*/
function attachModernEnvelope<T extends SdkTransport>(transport: T): T {
let envelope: Record<string, unknown> | undefined;
const origSend = transport.send.bind(transport);
transport.send = async (message, opts) => {
let outbound = message;
if ('method' in message) {
const params = (message.params ?? {}) as { _meta?: Record<string, unknown> };
const meta = params._meta;
if (meta?.[PROTOCOL_VERSION_META_KEY] !== undefined) {
envelope ??= {
[PROTOCOL_VERSION_META_KEY]: meta[PROTOCOL_VERSION_META_KEY],
[CLIENT_INFO_META_KEY]: meta[CLIENT_INFO_META_KEY],
[CLIENT_CAPABILITIES_META_KEY]: meta[CLIENT_CAPABILITIES_META_KEY]
};
} else if (envelope !== undefined) {
outbound = { ...message, params: { ...params, _meta: { ...envelope, ...meta } } };
}
}
return origSend(outbound, opts);
};
return transport;
}

// ───────────────────────────────────────────────────────────────────────────────
// In-process stdio client — TEST-ONLY
//
Expand Down
20 changes: 16 additions & 4 deletions test/e2e/helpers/verifies.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,11 +18,23 @@
import { describe, test } from 'vitest';

import { REQUIREMENTS } from '../requirements.js';
import type { TestArgs } from '../types.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS } from '../types.js';
import type { Requirement, SpecVersion, TestArgs, Transport } from '../types.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS, ENTRY_TRANSPORTS, TRANSPORT_SPEC_VERSIONS } from '../types.js';

type TestBody = (args: TestArgs) => Promise<void>;

/** Whether a requirement's `entryExclusions` keep the given entry arm out of its cells. */
function excludedFromEntryArm(req: Requirement, transport: Transport): boolean {
if (!(ENTRY_TRANSPORTS as readonly Transport[]).includes(transport)) return false;
return (req.entryExclusions ?? []).some(x => x.arm === undefined || x.arm === transport);
}

/** Whether a transport arm serves the given spec version (era-fixed arms serve exactly one). */
function transportServesVersion(transport: Transport, version: SpecVersion): boolean {
const versions = TRANSPORT_SPEC_VERSIONS[transport];
return versions === undefined || versions.includes(version);
}

export function verifies(id: string | readonly string[], fn: TestBody, opts?: { title?: string }): void {
const ids = Array.isArray(id) ? id : [id];
for (const rid of ids) registerOne(rid, fn, opts);
Expand All@@ -33,13 +45,13 @@ function registerOne(id: string, fn: TestBody, opts?: { title?: string }): void
if (!req) throw new Error(`verifies('${id}'): unknown requirement id`);
if (req.deferred) throw new Error(`verifies('${id}'): requirement is deferred — drop the deferral or the test`);

const transports = req.transports ?? ALL_TRANSPORTS;
const transports = (req.transports ?? ALL_TRANSPORTS).filter(t => !excludedFromEntryArm(req, t));
const versions = ALL_SPEC_VERSIONS.filter(
v =>
(req.addedInSpecVersion === undefined || v >= req.addedInSpecVersion) &&
(req.removedInSpecVersion === undefined || v < req.removedInSpecVersion)
);
const cells = versions.flatMap(v => transports.map(t => [t, v] as const));
const cells = versions.flatMap(v => transports.filter(t => transportServesVersion(t, v)).map(t => [t, v] as const));

describe.each(cells)(`${id} [%s %s]`, (transport, protocolVersion) => {
const kf = req.knownFailures?.find(
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
20 changes: 20 additions & 0 deletions test/e2e/CLAUDE.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,6 +58,26 @@ note: 'stateless hosting has no server→client back-channel'
`addedInSpecVersion` / `removedInSpecVersion` bound the spec versions a requirement applies to. A behavior changed by a spec release gets a sibling entry: the new entry lists every retired id it replaces in `supersedes` (an array, requires `addedInSpecVersion`), and each retired
entry points back via `supersededBy` (requires `removedInSpecVersion`). A coverage gate enforces that the links resolve and are exactly symmetric.

## The createMcpHandler entry arms (entryStateless / entryModern)

Two transport arms host the dual-era HTTP entry (`createMcpHandler`) in process via an injected fetch, exactly like the other HTTP arms. They are era-fixed (`TRANSPORT_SPEC_VERSIONS`), so each registers cells on exactly one spec-version axis:

- `entryStateless` — the entry with the `legacy: 'stateless'` slot; the scenario's plain client is served per request through the slot. Cells run on the 2025-11-25 axis only.
- `entryModern` — the entry modern-only strict (no legacy slot); the scenario's client is put into pinned 2026-07-28 negotiation by the arm and the per-request `_meta` envelope is attached to every outgoing request/notification by the arm (a harness stop-gap until the client
emits it itself). Cells run on the 2026-07-28 axis only.

Both arms are part of the default transport list, so unrestricted requirements run through the entry automatically. When a requirement cannot run on an entry arm, annotate it with a machine-readable reason instead of bending the test:

```ts
entryExclusions: [{ arm: 'entryModern', reason: 'method-not-in-modern-registry' /* optional note */ }];
```

Omitting `arm` excludes both arms. The reasons (`EntryExclusionReason` in types.ts) are the acceptance checklist for re-admitting cells when the corresponding entry feature lands; a coverage gate rejects annotations that would never have an effect. Requirement families that the
per-request entry structurally cannot serve at all (server→client requests, sessions/resumability, standalone GET streams, subscriptions) are already expressed through their `transports` restrictions and need no annotation.

Arm-specific helpers: `wire()`'s fourth argument also accepts `entry` (createMcpHandler hosting overrides — e.g. a `responseMode` or a bring-your-own `legacy` slot value), the returned `Wired.httpLog` records every HTTP exchange (request body, status, content-type, a readable
response clone) for raw wire assertions, factories may accept the optional per-request context (`EntryServerFactory`), and `modernEnvelopeMeta()` builds the envelope for bodies that POST raw 2026-era requests through `wired.fetch`.

## Running

From the repo root (the suite is the `@modelcontextprotocol/test-e2e` workspace package):
Expand Down
29 changes: 29 additions & 0 deletions test/e2e/coverage.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,7 @@ import { fileURLToPath } from 'node:url';
import { expect, test } from 'vitest';

import { REQUIREMENTS } from './requirements.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS, ENTRY_TRANSPORTS, TRANSPORT_SPEC_VERSIONS } from './types.js';

const E2E_DIR = path.dirname(fileURLToPath(import.meta.url));

Expand DownExpand Up@@ -88,6 +89,34 @@ test('every transport-restricted requirement explains why in note', () => {
expect(missing).toEqual([]);
});

test('every entryExclusions annotation targets an entry arm the requirement would otherwise run on', () => {
const bad: string[] = [];
for (const [id, r] of Object.entries(REQUIREMENTS)) {
for (const exclusion of r.entryExclusions ?? []) {
const arms = exclusion.arm === undefined ? ENTRY_TRANSPORTS : [exclusion.arm];
for (const arm of arms) {
const transports = r.transports ?? ALL_TRANSPORTS;
if (!transports.includes(arm)) {
bad.push(`${id}: entryExclusions targets '${arm}', which the requirement's transports never include`);
continue;
}
const versions = ALL_SPEC_VERSIONS.filter(
v =>
(r.addedInSpecVersion === undefined || v >= r.addedInSpecVersion) &&
(r.removedInSpecVersion === undefined || v < r.removedInSpecVersion) &&
(TRANSPORT_SPEC_VERSIONS[arm]?.includes(v) ?? true)
);
if (versions.length === 0) {
bad.push(
`${id}: entryExclusions targets '${arm}', which registers no cells within the requirement's spec-version bounds`
);
}
}
}
}
expect(bad).toEqual([]);
});

test('supersedes/supersededBy links are symmetric and resolve', () => {
const bad: string[] = [];
for (const [id, req] of Object.entries(REQUIREMENTS)) {
Expand Down
29 changes: 29 additions & 0 deletions test/e2e/fixtures/dual-era-stdio-server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
/**
* Runnable dual-era stdio MCP server fixture for the dual-era stdio e2e cells.
*
* `eraSupport: 'dual-era'` is the single declared act on an otherwise ordinary
* hand-constructed McpServer connected to the unchanged StdioServerTransport.
* Spawned as a real child process (via tsx) by
* test/e2e/scenarios/stdio-dual-era.test.ts; exits when its stdin reaches EOF.
*/

import { McpServer } from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
import { z } from 'zod/v4';

const server = new McpServer(
{ name: 'dual-era-stdio-e2e-fixture', version: '1.0.0' },
{ capabilities: { tools: {} }, eraSupport: 'dual-era' }
);

server.registerTool(
'echo',
{
description: 'Echoes the input text back as a text content block.',
inputSchema: z.object({ text: z.string() })
},
({ text }) => ({ content: [{ type: 'text', text }] })
);

await server.connect(new StdioServerTransport());
process.stderr.write('[dual-era-stdio-server] ready\n');
194 changes: 185 additions & 9 deletions test/e2e/helpers/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,30 +15,93 @@ import { PassThrough } from 'node:stream';

import type { Client } from '@modelcontextprotocol/client';
import { SSEClientTransport, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
import type { EventStore, JSONRPCMessage, McpServer, Server } from '@modelcontextprotocol/server';
import { InMemoryTransport, ReadBuffer, serializeMessage, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server';
import { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, PROTOCOL_VERSION_META_KEY } from '@modelcontextprotocol/core';
import type {
CreateMcpHandlerOptions,
EventStore,
Implementation,
JSONRPCMessage,
McpRequestContext,
McpServer,
Server,
Transport as SdkTransport
} from '@modelcontextprotocol/server';
import {
createMcpHandler,
InMemoryTransport,
ReadBuffer,
serializeMessage,
WebStandardStreamableHTTPServerTransport
} from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';

import type { Transport } from '../types.js';
import type { SpecVersion, Transport } from '../types.js';
import { startLegacySseHost } from './sse-host.js';
import type { SnifferOptions } from './wire-sniffer.js';
import { sniffTransport } from './wire-sniffer.js';

export type ServerFactory = () => McpServer | Server;

/**
* A factory that optionally consumes the createMcpHandler per-request context.
* The context is only supplied on the entry arms (where the entry constructs a
* fresh instance per request); on every other arm the factory is called with no
* arguments, so declare the parameter optional.
*/
export type EntryServerFactory = (ctx?: McpRequestContext) => McpServer | Server;

/** One HTTP exchange recorded by the entry arms (see {@linkcode Wired.httpLog}). */
export interface RecordedHttpExchange {
/** HTTP request method (GET/POST/DELETE). */
method: string;
/** The request body text, when one was sent as a string. */
requestBody?: string;
/** HTTP response status. */
status: number;
/** Response content-type header (empty string when absent). */
contentType: string;
/** An unread clone of the HTTP response, for byte-level assertions (`await exchange.response.text()`). */
response: Response;
}

export interface Wired extends AsyncDisposable {
readonly fetch?: (url: URL | string, init?: RequestInit) => Promise<Response>;
readonly url?: URL;
/**
* Every HTTP exchange the wired client performed, in order, including the
* connect-time negotiation. Recorded by the createMcpHandler entry arms
* only — scenarios on those arms use it to assert raw wire facts (request
* bodies, response status/content-type/bytes) that the typed client API
* does not expose.
*/
readonly httpLog?: readonly RecordedHttpExchange[];
}

/**
* The fourth argument controls the wire-format sniffer (see wire-sniffer.ts):
* every message the client sends or receives is validated against the SDK's
* spec-anchored Zod schemas. Tests that intentionally use vendor-extension
* methods pass `{ allowCustomMethods: true }`; tests that deliberately put
* malformed MCP on the wire pass `{ strictValidation: false }`.
* The fourth argument's sniffer options control the wire-format sniffer (see
* wire-sniffer.ts): every message the client sends or receives is validated
* against the SDK's spec-anchored Zod schemas. Tests that intentionally use
* vendor-extension methods pass `{ allowCustomMethods: true }`; tests that
* deliberately put malformed MCP on the wire pass `{ strictValidation: false }`.
* `entry` overrides the hosting options of the createMcpHandler entry arms
* (ignored by every other transport).
*/
export async function wire(transport: Transport, makeServer: ServerFactory, client: Client, sniff: SnifferOptions = {}): Promise<Wired> {
export interface WireOptions extends SnifferOptions {
/**
* createMcpHandler hosting overrides for the entry arms. Defaults:
* `{ legacy: 'stateless' }` on entryStateless (the canonical slot value) and
* modern-only strict (no legacy slot) on entryModern. `onerror` and
* `responseMode` pass through unchanged.
*/
entry?: CreateMcpHandlerOptions;
}

export async function wire(
transport: Transport,
makeServer: ServerFactory | EntryServerFactory,
client: Client,
sniff: WireOptions = {}
): Promise<Wired> {
switch (transport) {
case 'inMemory': {
const server = makeServer();
Expand DownExpand Up@@ -67,6 +130,47 @@ export async function wire(transport: Transport, makeServer: ServerFactory, clie
[Symbol.asyncDispose]: () => Promise.all([client.close(), handle.close()]).then(() => {})
};
}
case 'entryStateless':
case 'entryModern': {
// The dual-era HTTP entry (`createMcpHandler`) hosted in process via an
// injected fetch, exactly like the other HTTP arms. The scenario factory
// backs the entry directly (the entry calls it once per request with its
// per-request context). `entryStateless` serves the scenario's plain
// client through the entry's `legacy: 'stateless'` slot; `entryModern`
// keeps the endpoint modern-only strict and connects the client on the
// 2026-07-28 revision (pin-mode negotiation + the per-request envelope
// stop-gap). Every HTTP exchange is recorded on `httpLog`.
const handler = createMcpHandler(
makeServer,
transport === 'entryStateless' ? { legacy: 'stateless', ...sniff.entry } : { ...sniff.entry }
);
const url = new URL('http://in-process/mcp');
const httpLog: RecordedHttpExchange[] = [];
const fetch = async (u: URL | string, init?: RequestInit) => {
const request = new Request(u, init);
const response = await handler.fetch(request);
httpLog.push({
method: request.method.toUpperCase(),
...(typeof init?.body === 'string' && { requestBody: init.body }),
status: response.status,
contentType: response.headers.get('content-type') ?? '',
response: response.clone()
});
return response;
};
let clientTx = new StreamableHTTPClientTransport(url, { fetch });
if (transport === 'entryModern') {
pinModernNegotiation(client);
clientTx = attachModernEnvelope(clientTx);
}
await client.connect(sniffTransport(clientTx, 'client', sniff));
return {
fetch,
url,
httpLog,
[Symbol.asyncDispose]: () => Promise.all([client.close(), handler.close()]).then(() => {})
};
}
case 'sse': {
// The legacy SSE transport needs a real socket: the factory's server is hosted on the
// shipped SSEServerTransport (@modelcontextprotocol/server-legacy/sse) behind a loopback
Expand DownExpand Up@@ -212,6 +316,78 @@ export function hostStateless(makeServer: ServerFactory): { handleRequest: HttpH
};
}

// ───────────────────────────────────────────────────────────────────────────────
// createMcpHandler entry arms (entryStateless / entryModern) — client-side shims
// ───────────────────────────────────────────────────────────────────────────────

/** The protocol revision the entryModern arm negotiates and claims per request. */
const MODERN_REVISION: SpecVersion = '2026-07-28';

/**
* The per-request `_meta` envelope of a 2026-07-28 request, for scenario bodies
* that put raw HTTP requests on the wire (via `wired.fetch`) rather than going
* through the wired client. Typed calls through the wired client never need
* this — the entryModern arm attaches the envelope itself (see
* {@linkcode attachModernEnvelope}).
*/
export function modernEnvelopeMeta(clientInfo?: Implementation): Record<string, unknown> {
return {
[PROTOCOL_VERSION_META_KEY]: MODERN_REVISION,
[CLIENT_INFO_META_KEY]: clientInfo ?? { name: 'e2e-entry-client', version: '1.0.0' },
[CLIENT_CAPABILITIES_META_KEY]: {}
};
}

/**
* Put the (already constructed) scenario client into pinned 2026-07-28
* negotiation. Version negotiation is a constructor-only option and the
* scenario corpus constructs era-agnostic clients, so the entryModern arm flips
* the option on the instance before `connect()` — a harness stop-gap, not a
* public API. Clients that already opted into a negotiation mode are left
* untouched (their cells deliberately exercise that mode).
*/
function pinModernNegotiation(client: Client): void {
const internals = client as unknown as { _versionNegotiation?: { mode?: unknown } };
internals._versionNegotiation ??= { mode: { pin: MODERN_REVISION } };
}

/**
* The per-request `_meta` envelope stop-gap for the entryModern arm: the
* negotiating client only attaches the envelope to its `server/discover` probe
* today (automatic per-request emission is a client-side follow-up), so the
* harness re-attaches the same envelope to every later request and notification
* the scenario's typed calls put on the wire. The envelope is captured from the
* probe itself, so it always matches what the client actually claimed; messages
* that already carry a protocol-version claim (the probe, or a scenario's
* explicitly enveloped request) pass through untouched.
*
* Applied beneath the wire sniffer and `tapWire`, so recorded traffic shows the
* messages exactly as the scenario sent them while the wire carries the
* envelope the entry requires.
*/
function attachModernEnvelope<T extends SdkTransport>(transport: T): T {
let envelope: Record<string, unknown> | undefined;
const origSend = transport.send.bind(transport);
transport.send = async (message, opts) => {
let outbound = message;
if ('method' in message) {
const params = (message.params ?? {}) as { _meta?: Record<string, unknown> };
const meta = params._meta;
if (meta?.[PROTOCOL_VERSION_META_KEY] !== undefined) {
envelope ??= {
[PROTOCOL_VERSION_META_KEY]: meta[PROTOCOL_VERSION_META_KEY],
[CLIENT_INFO_META_KEY]: meta[CLIENT_INFO_META_KEY],
[CLIENT_CAPABILITIES_META_KEY]: meta[CLIENT_CAPABILITIES_META_KEY]
};
} else if (envelope !== undefined) {
outbound = { ...message, params: { ...params, _meta: { ...envelope, ...meta } } };
}
}
return origSend(outbound, opts);
};
return transport;
}

// ───────────────────────────────────────────────────────────────────────────────
// In-process stdio client — TEST-ONLY
//
Expand Down
20 changes: 16 additions & 4 deletions test/e2e/helpers/verifies.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,11 +18,23 @@
import { describe, test } from 'vitest';

import { REQUIREMENTS } from '../requirements.js';
import type { TestArgs } from '../types.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS } from '../types.js';
import type { Requirement, SpecVersion, TestArgs, Transport } from '../types.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS, ENTRY_TRANSPORTS, TRANSPORT_SPEC_VERSIONS } from '../types.js';

type TestBody = (args: TestArgs) => Promise<void>;

/** Whether a requirement's `entryExclusions` keep the given entry arm out of its cells. */
function excludedFromEntryArm(req: Requirement, transport: Transport): boolean {
if (!(ENTRY_TRANSPORTS as readonly Transport[]).includes(transport)) return false;
return (req.entryExclusions ?? []).some(x => x.arm === undefined || x.arm === transport);
}

/** Whether a transport arm serves the given spec version (era-fixed arms serve exactly one). */
function transportServesVersion(transport: Transport, version: SpecVersion): boolean {
const versions = TRANSPORT_SPEC_VERSIONS[transport];
return versions === undefined || versions.includes(version);
}

export function verifies(id: string | readonly string[], fn: TestBody, opts?: { title?: string }): void {
const ids = Array.isArray(id) ? id : [id];
for (const rid of ids) registerOne(rid, fn, opts);
Expand All@@ -33,13 +45,13 @@ function registerOne(id: string, fn: TestBody, opts?: { title?: string }): void
if (!req) throw new Error(`verifies('${id}'): unknown requirement id`);
if (req.deferred) throw new Error(`verifies('${id}'): requirement is deferred — drop the deferral or the test`);

const transports = req.transports ?? ALL_TRANSPORTS;
const transports = (req.transports ?? ALL_TRANSPORTS).filter(t => !excludedFromEntryArm(req, t));
const versions = ALL_SPEC_VERSIONS.filter(
v =>
(req.addedInSpecVersion === undefined || v >= req.addedInSpecVersion) &&
(req.removedInSpecVersion === undefined || v < req.removedInSpecVersion)
);
const cells = versions.flatMap(v => transports.map(t => [t, v] as const));
const cells = versions.flatMap(v => transports.filter(t => transportServesVersion(t, v)).map(t => [t, v] as const));

describe.each(cells)(`${id} [%s %s]`, (transport, protocolVersion) => {
const kf = req.knownFailures?.find(
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
20 changes: 20 additions & 0 deletions test/e2e/CLAUDE.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,6 +58,26 @@ note: 'stateless hosting has no server→client back-channel'
`addedInSpecVersion` / `removedInSpecVersion` bound the spec versions a requirement applies to. A behavior changed by a spec release gets a sibling entry: the new entry lists every retired id it replaces in `supersedes` (an array, requires `addedInSpecVersion`), and each retired
entry points back via `supersededBy` (requires `removedInSpecVersion`). A coverage gate enforces that the links resolve and are exactly symmetric.

## The createMcpHandler entry arms (entryStateless / entryModern)

Two transport arms host the dual-era HTTP entry (`createMcpHandler`) in process via an injected fetch, exactly like the other HTTP arms. They are era-fixed (`TRANSPORT_SPEC_VERSIONS`), so each registers cells on exactly one spec-version axis:

- `entryStateless` — the entry with the `legacy: 'stateless'` slot; the scenario's plain client is served per request through the slot. Cells run on the 2025-11-25 axis only.
- `entryModern` — the entry modern-only strict (no legacy slot); the scenario's client is put into pinned 2026-07-28 negotiation by the arm and the per-request `_meta` envelope is attached to every outgoing request/notification by the arm (a harness stop-gap until the client
emits it itself). Cells run on the 2026-07-28 axis only.

Both arms are part of the default transport list, so unrestricted requirements run through the entry automatically. When a requirement cannot run on an entry arm, annotate it with a machine-readable reason instead of bending the test:

```ts
entryExclusions: [{ arm: 'entryModern', reason: 'method-not-in-modern-registry' /* optional note */ }];
```

Omitting `arm` excludes both arms. The reasons (`EntryExclusionReason` in types.ts) are the acceptance checklist for re-admitting cells when the corresponding entry feature lands; a coverage gate rejects annotations that would never have an effect. Requirement families that the
per-request entry structurally cannot serve at all (server→client requests, sessions/resumability, standalone GET streams, subscriptions) are already expressed through their `transports` restrictions and need no annotation.

Arm-specific helpers: `wire()`'s fourth argument also accepts `entry` (createMcpHandler hosting overrides — e.g. a `responseMode` or a bring-your-own `legacy` slot value), the returned `Wired.httpLog` records every HTTP exchange (request body, status, content-type, a readable
response clone) for raw wire assertions, factories may accept the optional per-request context (`EntryServerFactory`), and `modernEnvelopeMeta()` builds the envelope for bodies that POST raw 2026-era requests through `wired.fetch`.

## Running

From the repo root (the suite is the `@modelcontextprotocol/test-e2e` workspace package):
Expand Down
29 changes: 29 additions & 0 deletions test/e2e/coverage.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,7 @@ import { fileURLToPath } from 'node:url';
import { expect, test } from 'vitest';

import { REQUIREMENTS } from './requirements.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS, ENTRY_TRANSPORTS, TRANSPORT_SPEC_VERSIONS } from './types.js';

const E2E_DIR = path.dirname(fileURLToPath(import.meta.url));

Expand DownExpand Up@@ -88,6 +89,34 @@ test('every transport-restricted requirement explains why in note', () => {
expect(missing).toEqual([]);
});

test('every entryExclusions annotation targets an entry arm the requirement would otherwise run on', () => {
const bad: string[] = [];
for (const [id, r] of Object.entries(REQUIREMENTS)) {
for (const exclusion of r.entryExclusions ?? []) {
const arms = exclusion.arm === undefined ? ENTRY_TRANSPORTS : [exclusion.arm];
for (const arm of arms) {
const transports = r.transports ?? ALL_TRANSPORTS;
if (!transports.includes(arm)) {
bad.push(`${id}: entryExclusions targets '${arm}', which the requirement's transports never include`);
continue;
}
const versions = ALL_SPEC_VERSIONS.filter(
v =>
(r.addedInSpecVersion === undefined || v >= r.addedInSpecVersion) &&
(r.removedInSpecVersion === undefined || v < r.removedInSpecVersion) &&
(TRANSPORT_SPEC_VERSIONS[arm]?.includes(v) ?? true)
);
if (versions.length === 0) {
bad.push(
`${id}: entryExclusions targets '${arm}', which registers no cells within the requirement's spec-version bounds`
);
}
}
}
}
expect(bad).toEqual([]);
});

test('supersedes/supersededBy links are symmetric and resolve', () => {
const bad: string[] = [];
for (const [id, req] of Object.entries(REQUIREMENTS)) {
Expand Down
29 changes: 29 additions & 0 deletions test/e2e/fixtures/dual-era-stdio-server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
/**
* Runnable dual-era stdio MCP server fixture for the dual-era stdio e2e cells.
*
* `eraSupport: 'dual-era'` is the single declared act on an otherwise ordinary
* hand-constructed McpServer connected to the unchanged StdioServerTransport.
* Spawned as a real child process (via tsx) by
* test/e2e/scenarios/stdio-dual-era.test.ts; exits when its stdin reaches EOF.
*/

import { McpServer } from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
import { z } from 'zod/v4';

const server = new McpServer(
{ name: 'dual-era-stdio-e2e-fixture', version: '1.0.0' },
{ capabilities: { tools: {} }, eraSupport: 'dual-era' }
);

server.registerTool(
'echo',
{
description: 'Echoes the input text back as a text content block.',
inputSchema: z.object({ text: z.string() })
},
({ text }) => ({ content: [{ type: 'text', text }] })
);

await server.connect(new StdioServerTransport());
process.stderr.write('[dual-era-stdio-server] ready\n');
194 changes: 185 additions & 9 deletions test/e2e/helpers/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,30 +15,93 @@ import { PassThrough } from 'node:stream';

import type { Client } from '@modelcontextprotocol/client';
import { SSEClientTransport, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
import type { EventStore, JSONRPCMessage, McpServer, Server } from '@modelcontextprotocol/server';
import { InMemoryTransport, ReadBuffer, serializeMessage, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server';
import { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, PROTOCOL_VERSION_META_KEY } from '@modelcontextprotocol/core';
import type {
CreateMcpHandlerOptions,
EventStore,
Implementation,
JSONRPCMessage,
McpRequestContext,
McpServer,
Server,
Transport as SdkTransport
} from '@modelcontextprotocol/server';
import {
createMcpHandler,
InMemoryTransport,
ReadBuffer,
serializeMessage,
WebStandardStreamableHTTPServerTransport
} from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';

import type { Transport } from '../types.js';
import type { SpecVersion, Transport } from '../types.js';
import { startLegacySseHost } from './sse-host.js';
import type { SnifferOptions } from './wire-sniffer.js';
import { sniffTransport } from './wire-sniffer.js';

export type ServerFactory = () => McpServer | Server;

/**
* A factory that optionally consumes the createMcpHandler per-request context.
* The context is only supplied on the entry arms (where the entry constructs a
* fresh instance per request); on every other arm the factory is called with no
* arguments, so declare the parameter optional.
*/
export type EntryServerFactory = (ctx?: McpRequestContext) => McpServer | Server;

/** One HTTP exchange recorded by the entry arms (see {@linkcode Wired.httpLog}). */
export interface RecordedHttpExchange {
/** HTTP request method (GET/POST/DELETE). */
method: string;
/** The request body text, when one was sent as a string. */
requestBody?: string;
/** HTTP response status. */
status: number;
/** Response content-type header (empty string when absent). */
contentType: string;
/** An unread clone of the HTTP response, for byte-level assertions (`await exchange.response.text()`). */
response: Response;
}

export interface Wired extends AsyncDisposable {
readonly fetch?: (url: URL | string, init?: RequestInit) => Promise<Response>;
readonly url?: URL;
/**
* Every HTTP exchange the wired client performed, in order, including the
* connect-time negotiation. Recorded by the createMcpHandler entry arms
* only — scenarios on those arms use it to assert raw wire facts (request
* bodies, response status/content-type/bytes) that the typed client API
* does not expose.
*/
readonly httpLog?: readonly RecordedHttpExchange[];
}

/**
* The fourth argument controls the wire-format sniffer (see wire-sniffer.ts):
* every message the client sends or receives is validated against the SDK's
* spec-anchored Zod schemas. Tests that intentionally use vendor-extension
* methods pass `{ allowCustomMethods: true }`; tests that deliberately put
* malformed MCP on the wire pass `{ strictValidation: false }`.
* The fourth argument's sniffer options control the wire-format sniffer (see
* wire-sniffer.ts): every message the client sends or receives is validated
* against the SDK's spec-anchored Zod schemas. Tests that intentionally use
* vendor-extension methods pass `{ allowCustomMethods: true }`; tests that
* deliberately put malformed MCP on the wire pass `{ strictValidation: false }`.
* `entry` overrides the hosting options of the createMcpHandler entry arms
* (ignored by every other transport).
*/
export async function wire(transport: Transport, makeServer: ServerFactory, client: Client, sniff: SnifferOptions = {}): Promise<Wired> {
export interface WireOptions extends SnifferOptions {
/**
* createMcpHandler hosting overrides for the entry arms. Defaults:
* `{ legacy: 'stateless' }` on entryStateless (the canonical slot value) and
* modern-only strict (no legacy slot) on entryModern. `onerror` and
* `responseMode` pass through unchanged.
*/
entry?: CreateMcpHandlerOptions;
}

export async function wire(
transport: Transport,
makeServer: ServerFactory | EntryServerFactory,
client: Client,
sniff: WireOptions = {}
): Promise<Wired> {
switch (transport) {
case 'inMemory': {
const server = makeServer();
Expand DownExpand Up@@ -67,6 +130,47 @@ export async function wire(transport: Transport, makeServer: ServerFactory, clie
[Symbol.asyncDispose]: () => Promise.all([client.close(), handle.close()]).then(() => {})
};
}
case 'entryStateless':
case 'entryModern': {
// The dual-era HTTP entry (`createMcpHandler`) hosted in process via an
// injected fetch, exactly like the other HTTP arms. The scenario factory
// backs the entry directly (the entry calls it once per request with its
// per-request context). `entryStateless` serves the scenario's plain
// client through the entry's `legacy: 'stateless'` slot; `entryModern`
// keeps the endpoint modern-only strict and connects the client on the
// 2026-07-28 revision (pin-mode negotiation + the per-request envelope
// stop-gap). Every HTTP exchange is recorded on `httpLog`.
const handler = createMcpHandler(
makeServer,
transport === 'entryStateless' ? { legacy: 'stateless', ...sniff.entry } : { ...sniff.entry }
);
const url = new URL('http://in-process/mcp');
const httpLog: RecordedHttpExchange[] = [];
const fetch = async (u: URL | string, init?: RequestInit) => {
const request = new Request(u, init);
const response = await handler.fetch(request);
httpLog.push({
method: request.method.toUpperCase(),
...(typeof init?.body === 'string' && { requestBody: init.body }),
status: response.status,
contentType: response.headers.get('content-type') ?? '',
response: response.clone()
});
return response;
};
let clientTx = new StreamableHTTPClientTransport(url, { fetch });
if (transport === 'entryModern') {
pinModernNegotiation(client);
clientTx = attachModernEnvelope(clientTx);
}
await client.connect(sniffTransport(clientTx, 'client', sniff));
return {
fetch,
url,
httpLog,
[Symbol.asyncDispose]: () => Promise.all([client.close(), handler.close()]).then(() => {})
};
}
case 'sse': {
// The legacy SSE transport needs a real socket: the factory's server is hosted on the
// shipped SSEServerTransport (@modelcontextprotocol/server-legacy/sse) behind a loopback
Expand DownExpand Up@@ -212,6 +316,78 @@ export function hostStateless(makeServer: ServerFactory): { handleRequest: HttpH
};
}

// ───────────────────────────────────────────────────────────────────────────────
// createMcpHandler entry arms (entryStateless / entryModern) — client-side shims
// ───────────────────────────────────────────────────────────────────────────────

/** The protocol revision the entryModern arm negotiates and claims per request. */
const MODERN_REVISION: SpecVersion = '2026-07-28';

/**
* The per-request `_meta` envelope of a 2026-07-28 request, for scenario bodies
* that put raw HTTP requests on the wire (via `wired.fetch`) rather than going
* through the wired client. Typed calls through the wired client never need
* this — the entryModern arm attaches the envelope itself (see
* {@linkcode attachModernEnvelope}).
*/
export function modernEnvelopeMeta(clientInfo?: Implementation): Record<string, unknown> {
return {
[PROTOCOL_VERSION_META_KEY]: MODERN_REVISION,
[CLIENT_INFO_META_KEY]: clientInfo ?? { name: 'e2e-entry-client', version: '1.0.0' },
[CLIENT_CAPABILITIES_META_KEY]: {}
};
}

/**
* Put the (already constructed) scenario client into pinned 2026-07-28
* negotiation. Version negotiation is a constructor-only option and the
* scenario corpus constructs era-agnostic clients, so the entryModern arm flips
* the option on the instance before `connect()` — a harness stop-gap, not a
* public API. Clients that already opted into a negotiation mode are left
* untouched (their cells deliberately exercise that mode).
*/
function pinModernNegotiation(client: Client): void {
const internals = client as unknown as { _versionNegotiation?: { mode?: unknown } };
internals._versionNegotiation ??= { mode: { pin: MODERN_REVISION } };
}

/**
* The per-request `_meta` envelope stop-gap for the entryModern arm: the
* negotiating client only attaches the envelope to its `server/discover` probe
* today (automatic per-request emission is a client-side follow-up), so the
* harness re-attaches the same envelope to every later request and notification
* the scenario's typed calls put on the wire. The envelope is captured from the
* probe itself, so it always matches what the client actually claimed; messages
* that already carry a protocol-version claim (the probe, or a scenario's
* explicitly enveloped request) pass through untouched.
*
* Applied beneath the wire sniffer and `tapWire`, so recorded traffic shows the
* messages exactly as the scenario sent them while the wire carries the
* envelope the entry requires.
*/
function attachModernEnvelope<T extends SdkTransport>(transport: T): T {
let envelope: Record<string, unknown> | undefined;
const origSend = transport.send.bind(transport);
transport.send = async (message, opts) => {
let outbound = message;
if ('method' in message) {
const params = (message.params ?? {}) as { _meta?: Record<string, unknown> };
const meta = params._meta;
if (meta?.[PROTOCOL_VERSION_META_KEY] !== undefined) {
envelope ??= {
[PROTOCOL_VERSION_META_KEY]: meta[PROTOCOL_VERSION_META_KEY],
[CLIENT_INFO_META_KEY]: meta[CLIENT_INFO_META_KEY],
[CLIENT_CAPABILITIES_META_KEY]: meta[CLIENT_CAPABILITIES_META_KEY]
};
} else if (envelope !== undefined) {
outbound = { ...message, params: { ...params, _meta: { ...envelope, ...meta } } };
}
}
return origSend(outbound, opts);
};
return transport;
}

// ───────────────────────────────────────────────────────────────────────────────
// In-process stdio client — TEST-ONLY
//
Expand Down
20 changes: 16 additions & 4 deletions test/e2e/helpers/verifies.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,11 +18,23 @@
import { describe, test } from 'vitest';

import { REQUIREMENTS } from '../requirements.js';
import type { TestArgs } from '../types.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS } from '../types.js';
import type { Requirement, SpecVersion, TestArgs, Transport } from '../types.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS, ENTRY_TRANSPORTS, TRANSPORT_SPEC_VERSIONS } from '../types.js';

type TestBody = (args: TestArgs) => Promise<void>;

/** Whether a requirement's `entryExclusions` keep the given entry arm out of its cells. */
function excludedFromEntryArm(req: Requirement, transport: Transport): boolean {
if (!(ENTRY_TRANSPORTS as readonly Transport[]).includes(transport)) return false;
return (req.entryExclusions ?? []).some(x => x.arm === undefined || x.arm === transport);
}

/** Whether a transport arm serves the given spec version (era-fixed arms serve exactly one). */
function transportServesVersion(transport: Transport, version: SpecVersion): boolean {
const versions = TRANSPORT_SPEC_VERSIONS[transport];
return versions === undefined || versions.includes(version);
}

export function verifies(id: string | readonly string[], fn: TestBody, opts?: { title?: string }): void {
const ids = Array.isArray(id) ? id : [id];
for (const rid of ids) registerOne(rid, fn, opts);
Expand All@@ -33,13 +45,13 @@ function registerOne(id: string, fn: TestBody, opts?: { title?: string }): void
if (!req) throw new Error(`verifies('${id}'): unknown requirement id`);
if (req.deferred) throw new Error(`verifies('${id}'): requirement is deferred — drop the deferral or the test`);

const transports = req.transports ?? ALL_TRANSPORTS;
const transports = (req.transports ?? ALL_TRANSPORTS).filter(t => !excludedFromEntryArm(req, t));
const versions = ALL_SPEC_VERSIONS.filter(
v =>
(req.addedInSpecVersion === undefined || v >= req.addedInSpecVersion) &&
(req.removedInSpecVersion === undefined || v < req.removedInSpecVersion)
);
const cells = versions.flatMap(v => transports.map(t => [t, v] as const));
const cells = versions.flatMap(v => transports.filter(t => transportServesVersion(t, v)).map(t => [t, v] as const));

describe.each(cells)(`${id} [%s %s]`, (transport, protocolVersion) => {
const kf = req.knownFailures?.find(
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
20 changes: 20 additions & 0 deletions test/e2e/CLAUDE.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,6 +58,26 @@ note: 'stateless hosting has no server→client back-channel'
`addedInSpecVersion` / `removedInSpecVersion` bound the spec versions a requirement applies to. A behavior changed by a spec release gets a sibling entry: the new entry lists every retired id it replaces in `supersedes` (an array, requires `addedInSpecVersion`), and each retired
entry points back via `supersededBy` (requires `removedInSpecVersion`). A coverage gate enforces that the links resolve and are exactly symmetric.

## The createMcpHandler entry arms (entryStateless / entryModern)

Two transport arms host the dual-era HTTP entry (`createMcpHandler`) in process via an injected fetch, exactly like the other HTTP arms. They are era-fixed (`TRANSPORT_SPEC_VERSIONS`), so each registers cells on exactly one spec-version axis:

- `entryStateless` — the entry with the `legacy: 'stateless'` slot; the scenario's plain client is served per request through the slot. Cells run on the 2025-11-25 axis only.
- `entryModern` — the entry modern-only strict (no legacy slot); the scenario's client is put into pinned 2026-07-28 negotiation by the arm and the per-request `_meta` envelope is attached to every outgoing request/notification by the arm (a harness stop-gap until the client
emits it itself). Cells run on the 2026-07-28 axis only.

Both arms are part of the default transport list, so unrestricted requirements run through the entry automatically. When a requirement cannot run on an entry arm, annotate it with a machine-readable reason instead of bending the test:

```ts
entryExclusions: [{ arm: 'entryModern', reason: 'method-not-in-modern-registry' /* optional note */ }];
```

Omitting `arm` excludes both arms. The reasons (`EntryExclusionReason` in types.ts) are the acceptance checklist for re-admitting cells when the corresponding entry feature lands; a coverage gate rejects annotations that would never have an effect. Requirement families that the
per-request entry structurally cannot serve at all (server→client requests, sessions/resumability, standalone GET streams, subscriptions) are already expressed through their `transports` restrictions and need no annotation.

Arm-specific helpers: `wire()`'s fourth argument also accepts `entry` (createMcpHandler hosting overrides — e.g. a `responseMode` or a bring-your-own `legacy` slot value), the returned `Wired.httpLog` records every HTTP exchange (request body, status, content-type, a readable
response clone) for raw wire assertions, factories may accept the optional per-request context (`EntryServerFactory`), and `modernEnvelopeMeta()` builds the envelope for bodies that POST raw 2026-era requests through `wired.fetch`.

## Running

From the repo root (the suite is the `@modelcontextprotocol/test-e2e` workspace package):
Expand Down
29 changes: 29 additions & 0 deletions test/e2e/coverage.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,7 @@ import { fileURLToPath } from 'node:url';
import { expect, test } from 'vitest';

import { REQUIREMENTS } from './requirements.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS, ENTRY_TRANSPORTS, TRANSPORT_SPEC_VERSIONS } from './types.js';

const E2E_DIR = path.dirname(fileURLToPath(import.meta.url));

Expand DownExpand Up@@ -88,6 +89,34 @@ test('every transport-restricted requirement explains why in note', () => {
expect(missing).toEqual([]);
});

test('every entryExclusions annotation targets an entry arm the requirement would otherwise run on', () => {
const bad: string[] = [];
for (const [id, r] of Object.entries(REQUIREMENTS)) {
for (const exclusion of r.entryExclusions ?? []) {
const arms = exclusion.arm === undefined ? ENTRY_TRANSPORTS : [exclusion.arm];
for (const arm of arms) {
const transports = r.transports ?? ALL_TRANSPORTS;
if (!transports.includes(arm)) {
bad.push(`${id}: entryExclusions targets '${arm}', which the requirement's transports never include`);
continue;
}
const versions = ALL_SPEC_VERSIONS.filter(
v =>
(r.addedInSpecVersion === undefined || v >= r.addedInSpecVersion) &&
(r.removedInSpecVersion === undefined || v < r.removedInSpecVersion) &&
(TRANSPORT_SPEC_VERSIONS[arm]?.includes(v) ?? true)
);
if (versions.length === 0) {
bad.push(
`${id}: entryExclusions targets '${arm}', which registers no cells within the requirement's spec-version bounds`
);
}
}
}
}
expect(bad).toEqual([]);
});

test('supersedes/supersededBy links are symmetric and resolve', () => {
const bad: string[] = [];
for (const [id, req] of Object.entries(REQUIREMENTS)) {
Expand Down
29 changes: 29 additions & 0 deletions test/e2e/fixtures/dual-era-stdio-server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
/**
* Runnable dual-era stdio MCP server fixture for the dual-era stdio e2e cells.
*
* `eraSupport: 'dual-era'` is the single declared act on an otherwise ordinary
* hand-constructed McpServer connected to the unchanged StdioServerTransport.
* Spawned as a real child process (via tsx) by
* test/e2e/scenarios/stdio-dual-era.test.ts; exits when its stdin reaches EOF.
*/

import { McpServer } from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
import { z } from 'zod/v4';

const server = new McpServer(
{ name: 'dual-era-stdio-e2e-fixture', version: '1.0.0' },
{ capabilities: { tools: {} }, eraSupport: 'dual-era' }
);

server.registerTool(
'echo',
{
description: 'Echoes the input text back as a text content block.',
inputSchema: z.object({ text: z.string() })
},
({ text }) => ({ content: [{ type: 'text', text }] })
);

await server.connect(new StdioServerTransport());
process.stderr.write('[dual-era-stdio-server] ready\n');
194 changes: 185 additions & 9 deletions test/e2e/helpers/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,30 +15,93 @@ import { PassThrough } from 'node:stream';

import type { Client } from '@modelcontextprotocol/client';
import { SSEClientTransport, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
import type { EventStore, JSONRPCMessage, McpServer, Server } from '@modelcontextprotocol/server';
import { InMemoryTransport, ReadBuffer, serializeMessage, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server';
import { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, PROTOCOL_VERSION_META_KEY } from '@modelcontextprotocol/core';
import type {
CreateMcpHandlerOptions,
EventStore,
Implementation,
JSONRPCMessage,
McpRequestContext,
McpServer,
Server,
Transport as SdkTransport
} from '@modelcontextprotocol/server';
import {
createMcpHandler,
InMemoryTransport,
ReadBuffer,
serializeMessage,
WebStandardStreamableHTTPServerTransport
} from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';

import type { Transport } from '../types.js';
import type { SpecVersion, Transport } from '../types.js';
import { startLegacySseHost } from './sse-host.js';
import type { SnifferOptions } from './wire-sniffer.js';
import { sniffTransport } from './wire-sniffer.js';

export type ServerFactory = () => McpServer | Server;

/**
* A factory that optionally consumes the createMcpHandler per-request context.
* The context is only supplied on the entry arms (where the entry constructs a
* fresh instance per request); on every other arm the factory is called with no
* arguments, so declare the parameter optional.
*/
export type EntryServerFactory = (ctx?: McpRequestContext) => McpServer | Server;

/** One HTTP exchange recorded by the entry arms (see {@linkcode Wired.httpLog}). */
export interface RecordedHttpExchange {
/** HTTP request method (GET/POST/DELETE). */
method: string;
/** The request body text, when one was sent as a string. */
requestBody?: string;
/** HTTP response status. */
status: number;
/** Response content-type header (empty string when absent). */
contentType: string;
/** An unread clone of the HTTP response, for byte-level assertions (`await exchange.response.text()`). */
response: Response;
}

export interface Wired extends AsyncDisposable {
readonly fetch?: (url: URL | string, init?: RequestInit) => Promise<Response>;
readonly url?: URL;
/**
* Every HTTP exchange the wired client performed, in order, including the
* connect-time negotiation. Recorded by the createMcpHandler entry arms
* only — scenarios on those arms use it to assert raw wire facts (request
* bodies, response status/content-type/bytes) that the typed client API
* does not expose.
*/
readonly httpLog?: readonly RecordedHttpExchange[];
}

/**
* The fourth argument controls the wire-format sniffer (see wire-sniffer.ts):
* every message the client sends or receives is validated against the SDK's
* spec-anchored Zod schemas. Tests that intentionally use vendor-extension
* methods pass `{ allowCustomMethods: true }`; tests that deliberately put
* malformed MCP on the wire pass `{ strictValidation: false }`.
* The fourth argument's sniffer options control the wire-format sniffer (see
* wire-sniffer.ts): every message the client sends or receives is validated
* against the SDK's spec-anchored Zod schemas. Tests that intentionally use
* vendor-extension methods pass `{ allowCustomMethods: true }`; tests that
* deliberately put malformed MCP on the wire pass `{ strictValidation: false }`.
* `entry` overrides the hosting options of the createMcpHandler entry arms
* (ignored by every other transport).
*/
export async function wire(transport: Transport, makeServer: ServerFactory, client: Client, sniff: SnifferOptions = {}): Promise<Wired> {
export interface WireOptions extends SnifferOptions {
/**
* createMcpHandler hosting overrides for the entry arms. Defaults:
* `{ legacy: 'stateless' }` on entryStateless (the canonical slot value) and
* modern-only strict (no legacy slot) on entryModern. `onerror` and
* `responseMode` pass through unchanged.
*/
entry?: CreateMcpHandlerOptions;
}

export async function wire(
transport: Transport,
makeServer: ServerFactory | EntryServerFactory,
client: Client,
sniff: WireOptions = {}
): Promise<Wired> {
switch (transport) {
case 'inMemory': {
const server = makeServer();
Expand DownExpand Up@@ -67,6 +130,47 @@ export async function wire(transport: Transport, makeServer: ServerFactory, clie
[Symbol.asyncDispose]: () => Promise.all([client.close(), handle.close()]).then(() => {})
};
}
case 'entryStateless':
case 'entryModern': {
// The dual-era HTTP entry (`createMcpHandler`) hosted in process via an
// injected fetch, exactly like the other HTTP arms. The scenario factory
// backs the entry directly (the entry calls it once per request with its
// per-request context). `entryStateless` serves the scenario's plain
// client through the entry's `legacy: 'stateless'` slot; `entryModern`
// keeps the endpoint modern-only strict and connects the client on the
// 2026-07-28 revision (pin-mode negotiation + the per-request envelope
// stop-gap). Every HTTP exchange is recorded on `httpLog`.
const handler = createMcpHandler(
makeServer,
transport === 'entryStateless' ? { legacy: 'stateless', ...sniff.entry } : { ...sniff.entry }
);
const url = new URL('http://in-process/mcp');
const httpLog: RecordedHttpExchange[] = [];
const fetch = async (u: URL | string, init?: RequestInit) => {
const request = new Request(u, init);
const response = await handler.fetch(request);
httpLog.push({
method: request.method.toUpperCase(),
...(typeof init?.body === 'string' && { requestBody: init.body }),
status: response.status,
contentType: response.headers.get('content-type') ?? '',
response: response.clone()
});
return response;
};
let clientTx = new StreamableHTTPClientTransport(url, { fetch });
if (transport === 'entryModern') {
pinModernNegotiation(client);
clientTx = attachModernEnvelope(clientTx);
}
await client.connect(sniffTransport(clientTx, 'client', sniff));
return {
fetch,
url,
httpLog,
[Symbol.asyncDispose]: () => Promise.all([client.close(), handler.close()]).then(() => {})
};
}
case 'sse': {
// The legacy SSE transport needs a real socket: the factory's server is hosted on the
// shipped SSEServerTransport (@modelcontextprotocol/server-legacy/sse) behind a loopback
Expand DownExpand Up@@ -212,6 +316,78 @@ export function hostStateless(makeServer: ServerFactory): { handleRequest: HttpH
};
}

// ───────────────────────────────────────────────────────────────────────────────
// createMcpHandler entry arms (entryStateless / entryModern) — client-side shims
// ───────────────────────────────────────────────────────────────────────────────

/** The protocol revision the entryModern arm negotiates and claims per request. */
const MODERN_REVISION: SpecVersion = '2026-07-28';

/**
* The per-request `_meta` envelope of a 2026-07-28 request, for scenario bodies
* that put raw HTTP requests on the wire (via `wired.fetch`) rather than going
* through the wired client. Typed calls through the wired client never need
* this — the entryModern arm attaches the envelope itself (see
* {@linkcode attachModernEnvelope}).
*/
export function modernEnvelopeMeta(clientInfo?: Implementation): Record<string, unknown> {
return {
[PROTOCOL_VERSION_META_KEY]: MODERN_REVISION,
[CLIENT_INFO_META_KEY]: clientInfo ?? { name: 'e2e-entry-client', version: '1.0.0' },
[CLIENT_CAPABILITIES_META_KEY]: {}
};
}

/**
* Put the (already constructed) scenario client into pinned 2026-07-28
* negotiation. Version negotiation is a constructor-only option and the
* scenario corpus constructs era-agnostic clients, so the entryModern arm flips
* the option on the instance before `connect()` — a harness stop-gap, not a
* public API. Clients that already opted into a negotiation mode are left
* untouched (their cells deliberately exercise that mode).
*/
function pinModernNegotiation(client: Client): void {
const internals = client as unknown as { _versionNegotiation?: { mode?: unknown } };
internals._versionNegotiation ??= { mode: { pin: MODERN_REVISION } };
}

/**
* The per-request `_meta` envelope stop-gap for the entryModern arm: the
* negotiating client only attaches the envelope to its `server/discover` probe
* today (automatic per-request emission is a client-side follow-up), so the
* harness re-attaches the same envelope to every later request and notification
* the scenario's typed calls put on the wire. The envelope is captured from the
* probe itself, so it always matches what the client actually claimed; messages
* that already carry a protocol-version claim (the probe, or a scenario's
* explicitly enveloped request) pass through untouched.
*
* Applied beneath the wire sniffer and `tapWire`, so recorded traffic shows the
* messages exactly as the scenario sent them while the wire carries the
* envelope the entry requires.
*/
function attachModernEnvelope<T extends SdkTransport>(transport: T): T {
let envelope: Record<string, unknown> | undefined;
const origSend = transport.send.bind(transport);
transport.send = async (message, opts) => {
let outbound = message;
if ('method' in message) {
const params = (message.params ?? {}) as { _meta?: Record<string, unknown> };
const meta = params._meta;
if (meta?.[PROTOCOL_VERSION_META_KEY] !== undefined) {
envelope ??= {
[PROTOCOL_VERSION_META_KEY]: meta[PROTOCOL_VERSION_META_KEY],
[CLIENT_INFO_META_KEY]: meta[CLIENT_INFO_META_KEY],
[CLIENT_CAPABILITIES_META_KEY]: meta[CLIENT_CAPABILITIES_META_KEY]
};
} else if (envelope !== undefined) {
outbound = { ...message, params: { ...params, _meta: { ...envelope, ...meta } } };
}
}
return origSend(outbound, opts);
};
return transport;
}

// ───────────────────────────────────────────────────────────────────────────────
// In-process stdio client — TEST-ONLY
//
Expand Down
20 changes: 16 additions & 4 deletions test/e2e/helpers/verifies.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,11 +18,23 @@
import { describe, test } from 'vitest';

import { REQUIREMENTS } from '../requirements.js';
import type { TestArgs } from '../types.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS } from '../types.js';
import type { Requirement, SpecVersion, TestArgs, Transport } from '../types.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS, ENTRY_TRANSPORTS, TRANSPORT_SPEC_VERSIONS } from '../types.js';

type TestBody = (args: TestArgs) => Promise<void>;

/** Whether a requirement's `entryExclusions` keep the given entry arm out of its cells. */
function excludedFromEntryArm(req: Requirement, transport: Transport): boolean {
if (!(ENTRY_TRANSPORTS as readonly Transport[]).includes(transport)) return false;
return (req.entryExclusions ?? []).some(x => x.arm === undefined || x.arm === transport);
}

/** Whether a transport arm serves the given spec version (era-fixed arms serve exactly one). */
function transportServesVersion(transport: Transport, version: SpecVersion): boolean {
const versions = TRANSPORT_SPEC_VERSIONS[transport];
return versions === undefined || versions.includes(version);
}

export function verifies(id: string | readonly string[], fn: TestBody, opts?: { title?: string }): void {
const ids = Array.isArray(id) ? id : [id];
for (const rid of ids) registerOne(rid, fn, opts);
Expand All@@ -33,13 +45,13 @@ function registerOne(id: string, fn: TestBody, opts?: { title?: string }): void
if (!req) throw new Error(`verifies('${id}'): unknown requirement id`);
if (req.deferred) throw new Error(`verifies('${id}'): requirement is deferred — drop the deferral or the test`);

const transports = req.transports ?? ALL_TRANSPORTS;
const transports = (req.transports ?? ALL_TRANSPORTS).filter(t => !excludedFromEntryArm(req, t));
const versions = ALL_SPEC_VERSIONS.filter(
v =>
(req.addedInSpecVersion === undefined || v >= req.addedInSpecVersion) &&
(req.removedInSpecVersion === undefined || v < req.removedInSpecVersion)
);
const cells = versions.flatMap(v => transports.map(t => [t, v] as const));
const cells = versions.flatMap(v => transports.filter(t => transportServesVersion(t, v)).map(t => [t, v] as const));

describe.each(cells)(`${id} [%s %s]`, (transport, protocolVersion) => {
const kf = req.knownFailures?.find(
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
20 changes: 20 additions & 0 deletions test/e2e/CLAUDE.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,6 +58,26 @@ note: 'stateless hosting has no server→client back-channel'
`addedInSpecVersion` / `removedInSpecVersion` bound the spec versions a requirement applies to. A behavior changed by a spec release gets a sibling entry: the new entry lists every retired id it replaces in `supersedes` (an array, requires `addedInSpecVersion`), and each retired
entry points back via `supersededBy` (requires `removedInSpecVersion`). A coverage gate enforces that the links resolve and are exactly symmetric.

## The createMcpHandler entry arms (entryStateless / entryModern)

Two transport arms host the dual-era HTTP entry (`createMcpHandler`) in process via an injected fetch, exactly like the other HTTP arms. They are era-fixed (`TRANSPORT_SPEC_VERSIONS`), so each registers cells on exactly one spec-version axis:

- `entryStateless` — the entry with the `legacy: 'stateless'` slot; the scenario's plain client is served per request through the slot. Cells run on the 2025-11-25 axis only.
- `entryModern` — the entry modern-only strict (no legacy slot); the scenario's client is put into pinned 2026-07-28 negotiation by the arm and the per-request `_meta` envelope is attached to every outgoing request/notification by the arm (a harness stop-gap until the client
emits it itself). Cells run on the 2026-07-28 axis only.

Both arms are part of the default transport list, so unrestricted requirements run through the entry automatically. When a requirement cannot run on an entry arm, annotate it with a machine-readable reason instead of bending the test:

```ts
entryExclusions: [{ arm: 'entryModern', reason: 'method-not-in-modern-registry' /* optional note */ }];
```

Omitting `arm` excludes both arms. The reasons (`EntryExclusionReason` in types.ts) are the acceptance checklist for re-admitting cells when the corresponding entry feature lands; a coverage gate rejects annotations that would never have an effect. Requirement families that the
per-request entry structurally cannot serve at all (server→client requests, sessions/resumability, standalone GET streams, subscriptions) are already expressed through their `transports` restrictions and need no annotation.

Arm-specific helpers: `wire()`'s fourth argument also accepts `entry` (createMcpHandler hosting overrides — e.g. a `responseMode` or a bring-your-own `legacy` slot value), the returned `Wired.httpLog` records every HTTP exchange (request body, status, content-type, a readable
response clone) for raw wire assertions, factories may accept the optional per-request context (`EntryServerFactory`), and `modernEnvelopeMeta()` builds the envelope for bodies that POST raw 2026-era requests through `wired.fetch`.

## Running

From the repo root (the suite is the `@modelcontextprotocol/test-e2e` workspace package):
Expand Down
29 changes: 29 additions & 0 deletions test/e2e/coverage.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,7 @@ import { fileURLToPath } from 'node:url';
import { expect, test } from 'vitest';

import { REQUIREMENTS } from './requirements.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS, ENTRY_TRANSPORTS, TRANSPORT_SPEC_VERSIONS } from './types.js';

const E2E_DIR = path.dirname(fileURLToPath(import.meta.url));

Expand DownExpand Up@@ -88,6 +89,34 @@ test('every transport-restricted requirement explains why in note', () => {
expect(missing).toEqual([]);
});

test('every entryExclusions annotation targets an entry arm the requirement would otherwise run on', () => {
const bad: string[] = [];
for (const [id, r] of Object.entries(REQUIREMENTS)) {
for (const exclusion of r.entryExclusions ?? []) {
const arms = exclusion.arm === undefined ? ENTRY_TRANSPORTS : [exclusion.arm];
for (const arm of arms) {
const transports = r.transports ?? ALL_TRANSPORTS;
if (!transports.includes(arm)) {
bad.push(`${id}: entryExclusions targets '${arm}', which the requirement's transports never include`);
continue;
}
const versions = ALL_SPEC_VERSIONS.filter(
v =>
(r.addedInSpecVersion === undefined || v >= r.addedInSpecVersion) &&
(r.removedInSpecVersion === undefined || v < r.removedInSpecVersion) &&
(TRANSPORT_SPEC_VERSIONS[arm]?.includes(v) ?? true)
);
if (versions.length === 0) {
bad.push(
`${id}: entryExclusions targets '${arm}', which registers no cells within the requirement's spec-version bounds`
);
}
}
}
}
expect(bad).toEqual([]);
});

test('supersedes/supersededBy links are symmetric and resolve', () => {
const bad: string[] = [];
for (const [id, req] of Object.entries(REQUIREMENTS)) {
Expand Down
29 changes: 29 additions & 0 deletions test/e2e/fixtures/dual-era-stdio-server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
/**
* Runnable dual-era stdio MCP server fixture for the dual-era stdio e2e cells.
*
* `eraSupport: 'dual-era'` is the single declared act on an otherwise ordinary
* hand-constructed McpServer connected to the unchanged StdioServerTransport.
* Spawned as a real child process (via tsx) by
* test/e2e/scenarios/stdio-dual-era.test.ts; exits when its stdin reaches EOF.
*/

import { McpServer } from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
import { z } from 'zod/v4';

const server = new McpServer(
{ name: 'dual-era-stdio-e2e-fixture', version: '1.0.0' },
{ capabilities: { tools: {} }, eraSupport: 'dual-era' }
);

server.registerTool(
'echo',
{
description: 'Echoes the input text back as a text content block.',
inputSchema: z.object({ text: z.string() })
},
({ text }) => ({ content: [{ type: 'text', text }] })
);

await server.connect(new StdioServerTransport());
process.stderr.write('[dual-era-stdio-server] ready\n');
194 changes: 185 additions & 9 deletions test/e2e/helpers/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,30 +15,93 @@ import { PassThrough } from 'node:stream';

import type { Client } from '@modelcontextprotocol/client';
import { SSEClientTransport, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
import type { EventStore, JSONRPCMessage, McpServer, Server } from '@modelcontextprotocol/server';
import { InMemoryTransport, ReadBuffer, serializeMessage, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server';
import { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, PROTOCOL_VERSION_META_KEY } from '@modelcontextprotocol/core';
import type {
CreateMcpHandlerOptions,
EventStore,
Implementation,
JSONRPCMessage,
McpRequestContext,
McpServer,
Server,
Transport as SdkTransport
} from '@modelcontextprotocol/server';
import {
createMcpHandler,
InMemoryTransport,
ReadBuffer,
serializeMessage,
WebStandardStreamableHTTPServerTransport
} from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';

import type { Transport } from '../types.js';
import type { SpecVersion, Transport } from '../types.js';
import { startLegacySseHost } from './sse-host.js';
import type { SnifferOptions } from './wire-sniffer.js';
import { sniffTransport } from './wire-sniffer.js';

export type ServerFactory = () => McpServer | Server;

/**
* A factory that optionally consumes the createMcpHandler per-request context.
* The context is only supplied on the entry arms (where the entry constructs a
* fresh instance per request); on every other arm the factory is called with no
* arguments, so declare the parameter optional.
*/
export type EntryServerFactory = (ctx?: McpRequestContext) => McpServer | Server;

/** One HTTP exchange recorded by the entry arms (see {@linkcode Wired.httpLog}). */
export interface RecordedHttpExchange {
/** HTTP request method (GET/POST/DELETE). */
method: string;
/** The request body text, when one was sent as a string. */
requestBody?: string;
/** HTTP response status. */
status: number;
/** Response content-type header (empty string when absent). */
contentType: string;
/** An unread clone of the HTTP response, for byte-level assertions (`await exchange.response.text()`). */
response: Response;
}

export interface Wired extends AsyncDisposable {
readonly fetch?: (url: URL | string, init?: RequestInit) => Promise<Response>;
readonly url?: URL;
/**
* Every HTTP exchange the wired client performed, in order, including the
* connect-time negotiation. Recorded by the createMcpHandler entry arms
* only — scenarios on those arms use it to assert raw wire facts (request
* bodies, response status/content-type/bytes) that the typed client API
* does not expose.
*/
readonly httpLog?: readonly RecordedHttpExchange[];
}

/**
* The fourth argument controls the wire-format sniffer (see wire-sniffer.ts):
* every message the client sends or receives is validated against the SDK's
* spec-anchored Zod schemas. Tests that intentionally use vendor-extension
* methods pass `{ allowCustomMethods: true }`; tests that deliberately put
* malformed MCP on the wire pass `{ strictValidation: false }`.
* The fourth argument's sniffer options control the wire-format sniffer (see
* wire-sniffer.ts): every message the client sends or receives is validated
* against the SDK's spec-anchored Zod schemas. Tests that intentionally use
* vendor-extension methods pass `{ allowCustomMethods: true }`; tests that
* deliberately put malformed MCP on the wire pass `{ strictValidation: false }`.
* `entry` overrides the hosting options of the createMcpHandler entry arms
* (ignored by every other transport).
*/
export async function wire(transport: Transport, makeServer: ServerFactory, client: Client, sniff: SnifferOptions = {}): Promise<Wired> {
export interface WireOptions extends SnifferOptions {
/**
* createMcpHandler hosting overrides for the entry arms. Defaults:
* `{ legacy: 'stateless' }` on entryStateless (the canonical slot value) and
* modern-only strict (no legacy slot) on entryModern. `onerror` and
* `responseMode` pass through unchanged.
*/
entry?: CreateMcpHandlerOptions;
}

export async function wire(
transport: Transport,
makeServer: ServerFactory | EntryServerFactory,
client: Client,
sniff: WireOptions = {}
): Promise<Wired> {
switch (transport) {
case 'inMemory': {
const server = makeServer();
Expand DownExpand Up@@ -67,6 +130,47 @@ export async function wire(transport: Transport, makeServer: ServerFactory, clie
[Symbol.asyncDispose]: () => Promise.all([client.close(), handle.close()]).then(() => {})
};
}
case 'entryStateless':
case 'entryModern': {
// The dual-era HTTP entry (`createMcpHandler`) hosted in process via an
// injected fetch, exactly like the other HTTP arms. The scenario factory
// backs the entry directly (the entry calls it once per request with its
// per-request context). `entryStateless` serves the scenario's plain
// client through the entry's `legacy: 'stateless'` slot; `entryModern`
// keeps the endpoint modern-only strict and connects the client on the
// 2026-07-28 revision (pin-mode negotiation + the per-request envelope
// stop-gap). Every HTTP exchange is recorded on `httpLog`.
const handler = createMcpHandler(
makeServer,
transport === 'entryStateless' ? { legacy: 'stateless', ...sniff.entry } : { ...sniff.entry }
);
const url = new URL('http://in-process/mcp');
const httpLog: RecordedHttpExchange[] = [];
const fetch = async (u: URL | string, init?: RequestInit) => {
const request = new Request(u, init);
const response = await handler.fetch(request);
httpLog.push({
method: request.method.toUpperCase(),
...(typeof init?.body === 'string' && { requestBody: init.body }),
status: response.status,
contentType: response.headers.get('content-type') ?? '',
response: response.clone()
});
return response;
};
let clientTx = new StreamableHTTPClientTransport(url, { fetch });
if (transport === 'entryModern') {
pinModernNegotiation(client);
clientTx = attachModernEnvelope(clientTx);
}
await client.connect(sniffTransport(clientTx, 'client', sniff));
return {
fetch,
url,
httpLog,
[Symbol.asyncDispose]: () => Promise.all([client.close(), handler.close()]).then(() => {})
};
}
case 'sse': {
// The legacy SSE transport needs a real socket: the factory's server is hosted on the
// shipped SSEServerTransport (@modelcontextprotocol/server-legacy/sse) behind a loopback
Expand DownExpand Up@@ -212,6 +316,78 @@ export function hostStateless(makeServer: ServerFactory): { handleRequest: HttpH
};
}

// ───────────────────────────────────────────────────────────────────────────────
// createMcpHandler entry arms (entryStateless / entryModern) — client-side shims
// ───────────────────────────────────────────────────────────────────────────────

/** The protocol revision the entryModern arm negotiates and claims per request. */
const MODERN_REVISION: SpecVersion = '2026-07-28';

/**
* The per-request `_meta` envelope of a 2026-07-28 request, for scenario bodies
* that put raw HTTP requests on the wire (via `wired.fetch`) rather than going
* through the wired client. Typed calls through the wired client never need
* this — the entryModern arm attaches the envelope itself (see
* {@linkcode attachModernEnvelope}).
*/
export function modernEnvelopeMeta(clientInfo?: Implementation): Record<string, unknown> {
return {
[PROTOCOL_VERSION_META_KEY]: MODERN_REVISION,
[CLIENT_INFO_META_KEY]: clientInfo ?? { name: 'e2e-entry-client', version: '1.0.0' },
[CLIENT_CAPABILITIES_META_KEY]: {}
};
}

/**
* Put the (already constructed) scenario client into pinned 2026-07-28
* negotiation. Version negotiation is a constructor-only option and the
* scenario corpus constructs era-agnostic clients, so the entryModern arm flips
* the option on the instance before `connect()` — a harness stop-gap, not a
* public API. Clients that already opted into a negotiation mode are left
* untouched (their cells deliberately exercise that mode).
*/
function pinModernNegotiation(client: Client): void {
const internals = client as unknown as { _versionNegotiation?: { mode?: unknown } };
internals._versionNegotiation ??= { mode: { pin: MODERN_REVISION } };
}

/**
* The per-request `_meta` envelope stop-gap for the entryModern arm: the
* negotiating client only attaches the envelope to its `server/discover` probe
* today (automatic per-request emission is a client-side follow-up), so the
* harness re-attaches the same envelope to every later request and notification
* the scenario's typed calls put on the wire. The envelope is captured from the
* probe itself, so it always matches what the client actually claimed; messages
* that already carry a protocol-version claim (the probe, or a scenario's
* explicitly enveloped request) pass through untouched.
*
* Applied beneath the wire sniffer and `tapWire`, so recorded traffic shows the
* messages exactly as the scenario sent them while the wire carries the
* envelope the entry requires.
*/
function attachModernEnvelope<T extends SdkTransport>(transport: T): T {
let envelope: Record<string, unknown> | undefined;
const origSend = transport.send.bind(transport);
transport.send = async (message, opts) => {
let outbound = message;
if ('method' in message) {
const params = (message.params ?? {}) as { _meta?: Record<string, unknown> };
const meta = params._meta;
if (meta?.[PROTOCOL_VERSION_META_KEY] !== undefined) {
envelope ??= {
[PROTOCOL_VERSION_META_KEY]: meta[PROTOCOL_VERSION_META_KEY],
[CLIENT_INFO_META_KEY]: meta[CLIENT_INFO_META_KEY],
[CLIENT_CAPABILITIES_META_KEY]: meta[CLIENT_CAPABILITIES_META_KEY]
};
} else if (envelope !== undefined) {
outbound = { ...message, params: { ...params, _meta: { ...envelope, ...meta } } };
}
}
return origSend(outbound, opts);
};
return transport;
}

// ───────────────────────────────────────────────────────────────────────────────
// In-process stdio client — TEST-ONLY
//
Expand Down
20 changes: 16 additions & 4 deletions test/e2e/helpers/verifies.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,11 +18,23 @@
import { describe, test } from 'vitest';

import { REQUIREMENTS } from '../requirements.js';
import type { TestArgs } from '../types.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS } from '../types.js';
import type { Requirement, SpecVersion, TestArgs, Transport } from '../types.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS, ENTRY_TRANSPORTS, TRANSPORT_SPEC_VERSIONS } from '../types.js';

type TestBody = (args: TestArgs) => Promise<void>;

/** Whether a requirement's `entryExclusions` keep the given entry arm out of its cells. */
function excludedFromEntryArm(req: Requirement, transport: Transport): boolean {
if (!(ENTRY_TRANSPORTS as readonly Transport[]).includes(transport)) return false;
return (req.entryExclusions ?? []).some(x => x.arm === undefined || x.arm === transport);
}

/** Whether a transport arm serves the given spec version (era-fixed arms serve exactly one). */
function transportServesVersion(transport: Transport, version: SpecVersion): boolean {
const versions = TRANSPORT_SPEC_VERSIONS[transport];
return versions === undefined || versions.includes(version);
}

export function verifies(id: string | readonly string[], fn: TestBody, opts?: { title?: string }): void {
const ids = Array.isArray(id) ? id : [id];
for (const rid of ids) registerOne(rid, fn, opts);
Expand All@@ -33,13 +45,13 @@ function registerOne(id: string, fn: TestBody, opts?: { title?: string }): void
if (!req) throw new Error(`verifies('${id}'): unknown requirement id`);
if (req.deferred) throw new Error(`verifies('${id}'): requirement is deferred — drop the deferral or the test`);

const transports = req.transports ?? ALL_TRANSPORTS;
const transports = (req.transports ?? ALL_TRANSPORTS).filter(t => !excludedFromEntryArm(req, t));
const versions = ALL_SPEC_VERSIONS.filter(
v =>
(req.addedInSpecVersion === undefined || v >= req.addedInSpecVersion) &&
(req.removedInSpecVersion === undefined || v < req.removedInSpecVersion)
);
const cells = versions.flatMap(v => transports.map(t => [t, v] as const));
const cells = versions.flatMap(v => transports.filter(t => transportServesVersion(t, v)).map(t => [t, v] as const));

describe.each(cells)(`${id} [%s %s]`, (transport, protocolVersion) => {
const kf = req.knownFailures?.find(
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
20 changes: 20 additions & 0 deletions test/e2e/CLAUDE.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,6 +58,26 @@ note: 'stateless hosting has no server→client back-channel'
`addedInSpecVersion` / `removedInSpecVersion` bound the spec versions a requirement applies to. A behavior changed by a spec release gets a sibling entry: the new entry lists every retired id it replaces in `supersedes` (an array, requires `addedInSpecVersion`), and each retired
entry points back via `supersededBy` (requires `removedInSpecVersion`). A coverage gate enforces that the links resolve and are exactly symmetric.

## The createMcpHandler entry arms (entryStateless / entryModern)

Two transport arms host the dual-era HTTP entry (`createMcpHandler`) in process via an injected fetch, exactly like the other HTTP arms. They are era-fixed (`TRANSPORT_SPEC_VERSIONS`), so each registers cells on exactly one spec-version axis:

- `entryStateless` — the entry with the `legacy: 'stateless'` slot; the scenario's plain client is served per request through the slot. Cells run on the 2025-11-25 axis only.
- `entryModern` — the entry modern-only strict (no legacy slot); the scenario's client is put into pinned 2026-07-28 negotiation by the arm and the per-request `_meta` envelope is attached to every outgoing request/notification by the arm (a harness stop-gap until the client
emits it itself). Cells run on the 2026-07-28 axis only.

Both arms are part of the default transport list, so unrestricted requirements run through the entry automatically. When a requirement cannot run on an entry arm, annotate it with a machine-readable reason instead of bending the test:

```ts
entryExclusions: [{ arm: 'entryModern', reason: 'method-not-in-modern-registry' /* optional note */ }];
```

Omitting `arm` excludes both arms. The reasons (`EntryExclusionReason` in types.ts) are the acceptance checklist for re-admitting cells when the corresponding entry feature lands; a coverage gate rejects annotations that would never have an effect. Requirement families that the
per-request entry structurally cannot serve at all (server→client requests, sessions/resumability, standalone GET streams, subscriptions) are already expressed through their `transports` restrictions and need no annotation.

Arm-specific helpers: `wire()`'s fourth argument also accepts `entry` (createMcpHandler hosting overrides — e.g. a `responseMode` or a bring-your-own `legacy` slot value), the returned `Wired.httpLog` records every HTTP exchange (request body, status, content-type, a readable
response clone) for raw wire assertions, factories may accept the optional per-request context (`EntryServerFactory`), and `modernEnvelopeMeta()` builds the envelope for bodies that POST raw 2026-era requests through `wired.fetch`.

## Running

From the repo root (the suite is the `@modelcontextprotocol/test-e2e` workspace package):
Expand Down
29 changes: 29 additions & 0 deletions test/e2e/coverage.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,7 @@ import { fileURLToPath } from 'node:url';
import { expect, test } from 'vitest';

import { REQUIREMENTS } from './requirements.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS, ENTRY_TRANSPORTS, TRANSPORT_SPEC_VERSIONS } from './types.js';

const E2E_DIR = path.dirname(fileURLToPath(import.meta.url));

Expand DownExpand Up@@ -88,6 +89,34 @@ test('every transport-restricted requirement explains why in note', () => {
expect(missing).toEqual([]);
});

test('every entryExclusions annotation targets an entry arm the requirement would otherwise run on', () => {
const bad: string[] = [];
for (const [id, r] of Object.entries(REQUIREMENTS)) {
for (const exclusion of r.entryExclusions ?? []) {
const arms = exclusion.arm === undefined ? ENTRY_TRANSPORTS : [exclusion.arm];
for (const arm of arms) {
const transports = r.transports ?? ALL_TRANSPORTS;
if (!transports.includes(arm)) {
bad.push(`${id}: entryExclusions targets '${arm}', which the requirement's transports never include`);
continue;
}
const versions = ALL_SPEC_VERSIONS.filter(
v =>
(r.addedInSpecVersion === undefined || v >= r.addedInSpecVersion) &&
(r.removedInSpecVersion === undefined || v < r.removedInSpecVersion) &&
(TRANSPORT_SPEC_VERSIONS[arm]?.includes(v) ?? true)
);
if (versions.length === 0) {
bad.push(
`${id}: entryExclusions targets '${arm}', which registers no cells within the requirement's spec-version bounds`
);
}
}
}
}
expect(bad).toEqual([]);
});

test('supersedes/supersededBy links are symmetric and resolve', () => {
const bad: string[] = [];
for (const [id, req] of Object.entries(REQUIREMENTS)) {
Expand Down
29 changes: 29 additions & 0 deletions test/e2e/fixtures/dual-era-stdio-server.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
/**
* Runnable dual-era stdio MCP server fixture for the dual-era stdio e2e cells.
*
* `eraSupport: 'dual-era'` is the single declared act on an otherwise ordinary
* hand-constructed McpServer connected to the unchanged StdioServerTransport.
* Spawned as a real child process (via tsx) by
* test/e2e/scenarios/stdio-dual-era.test.ts; exits when its stdin reaches EOF.
*/

import { McpServer } from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
import { z } from 'zod/v4';

const server = new McpServer(
{ name: 'dual-era-stdio-e2e-fixture', version: '1.0.0' },
{ capabilities: { tools: {} }, eraSupport: 'dual-era' }
);

server.registerTool(
'echo',
{
description: 'Echoes the input text back as a text content block.',
inputSchema: z.object({ text: z.string() })
},
({ text }) => ({ content: [{ type: 'text', text }] })
);

await server.connect(new StdioServerTransport());
process.stderr.write('[dual-era-stdio-server] ready\n');
194 changes: 185 additions & 9 deletions test/e2e/helpers/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,30 +15,93 @@ import { PassThrough } from 'node:stream';

import type { Client } from '@modelcontextprotocol/client';
import { SSEClientTransport, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
import type { EventStore, JSONRPCMessage, McpServer, Server } from '@modelcontextprotocol/server';
import { InMemoryTransport, ReadBuffer, serializeMessage, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server';
import { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, PROTOCOL_VERSION_META_KEY } from '@modelcontextprotocol/core';
import type {
CreateMcpHandlerOptions,
EventStore,
Implementation,
JSONRPCMessage,
McpRequestContext,
McpServer,
Server,
Transport as SdkTransport
} from '@modelcontextprotocol/server';
import {
createMcpHandler,
InMemoryTransport,
ReadBuffer,
serializeMessage,
WebStandardStreamableHTTPServerTransport
} from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';

import type { Transport } from '../types.js';
import type { SpecVersion, Transport } from '../types.js';
import { startLegacySseHost } from './sse-host.js';
import type { SnifferOptions } from './wire-sniffer.js';
import { sniffTransport } from './wire-sniffer.js';

export type ServerFactory = () => McpServer | Server;

/**
* A factory that optionally consumes the createMcpHandler per-request context.
* The context is only supplied on the entry arms (where the entry constructs a
* fresh instance per request); on every other arm the factory is called with no
* arguments, so declare the parameter optional.
*/
export type EntryServerFactory = (ctx?: McpRequestContext) => McpServer | Server;

/** One HTTP exchange recorded by the entry arms (see {@linkcode Wired.httpLog}). */
export interface RecordedHttpExchange {
/** HTTP request method (GET/POST/DELETE). */
method: string;
/** The request body text, when one was sent as a string. */
requestBody?: string;
/** HTTP response status. */
status: number;
/** Response content-type header (empty string when absent). */
contentType: string;
/** An unread clone of the HTTP response, for byte-level assertions (`await exchange.response.text()`). */
response: Response;
}

export interface Wired extends AsyncDisposable {
readonly fetch?: (url: URL | string, init?: RequestInit) => Promise<Response>;
readonly url?: URL;
/**
* Every HTTP exchange the wired client performed, in order, including the
* connect-time negotiation. Recorded by the createMcpHandler entry arms
* only — scenarios on those arms use it to assert raw wire facts (request
* bodies, response status/content-type/bytes) that the typed client API
* does not expose.
*/
readonly httpLog?: readonly RecordedHttpExchange[];
}

/**
* The fourth argument controls the wire-format sniffer (see wire-sniffer.ts):
* every message the client sends or receives is validated against the SDK's
* spec-anchored Zod schemas. Tests that intentionally use vendor-extension
* methods pass `{ allowCustomMethods: true }`; tests that deliberately put
* malformed MCP on the wire pass `{ strictValidation: false }`.
* The fourth argument's sniffer options control the wire-format sniffer (see
* wire-sniffer.ts): every message the client sends or receives is validated
* against the SDK's spec-anchored Zod schemas. Tests that intentionally use
* vendor-extension methods pass `{ allowCustomMethods: true }`; tests that
* deliberately put malformed MCP on the wire pass `{ strictValidation: false }`.
* `entry` overrides the hosting options of the createMcpHandler entry arms
* (ignored by every other transport).
*/
export async function wire(transport: Transport, makeServer: ServerFactory, client: Client, sniff: SnifferOptions = {}): Promise<Wired> {
export interface WireOptions extends SnifferOptions {
/**
* createMcpHandler hosting overrides for the entry arms. Defaults:
* `{ legacy: 'stateless' }` on entryStateless (the canonical slot value) and
* modern-only strict (no legacy slot) on entryModern. `onerror` and
* `responseMode` pass through unchanged.
*/
entry?: CreateMcpHandlerOptions;
}

export async function wire(
transport: Transport,
makeServer: ServerFactory | EntryServerFactory,
client: Client,
sniff: WireOptions = {}
): Promise<Wired> {
switch (transport) {
case 'inMemory': {
const server = makeServer();
Expand DownExpand Up@@ -67,6 +130,47 @@ export async function wire(transport: Transport, makeServer: ServerFactory, clie
[Symbol.asyncDispose]: () => Promise.all([client.close(), handle.close()]).then(() => {})
};
}
case 'entryStateless':
case 'entryModern': {
// The dual-era HTTP entry (`createMcpHandler`) hosted in process via an
// injected fetch, exactly like the other HTTP arms. The scenario factory
// backs the entry directly (the entry calls it once per request with its
// per-request context). `entryStateless` serves the scenario's plain
// client through the entry's `legacy: 'stateless'` slot; `entryModern`
// keeps the endpoint modern-only strict and connects the client on the
// 2026-07-28 revision (pin-mode negotiation + the per-request envelope
// stop-gap). Every HTTP exchange is recorded on `httpLog`.
const handler = createMcpHandler(
makeServer,
transport === 'entryStateless' ? { legacy: 'stateless', ...sniff.entry } : { ...sniff.entry }
);
const url = new URL('http://in-process/mcp');
const httpLog: RecordedHttpExchange[] = [];
const fetch = async (u: URL | string, init?: RequestInit) => {
const request = new Request(u, init);
const response = await handler.fetch(request);
httpLog.push({
method: request.method.toUpperCase(),
...(typeof init?.body === 'string' && { requestBody: init.body }),
status: response.status,
contentType: response.headers.get('content-type') ?? '',
response: response.clone()
});
return response;
};
let clientTx = new StreamableHTTPClientTransport(url, { fetch });
if (transport === 'entryModern') {
pinModernNegotiation(client);
clientTx = attachModernEnvelope(clientTx);
}
await client.connect(sniffTransport(clientTx, 'client', sniff));
return {
fetch,
url,
httpLog,
[Symbol.asyncDispose]: () => Promise.all([client.close(), handler.close()]).then(() => {})
};
}
case 'sse': {
// The legacy SSE transport needs a real socket: the factory's server is hosted on the
// shipped SSEServerTransport (@modelcontextprotocol/server-legacy/sse) behind a loopback
Expand DownExpand Up@@ -212,6 +316,78 @@ export function hostStateless(makeServer: ServerFactory): { handleRequest: HttpH
};
}

// ───────────────────────────────────────────────────────────────────────────────
// createMcpHandler entry arms (entryStateless / entryModern) — client-side shims
// ───────────────────────────────────────────────────────────────────────────────

/** The protocol revision the entryModern arm negotiates and claims per request. */
const MODERN_REVISION: SpecVersion = '2026-07-28';

/**
* The per-request `_meta` envelope of a 2026-07-28 request, for scenario bodies
* that put raw HTTP requests on the wire (via `wired.fetch`) rather than going
* through the wired client. Typed calls through the wired client never need
* this — the entryModern arm attaches the envelope itself (see
* {@linkcode attachModernEnvelope}).
*/
export function modernEnvelopeMeta(clientInfo?: Implementation): Record<string, unknown> {
return {
[PROTOCOL_VERSION_META_KEY]: MODERN_REVISION,
[CLIENT_INFO_META_KEY]: clientInfo ?? { name: 'e2e-entry-client', version: '1.0.0' },
[CLIENT_CAPABILITIES_META_KEY]: {}
};
}

/**
* Put the (already constructed) scenario client into pinned 2026-07-28
* negotiation. Version negotiation is a constructor-only option and the
* scenario corpus constructs era-agnostic clients, so the entryModern arm flips
* the option on the instance before `connect()` — a harness stop-gap, not a
* public API. Clients that already opted into a negotiation mode are left
* untouched (their cells deliberately exercise that mode).
*/
function pinModernNegotiation(client: Client): void {
const internals = client as unknown as { _versionNegotiation?: { mode?: unknown } };
internals._versionNegotiation ??= { mode: { pin: MODERN_REVISION } };
}

/**
* The per-request `_meta` envelope stop-gap for the entryModern arm: the
* negotiating client only attaches the envelope to its `server/discover` probe
* today (automatic per-request emission is a client-side follow-up), so the
* harness re-attaches the same envelope to every later request and notification
* the scenario's typed calls put on the wire. The envelope is captured from the
* probe itself, so it always matches what the client actually claimed; messages
* that already carry a protocol-version claim (the probe, or a scenario's
* explicitly enveloped request) pass through untouched.
*
* Applied beneath the wire sniffer and `tapWire`, so recorded traffic shows the
* messages exactly as the scenario sent them while the wire carries the
* envelope the entry requires.
*/
function attachModernEnvelope<T extends SdkTransport>(transport: T): T {
let envelope: Record<string, unknown> | undefined;
const origSend = transport.send.bind(transport);
transport.send = async (message, opts) => {
let outbound = message;
if ('method' in message) {
const params = (message.params ?? {}) as { _meta?: Record<string, unknown> };
const meta = params._meta;
if (meta?.[PROTOCOL_VERSION_META_KEY] !== undefined) {
envelope ??= {
[PROTOCOL_VERSION_META_KEY]: meta[PROTOCOL_VERSION_META_KEY],
[CLIENT_INFO_META_KEY]: meta[CLIENT_INFO_META_KEY],
[CLIENT_CAPABILITIES_META_KEY]: meta[CLIENT_CAPABILITIES_META_KEY]
};
} else if (envelope !== undefined) {
outbound = { ...message, params: { ...params, _meta: { ...envelope, ...meta } } };
}
}
return origSend(outbound, opts);
};
return transport;
}

// ───────────────────────────────────────────────────────────────────────────────
// In-process stdio client — TEST-ONLY
//
Expand Down
20 changes: 16 additions & 4 deletions test/e2e/helpers/verifies.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,11 +18,23 @@
import { describe, test } from 'vitest';

import { REQUIREMENTS } from '../requirements.js';
import type { TestArgs } from '../types.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS } from '../types.js';
import type { Requirement, SpecVersion, TestArgs, Transport } from '../types.js';
import { ALL_SPEC_VERSIONS, ALL_TRANSPORTS, ENTRY_TRANSPORTS, TRANSPORT_SPEC_VERSIONS } from '../types.js';

type TestBody = (args: TestArgs) => Promise<void>;

/** Whether a requirement's `entryExclusions` keep the given entry arm out of its cells. */
function excludedFromEntryArm(req: Requirement, transport: Transport): boolean {
if (!(ENTRY_TRANSPORTS as readonly Transport[]).includes(transport)) return false;
return (req.entryExclusions ?? []).some(x => x.arm === undefined || x.arm === transport);
}

/** Whether a transport arm serves the given spec version (era-fixed arms serve exactly one). */
function transportServesVersion(transport: Transport, version: SpecVersion): boolean {
const versions = TRANSPORT_SPEC_VERSIONS[transport];
return versions === undefined || versions.includes(version);
}

export function verifies(id: string | readonly string[], fn: TestBody, opts?: { title?: string }): void {
const ids = Array.isArray(id) ? id : [id];
for (const rid of ids) registerOne(rid, fn, opts);
Expand All@@ -33,13 +45,13 @@ function registerOne(id: string, fn: TestBody, opts?: { title?: string }): void
if (!req) throw new Error(`verifies('${id}'): unknown requirement id`);
if (req.deferred) throw new Error(`verifies('${id}'): requirement is deferred — drop the deferral or the test`);

const transports = req.transports ?? ALL_TRANSPORTS;
const transports = (req.transports ?? ALL_TRANSPORTS).filter(t => !excludedFromEntryArm(req, t));
const versions = ALL_SPEC_VERSIONS.filter(
v =>
(req.addedInSpecVersion === undefined || v >= req.addedInSpecVersion) &&
(req.removedInSpecVersion === undefined || v < req.removedInSpecVersion)
);
const cells = versions.flatMap(v => transports.map(t => [t, v] as const));
const cells = versions.flatMap(v => transports.filter(t => transportServesVersion(t, v)).map(t => [t, v] as const));

describe.each(cells)(`${id} [%s %s]`, (transport, protocolVersion) => {
const kf = req.knownFailures?.find(
Expand Down
Loading
Loading