From 18529908b336900c74ac5f2a60045cc45f220f66 Mon Sep 17 00:00:00 2001 From: Tom Beckenham <34339192+tombeckenham@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:32:56 +1100 Subject: [PATCH 1/2] fix(ai-mcp): follow the final MCP Events webhook spec Send Mcp-Param headers, accept a gap with no cursor, and verify the raw webhook timestamp. --- .changeset/mcp-events-sep-3415-headers.md | 5 + docs/tools/mcp-events.md | 14 +- examples/react/mcp-events/src/lib/desk.ts | 5 +- packages/ai-mcp/skills/ai-mcp/SKILL.md | 10 +- packages/ai-mcp/src/client.ts | 16 +- packages/ai-mcp/src/errors.ts | 1 + packages/ai-mcp/src/events/capability.ts | 3 +- packages/ai-mcp/src/events/direct.ts | 68 ++++-- packages/ai-mcp/src/events/errors-map.ts | 1 + packages/ai-mcp/src/events/list.ts | 12 +- packages/ai-mcp/src/events/param-headers.ts | 214 ++++++++++++++++++ packages/ai-mcp/src/events/signature.ts | 11 +- packages/ai-mcp/src/events/types.ts | 11 +- packages/ai-mcp/src/events/webhook.ts | 2 +- packages/ai-mcp/src/events/wire.ts | 14 +- packages/ai-mcp/src/transport.ts | 115 +++++----- .../ai-mcp/tests/events/client-events.test.ts | 135 +++++++++++ packages/ai-mcp/tests/events/direct.test.ts | 86 ++++++- packages/ai-mcp/tests/events/e2e.test.ts | 2 +- .../ai-mcp/tests/events/errors-map.test.ts | 1 + .../ai-mcp/tests/events/param-headers.test.ts | 123 ++++++++++ .../ai-mcp/tests/events/signature.test.ts | 33 ++- packages/ai-mcp/tests/events/webhook.test.ts | 33 ++- packages/ai-mcp/tests/events/wire.test.ts | 48 +++- packages/ai-mcp/tests/helpers/sign-webhook.ts | 32 ++- packages/ai-mcp/tests/transport.test.ts | 44 ++++ testing/e2e/src/lib/mcp-events-session.ts | 4 +- 27 files changed, 922 insertions(+), 121 deletions(-) create mode 100644 .changeset/mcp-events-sep-3415-headers.md create mode 100644 packages/ai-mcp/src/events/param-headers.ts create mode 100644 packages/ai-mcp/tests/events/param-headers.test.ts diff --git a/.changeset/mcp-events-sep-3415-headers.md b/.changeset/mcp-events-sep-3415-headers.md new file mode 100644 index 0000000000..bbfc624990 --- /dev/null +++ b/.changeset/mcp-events-sep-3415-headers.md @@ -0,0 +1,5 @@ +--- +'@tanstack/ai-mcp': patch +--- + +MCP Events follows the final text of SEP-3415 for webhook delivery. `events/subscribe` and `events/unsubscribe` send `Mcp-Name` and `Mcp-Param-*` on HTTP, SSE, and a Streamable HTTP transport instance. An event type whose `x-mcp-header` annotation breaks the transport rules is left out of `events/list`. A control message with no cursor is accepted, and `onGap` can receive `cursor: null`. Webhook signatures use the raw `webhook-timestamp` header, so a timestamp with a leading zero still verifies. Event occurrences keep a JSON object `_meta`. A HeaderMismatch (`-32020`) makes the client list events again and retry that request once. diff --git a/docs/tools/mcp-events.md b/docs/tools/mcp-events.md index db597afb6f..d3258e47a7 100644 --- a/docs/tools/mcp-events.md +++ b/docs/tools/mcp-events.md @@ -16,7 +16,7 @@ An MCP server can push work to you: a new incident, a finished job, a ticket cha `@tanstack/ai-mcp` implements the MCP Events extension (SEP-3415) for webhook delivery. You list event types, subscribe with a callback URL, and handle deliveries with `createMCPEventWebhook`. -> **Experimental.** The wire format follows [SEP-3415](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/3415) draft revision `2ec39b9`. Method names and error codes can still change. +> **Experimental.** The wire format is the final text of [SEP-3415](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/seps/3415-events-extension.md). This package sends webhook deliveries only. A TanStack Start app that subscribes and receives a signed webhook is in [Subscribe to MCP Events](../tutorials/mcp-events). @@ -154,8 +154,8 @@ import { queue } from './queue' const store = inMemoryMCPEventStore() const webhook = createMCPEventWebhook({ store, - onEvent: async ({ event }) => { - await queue.send(event) + onEvent: async ({ event, messageId }) => { + await queue.send({ messageId, event }) }, }) @@ -177,8 +177,8 @@ const app = express() const store = inMemoryMCPEventStore() const webhook = createMCPEventWebhook({ store, - onEvent: async ({ event }) => { - await queue.send(event) + onEvent: async ({ event, messageId }) => { + await queue.send({ messageId, event }) }, }) @@ -254,7 +254,7 @@ async function renewDue(store: MCPEventStore, mcp: MCPClient) { | Payload | Handler | Store effect | |---|---|---| | Event | `onEvent` | Writes `event.cursor` when the field is present | -| `{ type: 'gap', cursor }` | `onGap` | Sets `cursor` and `truncated: true` | +| `{ type: 'gap', cursor }` | `onGap` | Sets `cursor`. A missing cursor is stored as `null`. Also sets `truncated: true` | | `{ type: 'terminated', error }` | `onTerminated` | Deletes the subscription | | `{ type: 'verification', challenge }` | none | Echoes `{ challenge }` with 200 | @@ -382,6 +382,6 @@ Treat that snippet as a sketch. Production delivery needs a durable store, retri | 401 without a query string | A proxy dropped `mcp_event_subscription` | | Duplicate `onEvent` calls | Dedupe on `messageId`. 503 after a store failure retries | | Subscribe times out | The client deletes the pending record. Call `subscribe` again | -| `Mcp-Name` missing | With `experimental_events` set, HTTP and SSE transports add it to `events/subscribe` and `events/unsubscribe`. Non-ASCII names use `=?base64?...?=` | +| `Mcp-Name` or `Mcp-Param-*` missing | With `experimental_events` set, HTTP, SSE, and a Streamable HTTP `Transport` instance add `Mcp-Name` and `Mcp-Param-*` to `events/subscribe` and `events/unsubscribe`. Non-ASCII values use `=?base64?...?=`. An event type with an invalid `x-mcp-header` annotation is left out of `list()`. A `-32020` HeaderMismatch makes the client list events again and retry that request once | Next: follow [Subscribe to MCP Events](../tutorials/mcp-events), or put `createMCPEventWebhook` on a POST route and subscribe with `{ store }`. \ No newline at end of file diff --git a/examples/react/mcp-events/src/lib/desk.ts b/examples/react/mcp-events/src/lib/desk.ts index c2f304748b..6ee660e111 100644 --- a/examples/react/mcp-events/src/lib/desk.ts +++ b/examples/react/mcp-events/src/lib/desk.ts @@ -145,10 +145,7 @@ export function handleWebhook(request: Request) { async function signAndDeliver(sub: StoredSub, bodyObj: unknown) { const raw = new TextEncoder().encode(JSON.stringify(bodyObj)) const timestamp = Math.floor(Date.now() / 1000) - const messageId = - isRecord(bodyObj) && typeof bodyObj.eventId === 'string' - ? bodyObj.eventId - : `msg_${crypto.randomUUID()}` + const messageId = `msg_${crypto.randomUUID()}` const signature = await signMCPEventPayload({ secret: sub.secret, messageId, diff --git a/packages/ai-mcp/skills/ai-mcp/SKILL.md b/packages/ai-mcp/skills/ai-mcp/SKILL.md index 871eb79d34..1982d0d88e 100644 --- a/packages/ai-mcp/skills/ai-mcp/SKILL.md +++ b/packages/ai-mcp/skills/ai-mcp/SKILL.md @@ -1273,10 +1273,14 @@ Gotchas: - Dedupe deliveries on `messageId`. A 503 after `onEvent` succeeded is retried. Capability check: `extensions["io.modelcontextprotocol/events"]` only. -With `experimental_events` set, HTTP/SSE transports add `Mcp-Name` for +With `experimental_events` set, HTTP, SSE, and a Streamable HTTP +`Transport` instance add `Mcp-Name` and `Mcp-Param-*` on `events/subscribe` and `events/unsubscribe` (Base64 sentinel when the -name is not printable ASCII). A failed subscribe deletes its `pending` -record. Deliveries must send `X-MCP-Subscription-Id`. +value is not printable ASCII). An event type with an invalid +`x-mcp-header` annotation is left out of `list()`. HeaderMismatch +(`-32020`) makes the client list events again and retry that request +once. A failed subscribe deletes its `pending` record. Deliveries must +send `X-MCP-Subscription-Id`. ## Error classes diff --git a/packages/ai-mcp/src/client.ts b/packages/ai-mcp/src/client.ts index 1b67dacf1c..3347b5bdf5 100644 --- a/packages/ai-mcp/src/client.ts +++ b/packages/ai-mcp/src/client.ts @@ -39,6 +39,8 @@ import { toServerTools, } from './tools' import { directMCPClient } from './direct-client' +import { createEventHeaderLookup } from './events/param-headers' +import type { EventHeaderLookup } from './events/param-headers' import { isTransportInstance, resolveTransport } from './transport' import type { DescriptorFromServer, @@ -265,6 +267,7 @@ class MCPClientImpl implements Omit< readonly #policy: ToolPolicy readonly #eventsOptions?: MCPEventsOptions readonly #eventsTransport: MCPEventAdapterTransport + readonly #eventHeaders?: EventHeaderLookup readonly #managedOps?: MCPEventOperations constructor( @@ -279,6 +282,7 @@ class MCPClientImpl implements Omit< eventsSetup?: { options?: MCPEventsOptions transport: MCPEventAdapterTransport + eventHeaders?: EventHeaderLookup }, ) { this.prefix = prefix @@ -288,6 +292,7 @@ class MCPClientImpl implements Omit< this.#events = events this.#eventsOptions = eventsSetup?.options this.#eventsTransport = eventsSetup?.transport ?? { type: 'custom' } + this.#eventHeaders = eventsSetup?.eventHeaders this.#managedOps = bindManagedOperations( eventsSetup?.options, this.#eventsTransport, @@ -710,6 +715,9 @@ class MCPClientImpl implements Omit< }, supportsEvents: serverSupportsEvents(this.capabilities), transport: this.#eventsTransport, + noteEventSchemas: (events) => { + this.#eventHeaders?.replace(events) + }, request: (method, params, schema, signal) => this.#client.request( { method, params }, @@ -846,8 +854,13 @@ export type OnElicit = ( export async function connectTransport< TServer extends ServerDescriptor = AutomaticDescriptor, >(options: MCPClientOptions, onElicit?: OnElicit) { + const eventHeaders = + options.experimental_events !== undefined + ? createEventHeaderLookup() + : undefined const transport = await resolveTransport(options.transport, { - events: options.experimental_events !== undefined, + events: eventHeaders !== undefined, + eventHeaders, }) const impl = new MCPClientImpl( options.prefix, @@ -871,6 +884,7 @@ export async function connectTransport< { options: options.experimental_events, transport: eventsTransportOf(options.transport), + eventHeaders, }, ) await impl.connect(transport, options.prior, options.signal) diff --git a/packages/ai-mcp/src/errors.ts b/packages/ai-mcp/src/errors.ts index 8805cdc27d..711a3fb480 100644 --- a/packages/ai-mcp/src/errors.ts +++ b/packages/ai-mcp/src/errors.ts @@ -146,6 +146,7 @@ export type MCPEventRequestKind = | 'resource-exhausted' | 'unsupported' | 'callback-endpoint' + | 'header-mismatch' | 'unknown' /** diff --git a/packages/ai-mcp/src/events/capability.ts b/packages/ai-mcp/src/events/capability.ts index 635e193784..aae62a45a6 100644 --- a/packages/ai-mcp/src/events/capability.ts +++ b/packages/ai-mcp/src/events/capability.ts @@ -2,8 +2,7 @@ import type { ClientCapabilities } from '@modelcontextprotocol/client' import { isRecord } from './value' /** - * MCP Events extension id from SEP-3415 - * (`modelcontextprotocol/modelcontextprotocol@2ec39b9`). + * MCP Events extension id from the final text of SEP-3415. * * @experimental */ diff --git a/packages/ai-mcp/src/events/direct.ts b/packages/ai-mcp/src/events/direct.ts index c78f31b4da..3e44610a13 100644 --- a/packages/ai-mcp/src/events/direct.ts +++ b/packages/ai-mcp/src/events/direct.ts @@ -29,6 +29,10 @@ function rethrowEvents(err: unknown): never { throw toMCPEventRequestError(err) } +function isHeaderMismatch(err: unknown): boolean { + return err instanceof MCPEventRequestError && err.kind === 'header-mismatch' +} + function assertWebhookMode(mode: string) { if (mode !== 'webhook') { throw new MCPEventConfigError('delivery.mode must be webhook') @@ -101,7 +105,10 @@ export function createDirectMCPEvents( if (!ctx.supportsEvents) throw new MCPEventsUnsupportedError() } - async function send(record: MCPEventSubscription, signal?: AbortSignal) { + async function subscribeOnce( + record: MCPEventSubscription, + signal?: AbortSignal, + ): Promise { try { return await ctx.request( 'events/subscribe', @@ -114,6 +121,44 @@ export function createDirectMCPEvents( } } + async function send(record: MCPEventSubscription, signal?: AbortSignal) { + try { + return await subscribeOnce(record, signal) + } catch (err) { + if (!isHeaderMismatch(err)) throw err + } + // The remembered inputSchema was stale. List once, then retry once. + await listEventDefinitions(ctx, signal) + return await subscribeOnce(record, signal) + } + + async function unsubscribeOnce( + record: MCPEventSubscription, + signal?: AbortSignal, + ) { + try { + await ctx.request( + 'events/unsubscribe', + { + name: record.name, + arguments: record.arguments, + delivery: { mode: 'webhook', url: record.delivery.url }, + }, + emptyResult, + signal, + ) + } catch (err) { + const mapped = toMCPEventRequestError(err) + if ( + mapped instanceof MCPEventRequestError && + mapped.kind === 'not-found' + ) { + return + } + throw mapped + } + } + async function save( key: string, result: SubscribeEventsResult, @@ -189,24 +234,11 @@ export function createDirectMCPEvents( assertReady() const record = await resolveRecord(store, ref) try { - await ctx.request( - 'events/unsubscribe', - { - name: record.name, - arguments: record.arguments, - delivery: { mode: 'webhook', url: record.delivery.url }, - }, - emptyResult, - ref.signal, - ) + await unsubscribeOnce(record, ref.signal) } catch (err) { - const mapped = toMCPEventRequestError(err) - if ( - !(mapped instanceof MCPEventRequestError) || - mapped.kind !== 'not-found' - ) { - throw mapped - } + if (!isHeaderMismatch(err)) throw err + await listEventDefinitions(ctx, ref.signal) + await unsubscribeOnce(record, ref.signal) } await store.delete(record.key) }, diff --git a/packages/ai-mcp/src/events/errors-map.ts b/packages/ai-mcp/src/events/errors-map.ts index b91901f37d..396abbadde 100644 --- a/packages/ai-mcp/src/events/errors-map.ts +++ b/packages/ai-mcp/src/events/errors-map.ts @@ -10,6 +10,7 @@ const KIND_BY_CODE: Record = { [-32025]: 'resource-exhausted', [-32026]: 'unsupported', [-32027]: 'callback-endpoint', + [-32020]: 'header-mismatch', } function redactData(data: unknown): unknown { diff --git a/packages/ai-mcp/src/events/list.ts b/packages/ai-mcp/src/events/list.ts index 809a8737ff..6caf70d667 100644 --- a/packages/ai-mcp/src/events/list.ts +++ b/packages/ai-mcp/src/events/list.ts @@ -1,6 +1,7 @@ import { listPages } from '../list-pages' import { MCPEventsUnsupportedError } from '../errors' import { isMethodNotFound, toMCPEventRequestError } from './errors-map' +import { eventHeaderFault } from './param-headers' import type { MCPEventDefinition, MCPEventsContext } from './types' import { listEventsResult } from './wire' @@ -13,8 +14,9 @@ export async function listEventDefinitions( ): Promise> { ctx.assertOpen() if (!ctx.supportsEvents) throw new MCPEventsUnsupportedError() + let events: Array try { - return await listPages(async (cursor) => { + events = await listPages(async (cursor) => { const page = await ctx.request( 'events/list', cursor === undefined ? {} : { cursor }, @@ -27,4 +29,12 @@ export async function listEventDefinitions( if (isMethodNotFound(err)) throw new MCPEventsUnsupportedError() throw toMCPEventRequestError(err) } + const kept = events.filter((event) => { + const fault = eventHeaderFault(event.inputSchema) + if (fault === undefined) return true + console.warn(`MCP events: left ${event.name} out of events/list. ${fault}`) + return false + }) + ctx.noteEventSchemas?.(kept) + return kept } diff --git a/packages/ai-mcp/src/events/param-headers.ts b/packages/ai-mcp/src/events/param-headers.ts new file mode 100644 index 0000000000..bb7dea92fc --- /dev/null +++ b/packages/ai-mcp/src/events/param-headers.ts @@ -0,0 +1,214 @@ +/** + * `x-mcp-header` scan and `Mcp-Param-*` values for `events/*` requests. + * + * The MCP SDK builds these headers for `tools/call` only. Events methods + * are not in that path, so the HTTP fetch wrapper reads this lookup. + */ + +const HEADER_KEY = 'x-mcp-header' +const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/ +const PRIMITIVE_TYPES = new Set(['string', 'integer', 'boolean']) +const SENTINEL_PREFIX = '=?base64?' +const SENTINEL_SUFFIX = '?=' + +const NON_REACHABLE = [ + 'items', + 'prefixItems', + 'contains', + 'additionalProperties', + 'unevaluatedProperties', + 'unevaluatedItems', + 'propertyNames', + 'patternProperties', + 'dependentSchemas', + 'oneOf', + 'anyOf', + 'allOf', + 'not', + 'if', + 'then', + 'else', + '$defs', + 'definitions', +] as const + +const OBJECT_BRANCHES = new Set([ + 'patternProperties', + 'dependentSchemas', + '$defs', + 'definitions', +]) + +export interface McpParamDeclaration { + path: Array + headerName: string +} + +function pathLabel(path: Array): string { + return path.length === 0 ? '' : path.join('.') +} + +function isSchema(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +/** + * `undefined` when the schema's annotations are valid (including none). + * A string is the first constraint the schema breaks. + */ +export function eventHeaderFault(inputSchema: unknown): string | undefined { + return scan(inputSchema).fault +} + +function scan(inputSchema: unknown): { + fault?: string + declarations: Array +} { + const declarations: Array = [] + const seen = new Map() + + const visit = ( + node: unknown, + path: Array, + reachable: boolean, + ): string | undefined => { + if (!isSchema(node)) return undefined + if (HEADER_KEY in node) { + if (!reachable || path.length === 0) { + return `${pathLabel(path)}: x-mcp-header is only permitted on properties reached through properties keys` + } + const raw = node[HEADER_KEY] + if (typeof raw !== 'string' || raw.length === 0) { + return `${pathLabel(path)}: x-mcp-header must be a non-empty string` + } + if (!TOKEN.test(raw)) { + return `${pathLabel(path)}: x-mcp-header '${raw}' is not an HTTP token` + } + const type = typeof node.type === 'string' ? node.type : undefined + if (type === undefined || !PRIMITIVE_TYPES.has(type)) { + return `${pathLabel(path)}: x-mcp-header is only permitted on string, integer, or boolean` + } + const lower = raw.toLowerCase() + const prior = seen.get(lower) + if (prior !== undefined) { + return `x-mcp-header '${raw}' is not case-insensitively unique (also '${prior}')` + } + seen.set(lower, raw) + declarations.push({ path, headerName: raw }) + } + const properties = node.properties + if (isSchema(properties)) { + for (const [key, child] of Object.entries(properties)) { + const fault = visit(child, [...path, key], reachable) + if (fault !== undefined) return fault + } + } + for (const keyword of NON_REACHABLE) { + if (!(keyword in node)) continue + const sub = node[keyword] + const branches = Array.isArray(sub) + ? sub + : isSchema(sub) && OBJECT_BRANCHES.has(keyword) + ? Object.values(sub) + : [sub] + for (const branch of branches) { + const fault = visit(branch, [...path, `<${keyword}>`], false) + if (fault !== undefined) return fault + } + } + return undefined + } + + const fault = visit(inputSchema, [], true) + return fault === undefined ? { declarations } : { fault, declarations: [] } +} + +function valueAt(root: unknown, path: Array): unknown { + let node = root + for (const key of path) { + if (!isSchema(node)) return undefined + node = node[key] + } + return node +} + +function primitiveToString(value: unknown): string | undefined { + if (typeof value === 'string') return value + if (typeof value === 'boolean') return value ? 'true' : 'false' + if (typeof value === 'number') { + if (!Number.isFinite(value)) return undefined + if (Number.isInteger(value) && !Number.isSafeInteger(value)) + return undefined + return String(value) + } + return undefined +} + +function needsBase64(value: string): boolean { + if (value.length === 0) return true + if (value.startsWith(SENTINEL_PREFIX) && value.endsWith(SENTINEL_SUFFIX)) { + return true + } + if (value !== value.trim()) return true + for (let i = 0; i < value.length; i++) { + const code = value.codePointAt(i) + if (code === 9 || (code !== undefined && code >= 32 && code <= 126)) { + continue + } + return true + } + return false +} + +function utf8ToBase64(value: string): string { + const bytes = new TextEncoder().encode(value) + let binary = '' + for (const byte of bytes) binary += String.fromCodePoint(byte) + return btoa(binary) +} + +/** Plain ASCII stays as-is. Anything else uses the `=?base64?...?=` sentinel. */ +export function encodeMcpHeaderValue(value: string): string { + return needsBase64(value) + ? `${SENTINEL_PREFIX}${utf8ToBase64(value)}${SENTINEL_SUFFIX}` + : value +} + +export function mcpParamHeaders( + declarations: Array, + args: unknown, +): Record { + const headers: Record = {} + for (const decl of declarations) { + const raw = valueAt(args, decl.path) + if (raw === undefined || raw === null) continue + const text = primitiveToString(raw) + if (text === undefined) continue + headers[`Mcp-Param-${decl.headerName}`] = encodeMcpHeaderValue(text) + } + return headers +} + +export interface EventHeaderLookup { + replace: (events: Array<{ name: string; inputSchema: unknown }>) => void + headersFor: (name: string, args: unknown) => Record +} + +export function createEventHeaderLookup(): EventHeaderLookup { + const byName = new Map>() + return { + replace(events) { + byName.clear() + for (const event of events) { + const scanned = scan(event.inputSchema) + if (scanned.fault !== undefined) continue + byName.set(event.name, scanned.declarations) + } + }, + headersFor(name, args) { + const declarations = byName.get(name) + if (declarations === undefined || declarations.length === 0) return {} + return mcpParamHeaders(declarations, args) + }, + } +} diff --git a/packages/ai-mcp/src/events/signature.ts b/packages/ai-mcp/src/events/signature.ts index 0342b600d8..c068cbf432 100644 --- a/packages/ai-mcp/src/events/signature.ts +++ b/packages/ai-mcp/src/events/signature.ts @@ -9,7 +9,7 @@ function concat(prefix: Uint8Array, body: Uint8Array): Uint8Array { function signedBytes( messageId: string, - timestamp: number, + timestamp: string, body: Uint8Array, ): Uint8Array { const prefix = new TextEncoder().encode(`${messageId}.${timestamp}.`) @@ -59,7 +59,11 @@ export async function signMCPEventPayload(input: { const signature = await crypto.subtle.sign( 'HMAC', key, - signedBytes(input.messageId, input.timestamp, input.body) as BufferSource, + signedBytes( + input.messageId, + String(input.timestamp), + input.body, + ) as BufferSource, ) return `v1,${bytesToBase64(new Uint8Array(signature))}` } @@ -73,7 +77,8 @@ export async function signMCPEventPayload(input: { export async function verifyMCPEventSignature(input: { secret: string messageId: string - timestamp: number + /** Raw `webhook-timestamp` header. Leading zeros are part of the signature. */ + timestamp: string body: Uint8Array header: string }): Promise { diff --git a/packages/ai-mcp/src/events/types.ts b/packages/ai-mcp/src/events/types.ts index cad58b6346..f1ac6ca3a9 100644 --- a/packages/ai-mcp/src/events/types.ts +++ b/packages/ai-mcp/src/events/types.ts @@ -68,6 +68,8 @@ export interface MCPEventOccurrence { timestamp: string data: JSONObject cursor?: string | null + /** Protocol metadata. Not part of `payloadSchema`. */ + _meta?: JSONObject } /** @@ -358,6 +360,13 @@ export interface MCPEventsContext { assertOpen: () => void readonly supportsEvents: boolean readonly transport: MCPEventAdapterTransport + /** + * Records the schemas from the latest `events/list` so subscribe, + * refresh, and unsubscribe can send `Mcp-Param-*` headers. + */ + noteEventSchemas?: ( + events: Array>, + ) => void } /** @@ -387,7 +396,7 @@ export interface MCPEventWebhookOptions { onGap?: (args: { subscription: MCPEventSubscriptionInfo messageId: string - gap: { cursor: string; truncated: true } + gap: { cursor: string | null; truncated: true } }) => Promise | void onTerminated?: (args: { subscription: MCPEventSubscriptionInfo diff --git a/packages/ai-mcp/src/events/webhook.ts b/packages/ai-mcp/src/events/webhook.ts index 6a3f3b8fb7..f010026596 100644 --- a/packages/ai-mcp/src/events/webhook.ts +++ b/packages/ai-mcp/src/events/webhook.ts @@ -208,7 +208,7 @@ export function createMCPEventWebhook( verified = await verifyMCPEventSignature({ secret: record.delivery.secret, messageId: webhookId, - timestamp, + timestamp: webhookTimestamp, body, header: webhookSignature, }) diff --git a/packages/ai-mcp/src/events/wire.ts b/packages/ai-mcp/src/events/wire.ts index d0f7eaa954..8009f41944 100644 --- a/packages/ai-mcp/src/events/wire.ts +++ b/packages/ai-mcp/src/events/wire.ts @@ -29,6 +29,7 @@ function parseEventDefinition(value: unknown): MCPEventDefinition | undefined { if (!isDeliveryMode(mode)) return undefined delivery.push(mode) } + // A conforming descriptor has both schemas. One bad item fails the page. if (!('inputSchema' in value) || !('payloadSchema' in value)) return undefined const description = typeof value.description === 'string' ? value.description : undefined @@ -125,6 +126,7 @@ export const subscribeResult: StandardSchemaV1Sync< if (!isRecord(value) || !isNonEmptyString(value.id)) { return issues('events/subscribe result must include id') } + // Every subscribe result in the final SEP includes truncated. if (typeof value.truncated !== 'boolean') { return issues('events/subscribe result must include truncated') } @@ -175,11 +177,13 @@ function parseEventOccurrence(value: unknown): MCPEventOccurrence | undefined { } const data = value.data if (!isJsonObject(data)) return undefined + const meta = isJsonObject(value._meta) ? value._meta : undefined const event: MCPEventOccurrence = { eventId: value.eventId, name: value.name, timestamp: value.timestamp, data, + ...(meta === undefined ? {} : { _meta: meta }), } if (value.cursor === undefined) return event if (value.cursor !== null && typeof value.cursor !== 'string') @@ -191,7 +195,7 @@ function parseEventOccurrence(value: unknown): MCPEventOccurrence | undefined { export type ClassifiedWebhookBody = | { kind: 'event'; event: MCPEventOccurrence } | { kind: 'verification'; challenge: string } - | { kind: 'gap'; cursor: string } + | { kind: 'gap'; cursor: string | null } | { kind: 'terminated' error: { code: number; message: string; data?: unknown } @@ -214,8 +218,12 @@ export function classifyWebhookBody(json: unknown): ClassifiedWebhookBody { return { kind: 'verification', challenge: json.challenge } } if (json.type === 'gap') { - if (!isNonEmptyString(json.cursor)) { - return { kind: 'invalid', issue: 'gap requires cursor' } + // An absent cursor is the same as null. Do not reject the envelope. + if (json.cursor === undefined || json.cursor === null) { + return { kind: 'gap', cursor: null } + } + if (typeof json.cursor !== 'string') { + return { kind: 'invalid', issue: 'gap cursor must be a string or null' } } return { kind: 'gap', cursor: json.cursor } } diff --git a/packages/ai-mcp/src/transport.ts b/packages/ai-mcp/src/transport.ts index 2bde0d00f8..971790077b 100644 --- a/packages/ai-mcp/src/transport.ts +++ b/packages/ai-mcp/src/transport.ts @@ -6,6 +6,11 @@ import type { OAuthClientProvider, Transport, } from '@modelcontextprotocol/client' +import { + createEventHeaderLookup, + encodeMcpHeaderValue, +} from './events/param-headers' +import type { EventHeaderLookup } from './events/param-headers' import { isRecord } from './events/value' export interface HttpTransportConfig { @@ -49,10 +54,12 @@ export function isTransportInstance(input: TransportInput): input is Transport { } /** - * SDK 2.1.0 does not send `Mcp-Name` for custom `events/*` methods. - * SEP-3415 requires it on Streamable HTTP for name-scoped events requests. + * SDK 2.1.0 does not send `Mcp-Name` or `Mcp-Param-*` for `events/*`. + * SEP-3415 requires both on Streamable HTTP. */ -async function mcpNameFromRpc(request: Request): Promise { +async function eventsRpc( + request: Request, +): Promise<{ name: string; args: unknown } | undefined> { if (request.method !== 'POST') return undefined let json: unknown try { @@ -70,77 +77,75 @@ async function mcpNameFromRpc(request: Request): Promise { if (!isRecord(json.params) || typeof json.params.name !== 'string') { return undefined } - return json.params.name -} - -const MCP_NAME_SENTINEL_PREFIX = '=?base64?' -const MCP_NAME_SENTINEL_SUFFIX = '?=' - -/** - * Copy of SDK 2.1.0 `needsBase64` / `encodeMcpParamValue` (not exported). - * Printable ASCII with no leading/trailing whitespace is sent as-is. - * Anything else uses `=?base64?{b64-of-utf8}?=` so `Headers.set` stays ASCII. - */ -function needsBase64(value: string): boolean { - if (value.length === 0) return true - if ( - value.startsWith(MCP_NAME_SENTINEL_PREFIX) && - value.endsWith(MCP_NAME_SENTINEL_SUFFIX) - ) { - return true - } - if (value !== value.trim()) return true - for (let i = 0; i < value.length; i++) { - const code = value.codePointAt(i) - if (code === 9 || (code !== undefined && code >= 32 && code <= 126)) { - continue - } - return true - } - return false + return { name: json.params.name, args: json.params.arguments } } -function utf8ToBase64(value: string): string { - const bytes = new TextEncoder().encode(value) - let binary = '' - for (const byte of bytes) binary += String.fromCodePoint(byte) - return btoa(binary) -} - -function encodeMcpName(value: string): string { - return needsBase64(value) - ? `${MCP_NAME_SENTINEL_PREFIX}${utf8ToBase64(value)}${MCP_NAME_SENTINEL_SUFFIX}` - : value -} - -function fetchWithMcpEventName(baseFetch: typeof fetch = fetch): typeof fetch { +function fetchWithMcpEventHeaders( + baseFetch: typeof fetch, + lookup: EventHeaderLookup, +): typeof fetch { return async (input, init) => { const request = new Request(input, init) - if (request.headers.has('mcp-name')) { - return baseFetch(input, init) - } - const name = await mcpNameFromRpc(request) - if (name === undefined) return baseFetch(input, init) + const rpc = await eventsRpc(request) + if (rpc === undefined) return baseFetch(input, init) const headers = new Headers(request.headers) - headers.set('Mcp-Name', encodeMcpName(name)) + let changed = false + if (!headers.has('mcp-name')) { + headers.set('Mcp-Name', encodeMcpHeaderValue(rpc.name)) + changed = true + } + for (const [name, value] of Object.entries( + lookup.headersFor(rpc.name, rpc.args), + )) { + headers.set(name, value) + changed = true + } + if (!changed) return baseFetch(input, init) return baseFetch(new Request(request, { headers })) } } +/** + * A caller-built Streamable HTTP or SSE transport already closed over its + * fetch. Replace that fetch so `events/*` still gets the routing headers. + */ +function wrapTransportFetch( + transport: Transport, + lookup: EventHeaderLookup, +): void { + const current = Reflect.get(transport, '_fetchWithInit') + if (typeof current !== 'function') return + Reflect.set( + transport, + '_fetchWithInit', + fetchWithMcpEventHeaders(current as typeof fetch, lookup), + ) +} + /** * Build a Transport from HTTP config, SSE config, or an existing Transport. * * For stdio, build the Transport with `stdioTransport` and pass that instance. * Throws an Error when the config type is `stdio` or is not a known type. - * With `events`, HTTP and SSE requests for `events/*` get the `Mcp-Name` header. + * With `events`, HTTP and SSE requests for `events/subscribe` and + * `events/unsubscribe` get `Mcp-Name` and `Mcp-Param-*`. + * A Transport instance is wrapped the same way when it has a fetch. */ export async function resolveTransport( input: TransportInput, - options?: { events?: boolean }, + options?: { events?: boolean; eventHeaders?: EventHeaderLookup }, ) { - if (isTransportInstance(input)) return input + const lookup = options?.events + ? (options.eventHeaders ?? createEventHeaderLookup()) + : undefined + if (isTransportInstance(input)) { + if (lookup !== undefined) wrapTransportFetch(input, lookup) + return input + } const withEvents = (base?: typeof fetch) => - options?.events ? fetchWithMcpEventName(base) : base + lookup !== undefined + ? fetchWithMcpEventHeaders(base ?? fetch, lookup) + : base switch (input.type) { case 'http': diff --git a/packages/ai-mcp/tests/events/client-events.test.ts b/packages/ai-mcp/tests/events/client-events.test.ts index b15476f00a..b8ec050077 100644 --- a/packages/ai-mcp/tests/events/client-events.test.ts +++ b/packages/ai-mcp/tests/events/client-events.test.ts @@ -301,4 +301,139 @@ describe('createMCPClient HTTP capability detection', () => { await http.close() } }) + + it('sends Mcp-Name and Mcp-Param on events/subscribe', async () => { + const seen: Array<{ + method: string + name: string | null + region: string | null + }> = [] + const events = createTestEventsServer({ + verify: 'skip', + events: [ + { + name: 'incident.created', + delivery: ['webhook'], + inputSchema: { + type: 'object', + properties: { + region: { type: 'string', 'x-mcp-header': 'Region' }, + }, + }, + payloadSchema: true, + }, + ], + }) + const inner = eventsHttpFetch(events) + const http = await listenHttp(async (request) => { + const json: unknown = await request + .clone() + .json() + .catch(() => undefined) + const method = + typeof json === 'object' && + json !== null && + 'method' in json && + typeof json.method === 'string' + ? json.method + : '' + if (method === 'events/list' || method === 'events/subscribe') { + seen.push({ + method, + name: request.headers.get('mcp-name'), + region: request.headers.get('mcp-param-region'), + }) + } + return inner(request) + }) + const client = await createMCPClient({ + transport: { type: 'http', url: http.url }, + experimental_events: { store: inMemoryMCPEventStore() }, + }) + try { + await client.experimental_events.subscribe({ + name: 'incident.created', + arguments: { region: 'eu' }, + delivery: { + mode: 'webhook', + url: 'https://hooks.example.test/mcp', + }, + }) + expect(seen.filter((item) => item.method === 'events/list')).toHaveLength( + 1, + ) + expect(seen.filter((item) => item.method === 'events/subscribe')).toEqual( + [ + { + method: 'events/subscribe', + name: 'incident.created', + region: 'eu', + }, + ], + ) + } finally { + await client.close() + await http.close() + } + }) + + it('lists again and retries subscribe once after HeaderMismatch', async () => { + let subscribeAttempts = 0 + const events = createTestEventsServer({ verify: 'skip' }) + const inner = eventsHttpFetch(events) + const http = await listenHttp(async (request) => { + const json: unknown = await request + .clone() + .json() + .catch(() => undefined) + const method = + typeof json === 'object' && + json !== null && + 'method' in json && + typeof json.method === 'string' + ? json.method + : '' + const id = + typeof json === 'object' && + json !== null && + 'id' in json && + (typeof json.id === 'string' || typeof json.id === 'number') + ? json.id + : null + if (method === 'events/subscribe') { + subscribeAttempts += 1 + if (subscribeAttempts === 1) { + return Response.json( + { + jsonrpc: '2.0', + id, + error: { code: -32020, message: 'HeaderMismatch' }, + }, + { status: 400 }, + ) + } + } + return inner(request) + }) + const client = await createMCPClient({ + transport: { type: 'http', url: http.url }, + experimental_events: { store: inMemoryMCPEventStore() }, + }) + try { + await client.experimental_events.subscribe({ + name: 'incident.created', + delivery: { + mode: 'webhook', + url: 'https://hooks.example.test/mcp', + }, + }) + expect(subscribeAttempts).toBe(2) + expect( + events.requests.filter((item) => item.method === 'events/list'), + ).toHaveLength(2) + } finally { + await client.close() + await http.close() + } + }) }) diff --git a/packages/ai-mcp/tests/events/direct.test.ts b/packages/ai-mcp/tests/events/direct.test.ts index 05631a1b40..2fb5788b34 100644 --- a/packages/ai-mcp/tests/events/direct.test.ts +++ b/packages/ai-mcp/tests/events/direct.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { ProtocolError } from '@modelcontextprotocol/client' import { MCPConnectionError } from '../../src/errors' import { @@ -538,6 +538,67 @@ describe('createDirectMCPEvents', () => { await expect(api.list()).rejects.toBeInstanceOf(MCPEventsUnsupportedError) }) + it('retries subscribe once after HeaderMismatch', async () => { + const store = inMemoryMCPEventStore() + let subscribeAttempts = 0 + const ctx = fakeCtx({ + async request(method) { + if (method === 'events/list') return { events: [webhookDef] } + subscribeAttempts += 1 + if (subscribeAttempts === 1) throw new ProtocolError(-32020, 'mismatch') + return { + id: 'sub_1', + refreshBefore: null, + cursor: null, + truncated: false, + } + }, + }) + const api = createDirectMCPEvents(ctx, { store }) + const sub = await api.subscribe({ name: 'incident.created', delivery }) + expect(sub.id).toBe('sub_1') + expect( + ctx.requests.filter((item) => item.method === 'events/list'), + ).toHaveLength(2) + expect( + ctx.requests.filter((item) => item.method === 'events/subscribe'), + ).toHaveLength(2) + expect(await store.get(sub.key)).toBeDefined() + }) + + it('retries unsubscribe once after HeaderMismatch', async () => { + const store = inMemoryMCPEventStore() + let unsubscribeAttempts = 0 + const ctx = fakeCtx({ + async request(method) { + if (method === 'events/list') return { events: [webhookDef] } + if (method === 'events/subscribe') { + return { + id: 'sub_1', + refreshBefore: null, + cursor: null, + truncated: false, + } + } + unsubscribeAttempts += 1 + if (unsubscribeAttempts === 1) { + throw new ProtocolError(-32020, 'mismatch') + } + return {} + }, + }) + const api = createDirectMCPEvents(ctx, { store }) + const sub = await api.subscribe({ name: 'incident.created', delivery }) + ctx.requests.length = 0 + await api.unsubscribe({ key: sub.key }) + expect(ctx.requests.map((item) => item.method)).toEqual([ + 'events/unsubscribe', + 'events/list', + 'events/unsubscribe', + ]) + expect(await store.get(sub.key)).toBeUndefined() + }) + it('throws MCPConnectionError after assertOpen fails', async () => { const api = createDirectMCPEvents( fakeCtx({ @@ -570,4 +631,27 @@ describe('createDiscoveryMCPEvents', () => { MCPEventConfigError, ) }) + + it('leaves out an event whose x-mcp-header annotation is invalid', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const bad = { + ...webhookDef, + name: 'incident.bad', + inputSchema: { + type: 'object', + properties: { n: { type: 'number', 'x-mcp-header': 'N' } }, + }, + } + const ctx = fakeCtx({ + async request() { + return { events: [webhookDef, bad] } + }, + }) + const api = createDiscoveryMCPEvents(ctx) + expect(await api.list()).toEqual([webhookDef]) + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('left incident.bad out of events/list'), + ) + warn.mockRestore() + }) }) diff --git a/packages/ai-mcp/tests/events/e2e.test.ts b/packages/ai-mcp/tests/events/e2e.test.ts index 27ec7c6262..1e09035102 100644 --- a/packages/ai-mcp/tests/events/e2e.test.ts +++ b/packages/ai-mcp/tests/events/e2e.test.ts @@ -27,7 +27,7 @@ const definition = { describe('MCP Events HTTP e2e', () => { const store = inMemoryMCPEventStore() const received: Array = [] - const gaps: Array<{ cursor: string }> = [] + const gaps: Array<{ cursor: string | null }> = [] let nowMs = Date.now() let onEventImpl: () => Promise | void = () => undefined const webhook = createMCPEventWebhook({ diff --git a/packages/ai-mcp/tests/events/errors-map.test.ts b/packages/ai-mcp/tests/events/errors-map.test.ts index ec843783ad..08e5043da8 100644 --- a/packages/ai-mcp/tests/events/errors-map.test.ts +++ b/packages/ai-mcp/tests/events/errors-map.test.ts @@ -25,6 +25,7 @@ describe('toMCPEventRequestError', () => { it.each([ [-32602, 'invalid-params'], + [-32020, 'header-mismatch'], [-32023, 'not-found'], [-32024, 'forbidden'], [-32025, 'resource-exhausted'], diff --git a/packages/ai-mcp/tests/events/param-headers.test.ts b/packages/ai-mcp/tests/events/param-headers.test.ts new file mode 100644 index 0000000000..e3e8a72cde --- /dev/null +++ b/packages/ai-mcp/tests/events/param-headers.test.ts @@ -0,0 +1,123 @@ +import { describe, expect, it } from 'vitest' +import { + createEventHeaderLookup, + encodeMcpHeaderValue, + eventHeaderFault, + mcpParamHeaders, +} from '../../src/events/param-headers' + +const regionSchema = { + type: 'object', + properties: { + region: { type: 'string', 'x-mcp-header': 'Region' }, + nested: { + type: 'object', + properties: { + on: { type: 'boolean', 'x-mcp-header': 'On' }, + }, + }, + count: { type: 'integer', 'x-mcp-header': 'Count' }, + }, +} + +describe('eventHeaderFault', () => { + it('accepts a schema with no annotations', () => { + expect(eventHeaderFault({})).toBeUndefined() + expect(eventHeaderFault(regionSchema)).toBeUndefined() + }) + + it('rejects an empty header name', () => { + expect( + eventHeaderFault({ + type: 'object', + properties: { region: { type: 'string', 'x-mcp-header': '' } }, + }), + ).toMatch(/non-empty/) + }) + + it('rejects a repeated header name', () => { + expect( + eventHeaderFault({ + type: 'object', + properties: { + a: { type: 'string', 'x-mcp-header': 'Region' }, + b: { type: 'string', 'x-mcp-header': 'region' }, + }, + }), + ).toMatch(/unique/) + }) + + it('rejects type number', () => { + expect( + eventHeaderFault({ + type: 'object', + properties: { n: { type: 'number', 'x-mcp-header': 'N' } }, + }), + ).toMatch(/string, integer, or boolean/) + }) + + it('rejects an annotation under oneOf', () => { + expect( + eventHeaderFault({ + oneOf: [ + { + type: 'object', + properties: { + region: { type: 'string', 'x-mcp-header': 'Region' }, + }, + }, + ], + }), + ).toMatch(/properties keys/) + }) +}) + +describe('mcpParamHeaders', () => { + const lookup = createEventHeaderLookup() + lookup.replace([{ name: 'incident.created', inputSchema: regionSchema }]) + + it('encodes string, boolean, and integer arguments', () => { + expect( + lookup.headersFor('incident.created', { + region: 'eu', + nested: { on: false }, + count: 3, + }), + ).toEqual({ + 'Mcp-Param-Region': 'eu', + 'Mcp-Param-On': 'false', + 'Mcp-Param-Count': '3', + }) + }) + + it('omits null, a missing value, and an unsafe integer', () => { + expect( + lookup.headersFor('incident.created', { + region: null, + count: Number.MAX_SAFE_INTEGER + 2, + }), + ).toEqual({}) + }) + + it('base64-encodes a non-ASCII value', () => { + const headers = mcpParamHeaders([{ path: ['city'], headerName: 'City' }], { + city: '東京', + }) + expect(headers['Mcp-Param-City']).toBe(encodeMcpHeaderValue('東京')) + expect(headers['Mcp-Param-City']?.startsWith('=?base64?')).toBe(true) + }) + + it('ignores a schema that still has a fault', () => { + const broken = createEventHeaderLookup() + broken.replace([ + { + name: 'incident.bad', + inputSchema: { + type: 'object', + properties: { n: { type: 'number', 'x-mcp-header': 'N' } }, + }, + }, + ]) + expect(broken.headersFor('incident.bad', { n: 1 })).toEqual({}) + }) +}) diff --git a/packages/ai-mcp/tests/events/signature.test.ts b/packages/ai-mcp/tests/events/signature.test.ts index 19d13da53c..e6efb0567a 100644 --- a/packages/ai-mcp/tests/events/signature.test.ts +++ b/packages/ai-mcp/tests/events/signature.test.ts @@ -17,7 +17,7 @@ const SPEC_SIGNATURE = 'v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=' function nodeOracle( secret: string, messageId: string, - timestamp: number, + timestamp: number | string, body: string, ) { const key = Buffer.from(secret.slice('whsec_'.length), 'base64') @@ -56,7 +56,7 @@ describe('verifyMCPEventSignature', () => { const ok = await verifyMCPEventSignature({ secret: SPEC_SECRET, messageId: SPEC_ID, - timestamp: SPEC_TS, + timestamp: String(SPEC_TS), body: new TextEncoder().encode(SPEC_BODY), header: `v1,bad ${SPEC_SIGNATURE}`, }) @@ -67,7 +67,7 @@ describe('verifyMCPEventSignature', () => { const ok = await verifyMCPEventSignature({ secret: SPEC_SECRET, messageId: SPEC_ID, - timestamp: SPEC_TS, + timestamp: String(SPEC_TS), body: new TextEncoder().encode(SPEC_BODY), header: `v1a,abc garbage ${SPEC_SIGNATURE}`, }) @@ -78,7 +78,7 @@ describe('verifyMCPEventSignature', () => { const ok = await verifyMCPEventSignature({ secret: createMCPEventSecret(), messageId: SPEC_ID, - timestamp: SPEC_TS, + timestamp: String(SPEC_TS), body: new TextEncoder().encode(SPEC_BODY), header: SPEC_SIGNATURE, }) @@ -90,7 +90,7 @@ describe('verifyMCPEventSignature', () => { const ok = await verifyMCPEventSignature({ secret: SPEC_SECRET, messageId: SPEC_ID, - timestamp: SPEC_TS, + timestamp: String(SPEC_TS), body: new TextEncoder().encode(resent), header: SPEC_SIGNATURE, }) @@ -109,10 +109,31 @@ describe('verifyMCPEventSignature', () => { const ok = await verifyMCPEventSignature({ secret, messageId: 'msg_utf8', - timestamp: SPEC_TS, + timestamp: String(SPEC_TS), body, header: signature, }) expect(ok).toBe(true) }) + + it('verifies a timestamp string that has a leading zero', async () => { + const timestamp = `0${SPEC_TS}` + const signature = nodeOracle(SPEC_SECRET, SPEC_ID, timestamp, SPEC_BODY) + const ok = await verifyMCPEventSignature({ + secret: SPEC_SECRET, + messageId: SPEC_ID, + timestamp, + body: new TextEncoder().encode(SPEC_BODY), + header: signature, + }) + expect(ok).toBe(true) + const numeric = await verifyMCPEventSignature({ + secret: SPEC_SECRET, + messageId: SPEC_ID, + timestamp: String(Number(timestamp)), + body: new TextEncoder().encode(SPEC_BODY), + header: signature, + }) + expect(numeric).toBe(false) + }) }) diff --git a/packages/ai-mcp/tests/events/webhook.test.ts b/packages/ai-mcp/tests/events/webhook.test.ts index f326c135cc..bdc8c81124 100644 --- a/packages/ai-mcp/tests/events/webhook.test.ts +++ b/packages/ai-mcp/tests/events/webhook.test.ts @@ -327,17 +327,29 @@ describe('createMCPEventWebhook', () => { expect((await webhook(request)).status).toBe(401) }) - it('returns 400 for an invalid control', async () => { + it('returns 400 for an unknown control', async () => { const record = sampleRecord() const { webhook } = await setup(record) const request = await signedRequest({ record, - body: { type: 'gap' }, + body: { type: 'nope' }, timestamp: FIXED_TS, }) expect((await webhook(request)).status).toBe(400) }) + it('verifies a webhook-timestamp that has a leading zero', async () => { + const record = sampleRecord() + const { webhook } = await setup(record) + const request = await signedRequest({ + record, + body: eventBody(), + timestamp: `0${FIXED_TS}`, + }) + expect(request.headers.get('webhook-timestamp')).toBe(`0${FIXED_TS}`) + expect((await webhook(request)).status).toBe(204) + }) + it('on terminated, calls onTerminated then deletes the record and returns 204, even when pending or expired', async () => { const pending = sampleRecord({ key: 'pending-key', @@ -403,6 +415,23 @@ describe('createMCPEventWebhook', () => { expect((await webhook(request)).status).toBe(503) }) + it('on a gap with no cursor, calls onGap with null and stores null', async () => { + const record = sampleRecord() + const { webhook, onGap, store } = await setup(record) + const request = await signedRequest({ + record, + body: { type: 'gap' }, + timestamp: FIXED_TS, + }) + expect((await webhook(request)).status).toBe(204) + expect(onGap).toHaveBeenCalledWith( + expect.objectContaining({ + gap: { cursor: null, truncated: true }, + }), + ) + expect((await store.get(record.key))?.cursor).toBeNull() + }) + it('on gap, calls onGap, stores cursor and truncated:true, returns 204', async () => { const record = sampleRecord() const { webhook, onGap, store } = await setup(record) diff --git a/packages/ai-mcp/tests/events/wire.test.ts b/packages/ai-mcp/tests/events/wire.test.ts index b94a994f96..e07c107800 100644 --- a/packages/ai-mcp/tests/events/wire.test.ts +++ b/packages/ai-mcp/tests/events/wire.test.ts @@ -112,8 +112,19 @@ describe('classifyWebhookBody', () => { }) }) - it('rejects a gap without cursor', () => { - expect(classifyWebhookBody({ type: 'gap' }).kind).toBe('invalid') + it('treats a gap with no cursor as cursor null', () => { + expect(classifyWebhookBody({ type: 'gap' })).toEqual({ + kind: 'gap', + cursor: null, + }) + expect(classifyWebhookBody({ type: 'gap', cursor: null })).toEqual({ + kind: 'gap', + cursor: null, + }) + }) + + it('rejects a gap whose cursor is not a string', () => { + expect(classifyWebhookBody({ type: 'gap', cursor: 1 }).kind).toBe('invalid') }) it('classifies verification', () => { @@ -157,6 +168,39 @@ describe('classifyWebhookBody', () => { }) }) + it('keeps _meta when it is a JSON object', () => { + expect( + classifyWebhookBody({ + eventId: 'e', + name: 'n', + timestamp: '2026-10-17T00:00:00Z', + data: {}, + _meta: { trace: 'a' }, + }), + ).toEqual({ + kind: 'event', + event: { + eventId: 'e', + name: 'n', + timestamp: '2026-10-17T00:00:00Z', + data: {}, + _meta: { trace: 'a' }, + }, + }) + }) + + it('drops _meta when it is not an object', () => { + const result = classifyWebhookBody({ + eventId: 'e', + name: 'n', + timestamp: '2026-10-17T00:00:00Z', + data: {}, + _meta: 'nope', + }) + expect(result.kind).toBe('event') + if (result.kind === 'event') expect(result.event._meta).toBeUndefined() + }) + it('rejects an event whose data is an array', () => { expect( classifyWebhookBody({ diff --git a/packages/ai-mcp/tests/helpers/sign-webhook.ts b/packages/ai-mcp/tests/helpers/sign-webhook.ts index 2b5e844bc5..d6130e76a3 100644 --- a/packages/ai-mcp/tests/helpers/sign-webhook.ts +++ b/packages/ai-mcp/tests/helpers/sign-webhook.ts @@ -1,3 +1,4 @@ +import { createHmac } from 'node:crypto' import { signMCPEventPayload } from '../../src/events/signature' import type { MCPEventSubscription } from '../../src/events/types' @@ -5,7 +6,8 @@ export async function signedRequest(input: { record: MCPEventSubscription body: unknown headers?: Record - timestamp?: number + /** A string is the raw `webhook-timestamp` header, including leading zeros. */ + timestamp?: number | string url?: string messageId?: string method?: string @@ -13,18 +15,21 @@ export async function signedRequest(input: { }): Promise { const json = JSON.stringify(input.body) const bodyBytes = input.rawBody ?? new TextEncoder().encode(json) - const timestamp = input.timestamp ?? Math.floor(Date.now() / 1000) + const timestamp = input.timestamp ?? String(Math.floor(Date.now() / 1000)) const messageId = input.messageId ?? (isRecord(input.body) && typeof input.body.eventId === 'string' ? input.body.eventId : 'msg_test_1') - const signature = await signMCPEventPayload({ - secret: input.record.delivery.secret, - messageId, - timestamp, - body: bodyBytes, - }) + const signature = + typeof timestamp === 'string' + ? signRaw(input.record.delivery.secret, messageId, timestamp, bodyBytes) + : await signMCPEventPayload({ + secret: input.record.delivery.secret, + messageId, + timestamp, + body: bodyBytes, + }) const url = input.url ?? `https://hooks.example.test/mcp?mcp_event_subscription=${input.record.key}` @@ -48,6 +53,17 @@ export async function signedRequest(input: { }) } +function signRaw( + secret: string, + messageId: string, + timestamp: string, + body: Uint8Array, +): string { + const key = Buffer.from(secret.slice('whsec_'.length), 'base64') + const prefix = Buffer.from(`${messageId}.${timestamp}.`) + return `v1,${createHmac('sha256', key).update(prefix).update(body).digest('base64')}` +} + function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) } diff --git a/packages/ai-mcp/tests/transport.test.ts b/packages/ai-mcp/tests/transport.test.ts index 1448cf8f7c..172be103c8 100644 --- a/packages/ai-mcp/tests/transport.test.ts +++ b/packages/ai-mcp/tests/transport.test.ts @@ -1,4 +1,6 @@ import { describe, expect, it } from 'vitest' +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/client' +import { createEventHeaderLookup } from '../src/events/param-headers' import { resolveTransport } from '../src/transport' import type { OAuthClientProvider, @@ -153,4 +155,46 @@ describe('resolveTransport', () => { expect(new TextDecoder().decode(bytes)).toBe(name) } }) + + it('sets Mcp-Param on a caller-built Streamable HTTP transport', async () => { + const seen: Array = [] + const transport = new StreamableHTTPClientTransport( + new URL('https://fixture.example/mcp'), + { + fetch: async (input, init) => { + seen.push(new Request(input, init)) + return new Response('{}') + }, + }, + ) + const lookup = createEventHeaderLookup() + lookup.replace([ + { + name: 'incident.created', + inputSchema: { + type: 'object', + properties: { + region: { type: 'string', 'x-mcp-header': 'Region' }, + }, + }, + }, + ]) + await resolveTransport(transport, { events: true, eventHeaders: lookup }) + const wrapped = Reflect.get(transport, '_fetchWithInit') as typeof fetch + await wrapped('https://fixture.example/mcp', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'events/subscribe', + params: { + name: 'incident.created', + arguments: { region: 'eu' }, + }, + }), + }) + expect(seen[0]?.headers.get('mcp-name')).toBe('incident.created') + expect(seen[0]?.headers.get('mcp-param-region')).toBe('eu') + }) }) diff --git a/testing/e2e/src/lib/mcp-events-session.ts b/testing/e2e/src/lib/mcp-events-session.ts index bb928155c6..b8da9cb2c4 100644 --- a/testing/e2e/src/lib/mcp-events-session.ts +++ b/testing/e2e/src/lib/mcp-events-session.ts @@ -20,7 +20,7 @@ type Session = { webhook: (request: Request) => Promise received: Array messageIds: Array - gaps: Array<{ cursor: string }> + gaps: Array<{ cursor: string | null }> terminations: Array<{ code: number; message: string }> errors: Array client?: EventsClient @@ -32,7 +32,7 @@ function createSession(origin: string): Session { const store = inMemoryMCPEventStore() const received: Array = [] const messageIds: Array = [] - const gaps: Array<{ cursor: string }> = [] + const gaps: Array<{ cursor: string | null }> = [] const terminations: Array<{ code: number; message: string }> = [] const errors: Array = [] const webhook = createMCPEventWebhook({ From 93d896b7565362db1b5ee6e9befe7152649239c4 Mon Sep 17 00:00:00 2001 From: TanStack Source Date: Sat, 21 Nov 2026 05:47:54 +0000 Subject: [PATCH 2/2] fix(ai-mcp): wrap transport _fetch so send() sends MCP event headers SDK 2.1.0 send() calls this._fetch, not _fetchWithInit. wrapTransportFetch now patches _fetch and uses fetch when _fetch is missing. The caller-built transport test drives send() instead of _fetchWithInit. TanStack-Source-Factory-Run: factory-2221-c88266c9-e33b-437c-8b6a-43145ae4db49 TanStack-Source-Agent: fixer --- packages/ai-mcp/src/transport.ts | 13 +++++-------- packages/ai-mcp/tests/transport.test.ts | 23 +++++++++-------------- 2 files changed, 14 insertions(+), 22 deletions(-) diff --git a/packages/ai-mcp/src/transport.ts b/packages/ai-mcp/src/transport.ts index 971790077b..789114f44e 100644 --- a/packages/ai-mcp/src/transport.ts +++ b/packages/ai-mcp/src/transport.ts @@ -107,19 +107,16 @@ function fetchWithMcpEventHeaders( /** * A caller-built Streamable HTTP or SSE transport already closed over its - * fetch. Replace that fetch so `events/*` still gets the routing headers. + * fetch. Replace `_fetch` so `send()` still gets the routing headers. + * SDK 2.1.0 `send()` calls `(this._fetch ?? fetch)`. */ function wrapTransportFetch( transport: Transport, lookup: EventHeaderLookup, ): void { - const current = Reflect.get(transport, '_fetchWithInit') - if (typeof current !== 'function') return - Reflect.set( - transport, - '_fetchWithInit', - fetchWithMcpEventHeaders(current as typeof fetch, lookup), - ) + const current = Reflect.get(transport, '_fetch') + const base = typeof current === 'function' ? (current as typeof fetch) : fetch + Reflect.set(transport, '_fetch', fetchWithMcpEventHeaders(base, lookup)) } /** diff --git a/packages/ai-mcp/tests/transport.test.ts b/packages/ai-mcp/tests/transport.test.ts index 172be103c8..cdd7f6f8c3 100644 --- a/packages/ai-mcp/tests/transport.test.ts +++ b/packages/ai-mcp/tests/transport.test.ts @@ -163,7 +163,7 @@ describe('resolveTransport', () => { { fetch: async (input, init) => { seen.push(new Request(input, init)) - return new Response('{}') + return new Response(null, { status: 202 }) }, }, ) @@ -180,19 +180,14 @@ describe('resolveTransport', () => { }, ]) await resolveTransport(transport, { events: true, eventHeaders: lookup }) - const wrapped = Reflect.get(transport, '_fetchWithInit') as typeof fetch - await wrapped('https://fixture.example/mcp', { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'events/subscribe', - params: { - name: 'incident.created', - arguments: { region: 'eu' }, - }, - }), + await transport.send({ + jsonrpc: '2.0', + id: 1, + method: 'events/subscribe', + params: { + name: 'incident.created', + arguments: { region: 'eu' }, + }, }) expect(seen[0]?.headers.get('mcp-name')).toBe('incident.created') expect(seen[0]?.headers.get('mcp-param-region')).toBe('eu')