From e88e854ad76ac91b770258f3b5917416e10f487b Mon Sep 17 00:00:00 2001 From: Phil Leggetter Date: Fri, 13 Nov 2026 13:06:27 +0000 Subject: [PATCH 1/4] feat: per-message webhook-id for SEP-3415 clients, eventId for legacy ones Each subscription now records which webhook-id its deliveries carry, chosen at subscribe time: - event: the eventId, as before. Clients that don't declare the events extension get it, as do declaring clients on a legacy list (TanStack AI, the Vercel AI SDK and OpenClaw by their default names), which reject a webhook-id that isn't the eventId. - message: msg_ plus 24 random characters, as SEP-3415 requires, for a client that declares io.modelcontextprotocol/events in the request's _meta. BRIDGE_WEBHOOK_ID (subscriptions.webhookId) sets auto (default), event or message. The mode is stored as wid in the connection description, where the transformation reads it; replays publish with the same rule. Event Gateway runs the transformation once per event, so retries keep a generated id (verified). Dedupe moves from headers.webhook-id to body.eventId, so a service's resend is still dropped when the id is random. Refs #113 Co-Authored-By: Claude Opus 5.5 --- src/core/config.ts | 20 ++++++- src/core/event-gateway-store.ts | 22 +++++--- src/core/hookdeck.ts | 7 ++- src/core/mcp.ts | 6 ++- src/core/migrate.ts | 2 + src/core/store.ts | 3 ++ src/core/subscriptions.ts | 16 +++++- src/core/transformation.ts | 18 ++++--- src/core/webhook-id.ts | 78 +++++++++++++++++++++++++++ src/host/server.ts | 11 ++-- test/core/callbacks.test.ts | 1 + test/core/config.test.ts | 8 +++ test/core/event-gateway-store.test.ts | 17 +++++- test/core/notifications.test.ts | 1 + test/core/store-concurrency.test.ts | 1 + test/core/transformation.test.ts | 33 +++++++++++- test/core/webhook-id.test.ts | 47 ++++++++++++++++ test/host/bridge.test.ts | 43 +++++++++++++-- test/support/subscriber.ts | 10 +++- 19 files changed, 312 insertions(+), 32 deletions(-) create mode 100644 src/core/webhook-id.ts create mode 100644 test/core/webhook-id.test.ts diff --git a/src/core/config.ts b/src/core/config.ts index 6003a1e..f3f881f 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -1,4 +1,5 @@ import type { SourceDefinition } from './sources/types.js'; +import { WEBHOOK_ID_SETTINGS, type WebhookIdSetting } from './webhook-id.js'; /* * The typed config file, bridge.config.ts: @@ -92,6 +93,12 @@ export interface BridgeConfig { } export interface SubscriptionSettings { + /** + * Which `webhook-id` deliveries carry: `auto` (per message for a client that declares the events extension in its + * request `_meta`, else the `eventId`), `event` (always the `eventId`) or `message` (always per message). See + * webhook-id.ts. Default: BRIDGE_WEBHOOK_ID, else `auto`. + */ + webhookId: WebhookIdSetting; defaultTtlMs: number; minTtlMs: number; maxTtlMs: number; @@ -102,6 +109,7 @@ export interface SubscriptionSettings { } export const DEFAULT_SUBSCRIPTION_SETTINGS: SubscriptionSettings = { + webhookId: 'auto', // Long: ChatGPT sent no ttlMs in the 1 Oct test, and the bridge may be offline when a refresh is due. defaultTtlMs: 30 * 24 * 60 * 60 * 1000, minTtlMs: 60 * 1000, @@ -143,6 +151,12 @@ function parseBoolean(name: string, value: string | undefined, fallback: boolean throw new ConfigError(`${name} must be true or false`); } +function parseWebhookId(value: string | undefined): WebhookIdSetting { + if (value === undefined || value === '') return DEFAULT_SUBSCRIPTION_SETTINGS.webhookId; + if ((WEBHOOK_ID_SETTINGS as readonly string[]).includes(value)) return value as WebhookIdSetting; + throw new ConfigError(`BRIDGE_WEBHOOK_ID (subscriptions.webhookId) must be ${WEBHOOK_ID_SETTINGS.join(', ')}`); +} + /** Resolves env() references and defaults. Missing required variables are collected into one error. */ export function resolveConfig(config: BridgeConfig, environment: Record): ResolvedConfig { const missing: string[] = []; @@ -198,7 +212,11 @@ export function resolveConfig(config: BridgeConfig, environment: Record`), to an HTTP destination at the callback URL: * * rules the source's transformation (it builds the MCP event), a filter for the event name and - * the subscription's arguments, dedupe on webhook-id, and retry. + * the subscription's arguments, dedupe on the event id, and retry. * destination the callback URL; STANDARD_WEBHOOKS auth with the subscriber's secret, so Event Gateway * signs every attempt. The sender's path isn't forwarded. * connection description JSON metadata: principal, event name, arguments, expiry, timestamps, delivery state - * (omitted while healthy), and what the transformation needs for cursors: `ca`, the - * arguments hash, and `rp` while a replay runs. Versioned: {"v":2. Version 1 is a - * subscription from 0.7 or earlier, on a topic source, left for the migration. + * (omitted while healthy), and what the transformation needs: `ca`, the cursor's + * arguments hash, `rp` while a replay runs, and `wid: "msg"` for a per-message + * webhook-id. Versioned: {"v":2. Version 1 is a subscription from 0.7 or earlier, + * on a topic source, left for the migration. * * Reads come from an in-memory index built by `load()` (one listing, plus one destination read per subscription for * its secret) and kept current by `put()` and `delete()`. One bridge instance per deployment. @@ -41,6 +42,8 @@ interface Metadata { ca: string; /** While a replay runs, where it started (the cursor's floor and watermark). */ rp?: { f: number; w: number }; + /** `msg` when deliveries' `webhook-id` is per message, for the transformation; omitted when it's the `eventId`. */ + wid?: 'msg'; } /** Where a subscription's connection goes, and what its rules hold: from the catalog and the source's transformation. */ @@ -157,14 +160,16 @@ export class EventGatewayStore implements SubscriptionStore { ...(!isHealthy(input.delivery) && { delivery: input.delivery }), ca: placement.cursorArgs, ...(input.replay && { rp: input.replay }), + ...(input.webhookIdMode === 'message' && { wid: 'msg' as const }), }; const description = JSON.stringify(metadata); - // Checked with the largest delivery block a failure notification can add later and a replay marker, so neither - // can overflow it. + // Checked with the largest delivery block a failure notification can add later, a replay marker and the + // per-message marker, so none of them can overflow it, and a refresh can switch the mode. const worstCase = JSON.stringify({ ...metadata, delivery: { active: false, lastError: 'connection_refused', failedSince: input.updatedAt }, rp: { f: 9_999_999_999_999, w: 9_999_999_999_999 }, + wid: 'msg', }); if (worstCase.length > DESCRIPTION_LIMIT) throw new SubscriptionTooLargeError('Subscription arguments are too large to store'); @@ -177,7 +182,7 @@ export class EventGatewayStore implements SubscriptionStore { type: 'HTTP', config: { url: input.url, path_forwarding_disabled: true, auth_type: 'STANDARD_WEBHOOKS', auth: { webhook_secret_key: input.secret } }, }, - rules: [{ type: 'transform', transformation_id: placement.transformationId }, placement.filter, WEBHOOK_ID_DEDUPE_RULE, SUBSCRIPTION_RETRY_RULE], + rules: [{ type: 'transform', transformation_id: placement.transformationId }, placement.filter, EVENT_ID_DEDUPE_RULE, SUBSCRIPTION_RETRY_RULE], }); const record: SubscriptionRecord = { ...input, connectionId: connection.id, destinationId: connection.destination.id, sourceId: connection.source.id }; this.records.set(record.id, record); @@ -201,6 +206,7 @@ export class EventGatewayStore implements SubscriptionStore { secret, replay: metadata.rp ?? null, delivery: metadata.delivery ?? healthyDelivery(), + webhookIdMode: metadata.wid === 'msg' ? 'message' : 'event', expiresAt: metadata.expiresAt, createdAt: metadata.createdAt, updatedAt: metadata.updatedAt, diff --git a/src/core/hookdeck.ts b/src/core/hookdeck.ts index 35c4b37..87d4121 100644 --- a/src/core/hookdeck.ts +++ b/src/core/hookdeck.ts @@ -157,8 +157,11 @@ export const SUBSCRIPTION_RETRY_RULE: Rule = { response_status_codes: ['>=300', '!410', '!413'], }; -/** Dedupe on the MCP event id. Best-effort, window of at most 1 hour. */ -export const WEBHOOK_ID_DEDUPE_RULE: Rule = { type: 'deduplicate', include_fields: ['headers.webhook-id'], window: 3_600_000 }; +/** + * Dedupe on the MCP event id, from the envelope the transformation built. Best-effort, window of at most 1 hour. Not on + * `webhook-id`: a per-message one is random, so a service's resend of an event would get a new one (see webhook-id.ts). + */ +export const EVENT_ID_DEDUPE_RULE: Rule = { type: 'deduplicate', include_fields: ['body.eventId'], window: 3_600_000 }; /** * Event statuses, and which of them are settled. diff --git a/src/core/mcp.ts b/src/core/mcp.ts index ccb9c55..444ffb8 100644 --- a/src/core/mcp.ts +++ b/src/core/mcp.ts @@ -217,8 +217,10 @@ export function buildMcpServer(deps: { const anyParams = z.record(z.string(), z.unknown()); server.server.setRequestHandler('events/list', { params: anyParams.optional() }, async () => ({ events: catalog.list() })); - server.server.setRequestHandler('events/subscribe', { params: anyParams }, async (params) => ({ - ...(await subscriptions.subscribe(principal, params)), + // The SDK lifts the per-request envelope (clientCapabilities, clientInfo) out of `_meta` into `ctx.mcpReq.envelope`; + // subscribe reads them from both, under their full `_meta` keys, to choose the webhook-id mode. + server.server.setRequestHandler('events/subscribe', { params: anyParams }, async (params, ctx) => ({ + ...(await subscriptions.subscribe(principal, params, { meta: { ...ctx.mcpReq._meta, ...(ctx.mcpReq.envelope as Record | undefined) } })), })); if (poll) server.server.setRequestHandler('events/poll', { params: anyParams }, async (params) => ({ ...(await poll.poll(params)) })); server.server.setRequestHandler('events/unsubscribe', { params: anyParams }, async (params) => subscriptions.unsubscribe(principal, params)); diff --git a/src/core/migrate.ts b/src/core/migrate.ts index 3c502f9..7950b74 100644 --- a/src/core/migrate.ts +++ b/src/core/migrate.ts @@ -212,6 +212,8 @@ export async function migrate(deps: { hookdeck: MigrationHookdeck; config: Resol secret: secret!, replay: null, delivery: metadata.delivery ?? healthyDelivery(), + // 0.7 and earlier sent the eventId; the client's next refresh picks the mode. + webhookIdMode: 'event', expiresAt: metadata.expiresAt, createdAt: metadata.createdAt, updatedAt: now.toISOString(), diff --git a/src/core/store.ts b/src/core/store.ts index 7823d94..62045fb 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -1,4 +1,5 @@ import type { CallbackFailureReason } from './errors.js'; +import type { WebhookIdMode } from './webhook-id.js'; /* * Subscription state. Event Gateway is the store: each subscription is a connection from its service's source to a @@ -31,6 +32,8 @@ export interface SubscriptionInput { /** While a replay runs, where it started: every delivery's cursor has it until the replay is done. */ replay: CursorPosition | null; delivery: SubscriptionDeliveryState; + /** Whether deliveries' `webhook-id` is the `eventId` (legacy clients) or per message (SEP-3415). See webhook-id.ts. */ + webhookIdMode: WebhookIdMode; expiresAt: string; createdAt: string; updatedAt: string; diff --git a/src/core/subscriptions.ts b/src/core/subscriptions.ts index fb983ff..4a1c151 100644 --- a/src/core/subscriptions.ts +++ b/src/core/subscriptions.ts @@ -6,6 +6,7 @@ import { deriveSubscriptionId, verificationKey } from './identity.js'; import { isValidWebhookSecret } from './secret.js'; import type { CallbackRegistry } from './callbacks.js'; import { SubscriptionTooLargeError, healthyDelivery, type CursorPosition, type SubscriptionRecord, type SubscriptionStore } from './store.js'; +import { chooseWebhookIdMode, clientName, declaresEventsExtension } from './webhook-id.js'; /* * MCP Events webhook subscriptions: subscribe (and refresh), unsubscribe, @@ -79,6 +80,14 @@ export function describeParams(params: Params): string { return JSON.stringify({ ...params, delivery: redacted }); } +/** Why a subscription got its webhook-id mode, for the log. */ +function describeClient(setting: SubscriptionSettings['webhookId'], meta: unknown): string { + if (setting !== 'auto') return `BRIDGE_WEBHOOK_ID=${setting}`; + const name = clientName(meta); + const client = name === undefined ? 'the client' : `client ${JSON.stringify(name.slice(0, 60))}`; + return `${client} ${declaresEventsExtension(meta) ? 'declares' : "doesn't declare"} io.modelcontextprotocol/events`; +} + /** A callback URL for logs: the query string can include a token, so it's replaced. */ export function redactUrl(url: string): string { const query = url.indexOf('?'); @@ -120,7 +129,8 @@ export class SubscriptionService { return { name: params.name, event: entry?.event, url, rawArgs: rawArgs as Record, delivery }; } - async subscribe(principal: string | undefined, params: Params): Promise { + /** `request.meta` is the request's `_meta`, including the per-request envelope the SDK lifts out of it. */ + async subscribe(principal: string | undefined, params: Params, request: { meta?: unknown } = {}): Promise { this.log(`events/subscribe from ${principal ?? '(none)'}: ${describeParams(params)}`); if (!principal) throw forbidden(); const { settings, store, transport } = this.deps; @@ -176,6 +186,8 @@ export class SubscriptionService { } const expiresAt = new Date(now.getTime() + grantTtlMs(params.ttlMs, settings)); + // Chosen on every subscribe, so a refresh picks up a client upgrade or a change to BRIDGE_WEBHOOK_ID. + const webhookIdMode = chooseWebhookIdMode(settings.webhookId, request.meta); const live = (record: SubscriptionRecord | undefined) => record !== undefined && Date.parse(record.expiresAt) > now.getTime(); // Read and written in the store's queue, so a concurrent write (a delivery-failure notification) can't be lost or undo this. const prior: { record?: SubscriptionRecord } = {}; @@ -196,6 +208,7 @@ export class SubscriptionService { replay: cursorCheck && this.deps.cursors && !live(existing) ? cursorCheck.position : live(existing) ? existing!.replay : null, // A refresh is the subscriber's liveness signal: delivery is active again. delivery: healthyDelivery(), + webhookIdMode, expiresAt: expiresAt.toISOString(), createdAt: existing?.createdAt ?? now.toISOString(), updatedAt: now.toISOString(), @@ -209,6 +222,7 @@ export class SubscriptionService { const existing = prior.record; if (existing && existing.secret !== secret) this.log(`rotated secret for ${id}`); this.log(`${existing ? 'refreshed' : 'subscribed'} ${id} until ${expiresAt.toISOString()}`); + this.log(`${id}: webhook-id ${webhookIdMode === 'message' ? 'per message' : 'is the eventId'} (${describeClient(settings.webhookId, request.meta)})`); return { id, diff --git a/src/core/transformation.ts b/src/core/transformation.ts index 53404cd..0f99220 100644 --- a/src/core/transformation.ts +++ b/src/core/transformation.ts @@ -36,17 +36,18 @@ export function functionSource(fn: (...args: never[]) => unknown): string { /** * The transformation's handler. Self-contained: it's serialized into the transformation, and called directly in - * tests. Anything it can't deliver gets an `x-mcp-skip` header, which every subscription's filter excludes, rather - * than an error, which would open an issue on every subscription for every request. + * tests. It uses only built-ins Event Gateway's runtime has (`Buffer` and `crypto.getRandomValues`). Anything it + * can't deliver gets an `x-mcp-skip` header, which every subscription's filter excludes, rather than an error, which + * would open an issue on every subscription for every request. */ export function envelopeHandler( runtime: Record, events: Array<{ key: string; name: string }>, constants: { subscriptionPrefix: string; maxBodyBytes: number; lookbackMs: number }, ) { - // From the connection description (event-gateway-store.ts): `ca`, the cursor's arguments hash, and `rp` while a - // replay runs. - type Meta = { ca?: unknown; rp?: { f?: unknown; w?: unknown } } | null; + // From the connection description (event-gateway-store.ts): `ca`, the cursor's arguments hash, `rp` while a replay + // runs, and `wid: "msg"` when the subscription's webhook-id is per message (webhook-id.ts). + type Meta = { ca?: unknown; rp?: { f?: unknown; w?: unknown }; wid?: unknown } | null; // Poll's cursor format, from now less the look-back, so a client persisting it never skips an event still in flight; // during a replay, from where the replay started. const cursorFor = (meta: Meta, name: string, now: number) => { @@ -70,6 +71,9 @@ export function envelopeHandler( const headers: Record = {}; for (const [key, value] of Object.entries(request.headers ?? {})) headers[key.toLowerCase()] = String(value); const req = { headers, body: request.body }; + // A per-message webhook-id (SEP-3415): random, so not derived from the event id. Event Gateway runs this once per + // event and every attempt reuses its headers, so retries keep it. Otherwise the event id, as legacy clients require. + const perMessage = meta !== null && meta.wid === 'msg'; let envelope: { eventId: string; name: string; timestamp: string; data: unknown; cursor: string | null } | null = null; let skip: string | null = 'event type not enabled'; @@ -79,7 +83,7 @@ export function envelopeHandler( if (!rt || !rt.matches(req)) continue; const eventId = String(rt.eventId(req)); envelope = { eventId, name: event.name, timestamp: rt.occurredAt(req), data: rt.summarize(req), cursor: cursorFor(meta, event.name, Date.now()) }; - skip = eventId.includes('.') ? 'event id contains a period, which Standard Webhooks ids cannot' : null; + skip = !perMessage && eventId.includes('.') ? 'event id contains a period, which Standard Webhooks ids cannot' : null; } catch (error) { envelope = null; skip = `could not build the event: ${error instanceof Error ? error.message : String(error)}`; @@ -89,7 +93,7 @@ export function envelopeHandler( if (envelope && !skip && Buffer.byteLength(JSON.stringify(envelope)) > constants.maxBodyBytes) skip = 'envelope over 256 KiB'; const out: Record = { 'content-type': 'application/json', 'x-mcp-subscription-id': subscriptionId }; - if (envelope) out['webhook-id'] = envelope.eventId; + if (envelope) out['webhook-id'] = perMessage ? `msg_${Buffer.from(crypto.getRandomValues(new Uint8Array(18))).toString('base64url')}` : envelope.eventId; if (skip) out['x-mcp-skip'] = skip.slice(0, 200); // The sender's query string isn't the subscriber's (the destination also ignores the sender's path). return { ...request, headers: out, body: envelope ?? {}, query: '', parsed_query: {} }; diff --git a/src/core/webhook-id.ts b/src/core/webhook-id.ts new file mode 100644 index 0000000..c01f550 --- /dev/null +++ b/src/core/webhook-id.ts @@ -0,0 +1,78 @@ +import { randomBytes } from 'node:crypto'; + +/* + * Which `webhook-id` a subscription's deliveries carry (#113). + * + * event the event's `eventId`, as the bridge has always sent it. The Vercel AI SDK, TanStack AI and OpenClaw reject + * a delivery whose `webhook-id` isn't its `eventId`, and OpenAI's guide for ChatGPT asks for the same. + * message a per-message id, `msg_` and 24 random characters, as SEP-3415 requires: unique to one event on one + * subscription, kept across retries, and never derived from `eventId`. + * + * The mode is chosen at subscribe time and kept in the subscription's connection description, where the + * transformation reads it. Event Gateway runs the transformation once per event and every attempt (automatic or + * manual retry) reuses its headers, so a generated id stays the same across retries (verified 13 Nov). + */ + +export type WebhookIdMode = 'event' | 'message'; + +/** The operator's choice: `auto` picks per subscription, from what the client declares; the others apply to every subscription. */ +export type WebhookIdSetting = 'auto' | WebhookIdMode; + +export const WEBHOOK_ID_SETTINGS: readonly WebhookIdSetting[] = ['auto', 'event', 'message']; + +export const EVENTS_EXTENSION = 'io.modelcontextprotocol/events'; +const CLIENT_CAPABILITIES_META_KEY = 'io.modelcontextprotocol/clientCapabilities'; +const CLIENT_INFO_META_KEY = 'io.modelcontextprotocol/clientInfo'; + +/** + * Clients that reject a delivery whose `webhook-id` isn't its `eventId`, by their default name in + * `_meta["io.modelcontextprotocol/clientInfo"]`. They get `event` mode under `auto` even if they declare the events + * extension. Checked 13 Nov: + * + * tanstack-ai-mcp TanStack AI (`@tanstack/ai-mcp` 1.2.0) declares the extension whenever events are enabled + * (`client.ts:311`), and rejects at `events/webhook.ts:297`. + * ai-sdk-mcp-client The Vercel AI SDK (`@ai-sdk/mcp` 2.0.99) declares it only if the application passes it in + * `capabilities`; rejects at `mcp-event-webhook.ts:211`. + * openclaw OpenClaw (v2026.11.3) declares nothing (`clientCapabilities: {}`); listed in case it starts. + * + * TanStack AI and the AI SDK let the application rename the client, which this list can't see: such a deployment sets + * BRIDGE_WEBHOOK_ID=event. Remove a client once a release that accepts a per-message id has shipped. + */ +export const LEGACY_WEBHOOK_ID_CLIENTS: readonly string[] = ['tanstack-ai-mcp', 'ai-sdk-mcp-client', 'openclaw']; + +const isObject = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value); + +/** Whether a request's `_meta` declares the events extension (SEP-3415's per-request client capabilities). */ +export function declaresEventsExtension(meta: unknown): boolean { + if (!isObject(meta)) return false; + const capabilities = meta[CLIENT_CAPABILITIES_META_KEY]; + return isObject(capabilities) && isObject(capabilities.extensions) && isObject(capabilities.extensions[EVENTS_EXTENSION]); +} + +/** The client's name from a request's `_meta`, if it sends one. */ +export function clientName(meta: unknown): string | undefined { + if (!isObject(meta)) return undefined; + const info = meta[CLIENT_INFO_META_KEY]; + return isObject(info) && typeof info.name === 'string' ? info.name : undefined; +} + +/** + * The mode for a subscribe request. Under `auto`, a client that declares the events extension in the request's + * `_meta` gets `message`, unless it's on the legacy list; any other client gets `event`. + */ +export function chooseWebhookIdMode(setting: WebhookIdSetting, meta: unknown, legacyClients: readonly string[] = LEGACY_WEBHOOK_ID_CLIENTS): WebhookIdMode { + if (setting !== 'auto') return setting; + if (!declaresEventsExtension(meta)) return 'event'; + const name = clientName(meta); + return name !== undefined && legacyClients.includes(name) ? 'event' : 'message'; +} + +/** A per-message `webhook-id`: `msg_` and 24 characters from [A-Za-z0-9_-] (18 random bytes). The transformation builds the same shape. */ +export function messageId(): string { + return `msg_${randomBytes(18).toString('base64url')}`; +} + +/** The `webhook-id` for one delivery of an event in a mode. */ +export function deliveryWebhookId(mode: WebhookIdMode, eventId: string): string { + return mode === 'message' ? messageId() : eventId; +} diff --git a/src/host/server.ts b/src/host/server.ts index 158232d..14c83c7 100644 --- a/src/host/server.ts +++ b/src/host/server.ts @@ -7,7 +7,8 @@ import { Catalog, descriptionWarnings } from '../core/catalog.js'; import { assertCredentials, type ResolvedConfig } from '../core/config.js'; import { EventGatewayStore } from '../core/event-gateway-store.js'; import { EventHistory } from '../core/event-history.js'; -import { HookdeckApiError, HookdeckClient, isSettled, SUBSCRIPTION_RETRY_RULE, WEBHOOK_ID_DEDUPE_RULE } from '../core/hookdeck.js'; +import { deliveryWebhookId } from '../core/webhook-id.js'; +import { HookdeckApiError, HookdeckClient, isSettled, SUBSCRIPTION_RETRY_RULE, EVENT_ID_DEDUPE_RULE } from '../core/hookdeck.js'; import { buildMcpServer } from '../core/mcp.js'; import { Notifications } from '../core/notifications.js'; import { REPLAY_CONNECTION_PREFIX, REPLAY_SOURCE, replayConnectionName } from '../core/names.js'; @@ -148,12 +149,16 @@ export async function createBridgeServer(config: ResolvedConfig, options: Bridge name: replayConnectionName(subscription.id), source_id: replaySourceId, destination_id: subscription.destinationId, - rules: [{ type: 'filter', headers: { 'x-mcp-subscription-id': subscription.id } }, WEBHOOK_ID_DEDUPE_RULE, SUBSCRIPTION_RETRY_RULE], + rules: [{ type: 'filter', headers: { 'x-mcp-subscription-id': subscription.id } }, EVENT_ID_DEDUPE_RULE, SUBSCRIPTION_RETRY_RULE], }); return connection.id; }, publish: (subscription, envelope) => - hookdeck.publish(REPLAY_SOURCE, { 'content-type': 'application/json', 'webhook-id': envelope.eventId, 'x-mcp-subscription-id': subscription.id }, JSON.stringify(envelope)), + hookdeck.publish( + REPLAY_SOURCE, + { 'content-type': 'application/json', 'webhook-id': deliveryWebhookId(subscription.webhookIdMode, envelope.eventId), 'x-mcp-subscription-id': subscription.id }, + JSON.stringify(envelope), + ), settled: async (connectionId, count, timeoutMs) => { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { diff --git a/test/core/callbacks.test.ts b/test/core/callbacks.test.ts index 2db5da4..e49831a 100644 --- a/test/core/callbacks.test.ts +++ b/test/core/callbacks.test.ts @@ -43,6 +43,7 @@ const subscription = (over: Partial = {}): SubscriptionInput secret: SECRET, replay: null, delivery: healthyDelivery(), + webhookIdMode: 'event', expiresAt: '2026-11-05T00:00:00.000Z', createdAt: '2026-10-05T16:00:00.000Z', updatedAt: '2026-10-05T16:00:00.000Z', diff --git a/test/core/config.test.ts b/test/core/config.test.ts index d9a504d..d826ad0 100644 --- a/test/core/config.test.ts +++ b/test/core/config.test.ts @@ -79,6 +79,14 @@ describe('resolveConfig', () => { expect(() => resolveConfig(config(), { ...base, BRIDGE_MCP_SECRET_URL: 'no' })).toThrow(/BRIDGE_MCP_SECRET_URL must be true or false/); }); + it('chooses webhook-id per subscription (auto) unless BRIDGE_WEBHOOK_ID or subscriptions.webhookId says event or message', () => { + expect(resolveConfig(config(), base).subscriptions.webhookId).toBe('auto'); + expect(resolveConfig(config(), { ...base, BRIDGE_WEBHOOK_ID: 'event' }).subscriptions.webhookId).toBe('event'); + expect(resolveConfig(config(), { ...base, BRIDGE_WEBHOOK_ID: 'message' }).subscriptions.webhookId).toBe('message'); + expect(resolveConfig(config({ subscriptions: { webhookId: 'event' } }), { ...base, BRIDGE_WEBHOOK_ID: 'message' }).subscriptions.webhookId).toBe('event'); + expect(() => resolveConfig(config(), { ...base, BRIDGE_WEBHOOK_ID: 'sep' })).toThrow(/BRIDGE_WEBHOOK_ID \(subscriptions.webhookId\) must be auto, event, message/); + }); + it('rejects a BRIDGE_MCP_SECRET that isn\'t URL-safe, such as a pasted line with a note after the value', () => { expect(resolveConfig(config(), { ...base, BRIDGE_MCP_SECRET: 'Ab-_9.~z' }).auth.mcpSecret).toBe('Ab-_9.~z'); expect(() => resolveConfig(config(), { ...base, BRIDGE_MCP_SECRET: 'abc123 (in .env, or: ...)' })).toThrow(/BRIDGE_MCP_SECRET can only contain/); diff --git a/test/core/event-gateway-store.test.ts b/test/core/event-gateway-store.test.ts index 18d8a1b..4ec2d9a 100644 --- a/test/core/event-gateway-store.test.ts +++ b/test/core/event-gateway-store.test.ts @@ -17,6 +17,7 @@ const input = (over: Partial = {}): SubscriptionInput => ({ secret: SECRET, replay: null, delivery: healthyDelivery(), + webhookIdMode: 'event', expiresAt: '2026-11-05T12:00:00.000Z', createdAt: '2026-10-05T12:00:00.000Z', updatedAt: '2026-10-05T12:00:00.000Z', @@ -58,7 +59,7 @@ describe('EventGatewayStore', () => { expect(connection.rules).toEqual([ { type: 'transform', transformation_id: 'trs_resend' }, { type: 'filter', headers: { 'x-mcp-skip': { $exist: false } }, body: { name: 'resend.email.received', data: { fromAddress: 'alice@example.com' } } }, - expect.objectContaining({ type: 'deduplicate', include_fields: ['headers.webhook-id'] }), + expect.objectContaining({ type: 'deduplicate', include_fields: ['body.eventId'] }), expect.objectContaining({ type: 'retry', response_status_codes: ['>=300', '!410', '!413'] }), ]); }); @@ -88,6 +89,20 @@ describe('EventGatewayStore', () => { expect(JSON.parse(gateway.connections.get(record.connectionId)!.description!).rp).toBeUndefined(); }); + it('marks a per-message webhook-id with wid in the description, reads it back on load, and drops it when a refresh switches to the eventId', async () => { + const { gateway, hookdeck, place, store } = await setup(); + const record = await store.put(input({ webhookIdMode: 'message' })); + expect(JSON.parse(gateway.connections.get(record.connectionId)!.description!).wid).toBe('msg'); + const fresh = new EventGatewayStore(hookdeck, place); + await fresh.load(); + expect(fresh.get(record.id)?.webhookIdMode).toBe('message'); + await store.update(record.id, (current) => ({ ...current!, webhookIdMode: 'event' })); + expect(JSON.parse(gateway.connections.get(record.connectionId)!.description!).wid).toBeUndefined(); + const again = new EventGatewayStore(hookdeck, place); + await again.load(); + expect(again.get(record.id)?.webhookIdMode).toBe('event'); + }); + it('rebuilds the same records on load, reading each secret from destination auth', async () => { const { hookdeck, place, store } = await setup(); const a = await store.put(input({ delivery: { active: false, lastError: 'http_5xx', failedSince: '2026-10-06T00:00:00.000Z' }, replay: { f: 1, w: 2 } })); diff --git a/test/core/notifications.test.ts b/test/core/notifications.test.ts index eed3f31..14564ba 100644 --- a/test/core/notifications.test.ts +++ b/test/core/notifications.test.ts @@ -37,6 +37,7 @@ const subscription = (over: Partial = {}): SubscriptionInput secret: generateWebhookSecret(), replay: null, delivery: healthyDelivery(), + webhookIdMode: 'event', expiresAt: '2026-11-05T00:00:00.000Z', createdAt: '2026-10-05T16:00:00.000Z', updatedAt: '2026-10-05T16:00:00.000Z', diff --git a/test/core/store-concurrency.test.ts b/test/core/store-concurrency.test.ts index 0b35c42..f69285f 100644 --- a/test/core/store-concurrency.test.ts +++ b/test/core/store-concurrency.test.ts @@ -143,6 +143,7 @@ function input(id: string, from = ''): SubscriptionInput { secret: generateWebhookSecret(), replay: null, delivery: healthyDelivery(), + webhookIdMode: 'event', expiresAt: '2026-11-04T12:00:00.000Z', createdAt: '2026-10-05T12:00:00.000Z', updatedAt: '2026-10-05T12:00:00.000Z', diff --git a/test/core/transformation.test.ts b/test/core/transformation.test.ts index 61049b8..0f4177c 100644 --- a/test/core/transformation.test.ts +++ b/test/core/transformation.test.ts @@ -41,10 +41,13 @@ const config = resolved(); const catalog = new Catalog(config.sources); const sourceOf = (id: string) => config.sources.find((s) => s.id === id) as ResolvedSource; -/** Runs a transformation as Event Gateway would: a fresh context with only built-ins, no imports. */ +/** + * Runs a transformation as Event Gateway would: a fresh context with only built-ins, no imports. Event Gateway's + * runtime has a global `crypto` with `getRandomValues` (verified 13 Nov). + */ function run(code: string, request: object, connection: Record = { name: 'mcp-sub-sub_1', description: '{}' }) { let handler: ((req: unknown, ctx: unknown) => unknown) | undefined; - vm.runInNewContext(code, { addHandler: (_type: string, fn: typeof handler) => (handler = fn), Buffer, TextEncoder }); + vm.runInNewContext(code, { addHandler: (_type: string, fn: typeof handler) => (handler = fn), Buffer, TextEncoder, crypto: globalThis.crypto }); // Through JSON, as Event Gateway returns it, so the comparison isn't across realms. return JSON.parse(JSON.stringify(handler!(request, { connection }))) as { headers: Record; @@ -97,6 +100,32 @@ describe('transformation: built from the source runtime, self-contained', () => expect(run(fills, { headers: {}, body: { ...fill, notes: 'x'.repeat(300_000) } }).headers['x-mcp-skip']).toBe('envelope over 256 KiB'); }); + it("sets webhook-id to the eventId by default (legacy clients), and to a random per-message id when the subscription's description has wid", () => { + const req = fixture('resend', 'email-received.json'); + const code = buildTransformation(sourceOf('resend'), catalog); + const legacy = run(code, req, { name: 'mcp-sub-sub_1', description: JSON.stringify({ v: 2, ca: 'a' }) }); + expect(legacy.headers['webhook-id']).toBe(legacy.body.eventId); + + const sep = { name: 'mcp-sub-sub_1', description: JSON.stringify({ v: 2, ca: 'a', wid: 'msg' }) }; + const first = run(code, req, sep); + const second = run(code, req, sep); + // SEP-3415: high entropy, header-safe, not the eventId; the envelope is unchanged. + expect(first.headers['webhook-id']).toMatch(/^msg_[A-Za-z0-9_-]{24}$/); + expect(first.headers['webhook-id']).not.toBe(first.body.eventId); + expect(second.headers['webhook-id']).not.toBe(first.headers['webhook-id']); + expect(first.body.eventId).toBe(legacy.body.eventId); + expect({ ...first.headers, 'webhook-id': '' }).toEqual({ ...legacy.headers, 'webhook-id': '' }); + }); + + it("delivers an event whose id has a period with a per-message webhook-id, since it isn't the eventId", () => { + const fills = buildTransformation(sourceOf('fills'), catalog); + const fill = { type: 'order.filled', id: 'f.1', symbol: 'AAPL', notes: 'ok' }; + const out = run(fills, { headers: {}, body: fill }, { name: 'mcp-sub-sub_1', description: JSON.stringify({ v: 2, ca: 'a', wid: 'msg' }) }); + expect(out.headers['x-mcp-skip']).toBeUndefined(); + expect(out.body.eventId).toBe('f.1'); + expect(out.headers['webhook-id']).toMatch(/^msg_/); + }); + it('maps GitHub events, offering only the enabled ones', () => { const code = buildTransformation(sourceOf('github'), catalog); const issues = fixture('github', 'issues-opened.json'); diff --git a/test/core/webhook-id.test.ts b/test/core/webhook-id.test.ts new file mode 100644 index 0000000..fd59fea --- /dev/null +++ b/test/core/webhook-id.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest'; +import { chooseWebhookIdMode, clientName, declaresEventsExtension, deliveryWebhookId, LEGACY_WEBHOOK_ID_CLIENTS, messageId } from '../../src/core/webhook-id.js'; + +/** A request's `_meta` as a 2026-07-28 client sends it. */ +const meta = (options: { events?: boolean; name?: string } = {}) => ({ + 'io.modelcontextprotocol/protocolVersion': '2026-07-28', + 'io.modelcontextprotocol/clientCapabilities': options.events ? { extensions: { 'io.modelcontextprotocol/events': {} } } : {}, + ...(options.name !== undefined && { 'io.modelcontextprotocol/clientInfo': { name: options.name, version: '1.0.0' } }), +}); + +describe('webhook-id mode', () => { + it('reads the events extension declaration and the client name from _meta', () => { + expect(declaresEventsExtension(meta({ events: true }))).toBe(true); + expect(declaresEventsExtension(meta())).toBe(false); + expect(declaresEventsExtension(undefined)).toBe(false); + expect(declaresEventsExtension({ 'io.modelcontextprotocol/clientCapabilities': { extensions: { 'io.modelcontextprotocol/events': true } } })).toBe(false); + expect(clientName(meta({ name: 'openclaw' }))).toBe('openclaw'); + expect(clientName(meta())).toBeUndefined(); + }); + + it('under auto, gives a per-message id to a client that declares the extension, and the eventId to one that does not', () => { + expect(chooseWebhookIdMode('auto', meta({ events: true, name: 'some-sep-client' }))).toBe('message'); + expect(chooseWebhookIdMode('auto', meta({ events: true }))).toBe('message'); + expect(chooseWebhookIdMode('auto', meta({ name: 'openclaw' }))).toBe('event'); + expect(chooseWebhookIdMode('auto', undefined)).toBe('event'); + }); + + it('under auto, keeps the eventId for a declaring client on the legacy list (TanStack AI declares it, and rejects a per-message id)', () => { + expect(LEGACY_WEBHOOK_ID_CLIENTS).toEqual(expect.arrayContaining(['tanstack-ai-mcp', 'ai-sdk-mcp-client', 'openclaw'])); + for (const name of LEGACY_WEBHOOK_ID_CLIENTS) expect(chooseWebhookIdMode('auto', meta({ events: true, name }))).toBe('event'); + expect(chooseWebhookIdMode('auto', meta({ events: true, name: 'x' }), ['x'])).toBe('event'); + }); + + it('applies event or message to every subscription when the operator sets it', () => { + expect(chooseWebhookIdMode('event', meta({ events: true, name: 'some-sep-client' }))).toBe('event'); + expect(chooseWebhookIdMode('message', meta({ name: 'tanstack-ai-mcp' }))).toBe('message'); + expect(chooseWebhookIdMode('message', undefined)).toBe('message'); + }); + + it('generates header-safe per-message ids, never the eventId', () => { + const ids = new Set(Array.from({ length: 100 }, () => messageId())); + expect(ids.size).toBe(100); + for (const id of ids) expect(id).toMatch(/^msg_[A-Za-z0-9_-]{24}$/); + expect(deliveryWebhookId('event', 'evt_1')).toBe('evt_1'); + expect(deliveryWebhookId('message', 'evt_1')).toMatch(/^msg_/); + }); +}); diff --git a/test/host/bridge.test.ts b/test/host/bridge.test.ts index 8616df4..81a7c7c 100644 --- a/test/host/bridge.test.ts +++ b/test/host/bridge.test.ts @@ -16,7 +16,7 @@ import { createNodeCallbackTransport } from '../../src/host/callback-transport.j import { createBridgeServer, redactPath } from '../../src/host/server.js'; import { resend } from '../../src/sources.js'; import { FakeEventGateway } from '../support/fake-event-gateway.js'; -import { Subscriber } from '../support/subscriber.js'; +import { Subscriber, type SubscriberOptions } from '../support/subscriber.js'; /* * The whole path in one process, with a fake Event Gateway: an MCP client @@ -68,8 +68,9 @@ async function startBridge({ return { gateway, bridge, port, logs }; } -async function startSubscriber(port: number, args: Record = {}) { +async function startSubscriber(port: number, args: Record = {}, options: Partial = {}) { const subscriber = new Subscriber({ + ...options, serverUrl: `http://127.0.0.1:${port}/mcp/${MCP_SECRET}`, token: '', eventName: 'resend.email.received', @@ -95,7 +96,7 @@ async function deliverFromSource(gateway: FakeEventGateway, subscriber: Subscrib if (!connection.name.startsWith('mcp-sub-')) continue; const [transform, filter] = connection.rules as Rules; let handler: ((req: unknown, ctx: unknown) => unknown) | undefined; - vm.runInNewContext(gateway.transformations.get(transform.transformation_id)!.code, { addHandler: (_type: string, fn: typeof handler) => (handler = fn), Buffer, TextEncoder }); + vm.runInNewContext(gateway.transformations.get(transform.transformation_id)!.code, { addHandler: (_type: string, fn: typeof handler) => (handler = fn), Buffer, TextEncoder, crypto: globalThis.crypto }); const out = JSON.parse(JSON.stringify(handler!(request, { connection: { name: connection.name, description: connection.description } }))) as { headers: Record; body: Record; @@ -169,6 +170,40 @@ describe('bridge server', () => { expect(typeof subscriber.events[0]!.cursor).toBe('string'); }); + it("sends a per-message webhook-id to a client that declares the events extension in _meta, through the MCP SDK's request envelope", async () => { + const { gateway, port, bridge, logs } = await startBridge(); + const webhookIds: string[] = []; + const subscriber = await startSubscriber(port, {}, { declareEvents: true, clientName: 'some-sep-client', onEvent: (_event, headers) => webhookIds.push(String(headers['webhook-id'])) }); + const record = bridge.store.get(subscriber.subscription!.id)!; + expect(record.webhookIdMode).toBe('message'); + expect(logs).toContain(`${record.id}: webhook-id per message (client "some-sep-client" declares io.modelcontextprotocol/events)`); + + await deliverFromSource(gateway, subscriber, resendDelivery()); + expect(subscriber.events).toHaveLength(1); + expect(subscriber.events[0]!.eventId).toBe(fixture.headers['svix-id']); + expect(webhookIds).toHaveLength(1); + expect(webhookIds[0]).toMatch(/^msg_[A-Za-z0-9_-]{24}$/); + expect(webhookIds[0]).not.toBe(fixture.headers['svix-id']); + }); + + it('keeps webhook-id equal to the eventId for a client that declares nothing, and for a declaring client on the legacy list', async () => { + const { gateway, port, bridge, logs } = await startBridge(); + const cases = [ + { from: 'a@example.com', options: {}, reason: `client "mcp-events-test-subscriber" doesn't declare io.modelcontextprotocol/events` }, + { from: 'b@example.com', options: { declareEvents: true, clientName: 'tanstack-ai-mcp' }, reason: 'client "tanstack-ai-mcp" declares io.modelcontextprotocol/events' }, + ]; + for (const { from, options, reason } of cases) { + const webhookIds: string[] = []; + const subscriber = await startSubscriber(port, { from }, { ...options, onEvent: (_event, headers) => webhookIds.push(String(headers['webhook-id'])) }); + const record = bridge.store.get(subscriber.subscription!.id)!; + expect(record.webhookIdMode).toBe('event'); + expect(logs).toContain(`${record.id}: webhook-id is the eventId (${reason})`); + const email = freshEmail(); + await deliverFromSource(gateway, subscriber, { headers: fixture.headers, body: { ...email, data: { ...(email.data as object), from } } }); + expect(webhookIds).toEqual([fixture.headers['svix-id']]); + } + }); + it('lists sources with their event types, as events/list describes them, and how many webhook subscriptions each has', async () => { const { port } = await startBridge(); await startSubscriber(port); @@ -229,7 +264,7 @@ describe('bridge server', () => { const store = new MemoryStore(); await store.put({ id: 'sub_old', principal: 'owner', name: 'email.received', arguments: {}, url: 'https://receiver.example.com/hook', - secret: generateWebhookSecret(), replay: null, delivery: healthyDelivery(), + secret: generateWebhookSecret(), replay: null, delivery: healthyDelivery(), webhookIdMode: 'event', expiresAt: '2099-01-01T00:00:00.000Z', createdAt: '2026-10-01T00:00:00.000Z', updatedAt: '2026-10-01T00:00:00.000Z', }); const { logs } = await startBridge({ store }); diff --git a/test/support/subscriber.ts b/test/support/subscriber.ts index 2d4b764..8fc4bef 100644 --- a/test/support/subscriber.ts +++ b/test/support/subscriber.ts @@ -50,6 +50,10 @@ export interface SubscriberOptions { /** Log each `webhook-signature` entry and which secret (current or previous) produced it. */ debug?: boolean; onEvent?: (event: McpEvent, headers: http.IncomingHttpHeaders) => void; + /** The client name the SDK sends in `_meta["io.modelcontextprotocol/clientInfo"]`. Default mcp-events-test-subscriber. */ + clientName?: string; + /** Declare the events extension in the client's capabilities, which the SDK sends in every request's `_meta`. */ + declareEvents?: boolean; /** Tests: the status to answer a verified event delivery with (default 200), for example 410 or 500. Not recorded as received unless 2xx. */ respondWith?: (event: McpEvent) => number; /** Called for every verified event delivery attempt, whatever the response. */ @@ -70,7 +74,7 @@ const MAX_BODY_BYTES = 256 * 1024; const ROTATION_OVERLAP_MS = 15 * 60 * 1000; export class Subscriber { - readonly client = new Client({ name: 'mcp-events-test-subscriber', version: '0.1.0' }, { versionNegotiation: { mode: 'auto' } }); + readonly client: Client; readonly events: McpEvent[] = []; readonly verificationsAnswered: string[] = []; subscription?: SubscribeResponse; @@ -87,6 +91,10 @@ export class Subscriber { constructor(private readonly options: SubscriberOptions) { this.log = options.log ?? ((message) => console.log(`[client] ${message}`)); + this.client = new Client( + { name: options.clientName ?? 'mcp-events-test-subscriber', version: '0.1.0' }, + { versionNegotiation: { mode: 'auto' }, ...(options.declareEvents && { capabilities: { extensions: { 'io.modelcontextprotocol/events': {} } } }) }, + ); if (options.secret && !isValidWebhookSecret(options.secret)) throw new Error('secret must be whsec_ followed by base64 of 24 to 64 bytes'); if (options.secret && options.rotateSecretOnRefresh) throw new Error('secret and rotateSecretOnRefresh cannot be combined'); this.secret = options.secret ?? generateWebhookSecret(); From c1057158d1a2b66b79863353c05c7a24ed269333 Mon Sep 17 00:00:00 2001 From: Phil Leggetter Date: Fri, 13 Nov 2026 13:08:04 +0000 Subject: [PATCH 2/4] docs: per-message webhook-id: architecture, spike record, README, skill and changelog Refs #113 Co-Authored-By: Claude Opus 5.5 --- .env.example | 3 ++ CHANGELOG.md | 10 +++++++ README.md | 8 +++-- docs/ARCHITECTURE.md | 25 +++++++++------- docs/SPIKES.md | 29 +++++++++++++++++++ skills/mcp-events-bridge/SKILL.md | 2 +- .../references/library-clients.md | 4 +-- .../references/receiving-deliveries.md | 2 +- 8 files changed, 66 insertions(+), 17 deletions(-) diff --git a/.env.example b/.env.example index 7c34cd3..503e2e4 100644 --- a/.env.example +++ b/.env.example @@ -14,6 +14,9 @@ HOOKDECK_SIGNING_SECRET= BRIDGE_MCP_SECRET= # `false` turns the URL form (/mcp/) off, for a bridge no ChatGPT connects to. Default true. # BRIDGE_MCP_SECRET_URL= +# Which webhook-id deliveries carry: `auto` (default; per message for clients that declare the events +# extension, except TanStack AI, the AI SDK and OpenClaw), `event` (always the eventId) or `message`. +# BRIDGE_WEBHOOK_ID= # How source events reach the bridge: `cli` locally (hookdeck listen, no public URL) or `http` when # deployed (the default on Fly.io). BRIDGE_INBOUND=cli diff --git a/CHANGELOG.md b/CHANGELOG.md index 9220c11..6657cc6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## Unreleased + +### Added + +- **A per-message `webhook-id` for clients that follow SEP-3415:** a webhook delivery's `webhook-id` was always the event's `eventId`. SEP-3415 now requires a per-message id, unique to one event on one subscription and never derived from `eventId`, so a receiver that dedupes on `webhook-id` doesn't drop an event that matches two of its subscriptions. A client that declares the events extension in a request's `_meta` (`io.modelcontextprotocol/clientCapabilities`) now gets `msg_` and 24 random characters, the same on every retry. Every other client still gets the `eventId`, as do TanStack AI, the Vercel AI SDK and OpenClaw by their default client names, since they reject a delivery whose `webhook-id` isn't its `eventId` (TanStack AI declares the extension). `BRIDGE_WEBHOOK_ID` (`subscriptions.webhookId`) is `auto` by default; `event` or `message` applies to every subscription. A subscription's mode is chosen when it's made or refreshed, and `serve` logs it: `: webhook-id per message (client "" declares io.modelcontextprotocol/events)` or `: webhook-id is the eventId (...)`. With a per-message id, an event whose id contains a period is delivered rather than skipped ([#113](https://github.com/hookdeck/mcp-events-bridge/issues/113)). + +### Changed + +- **Subscriptions dedupe on `eventId`, not `webhook-id`:** each subscription's connection (and a replay's) drops a repeated event by the envelope's `eventId`, since a per-message `webhook-id` differs each time a service resends an event. It's the same as before for subscriptions that get the `eventId`. Existing subscriptions change when they're next refreshed ([#113](https://github.com/hookdeck/mcp-events-bridge/issues/113)). + ## 0.10.0 (2026-11-05) Breaking, for code that reads `list_sources`' `events` as a list of names: each entry is now an event type object; read `events[].name`. diff --git a/README.md b/README.md index bd5cc51..830c6eb 100644 --- a/README.md +++ b/README.md @@ -248,7 +248,7 @@ The server signs each request's raw body with HMAC-SHA256 and the shared secret, These options work for every `source()`, whatever its type: - **`events`:** the sender's event names (offered as `{id}.{name}`, e.g. `fills.order.filled`), as a list or with a description each. Keep a description under about 400 characters: ChatGPT has been reported to leave out events with longer ones, and `setup` and `serve` warn about them. With more than one, `eventType` says where the sender names the event, `{ header }` or `{ field }` (a dot path into the body), and each event's `value` is the sender's name for it (default: the event name). Requests for other values are ignored. -- **`eventId`:** the sender's id for an event, from `{ header }` or `{ field }`. It becomes the MCP event's `eventId` (and its `webhook-id`), and Event Gateway drops repeats within an hour. Default: a hash of the JSON body (the first 32 hex characters of its SHA-256), so a sender's retry with the same body is dropped as a repeat, and two different events with identical bodies count as one. Set it if your sender has an id. +- **`eventId`:** the sender's id for an event, from `{ header }` or `{ field }`. It becomes the MCP event's `eventId` (and its `webhook-id`, for clients that need them equal: see `BRIDGE_WEBHOOK_ID`), and Event Gateway drops repeats within an hour. Default: a hash of the JSON body (the first 32 hex characters of its SHA-256), so a sender's retry with the same body is dropped as a repeat, and two different events with identical bodies count as one. Set it if your sender has an id. - **`occurredAt`:** a body field with an ISO 8601 or Unix time. Default: when Event Gateway received the request (for a live delivery, when Event Gateway built the event from it, moments later). - **Data:** the JSON body as sent, or only the top-level fields in `fields: [...]`. Bodies must be JSON (anything else is skipped, and stays in Event Gateway), and the event at most 256 KiB. - **`filters`:** top-level body fields subscribers can filter on, by exact match of value and type: `{ "quantity": 100 }` matches the number 100, not the string `"100"`. @@ -325,7 +325,7 @@ bridge-hookdeck-notifications source: Event Gateway's issue notifications ``` - **`bridge-`** (here `bridge-resend`) is the source's Event Gateway source, the URL its webhooks are registered with. Setup also writes its transformation, `bridge--envelope`, which turns each request into an MCP Event; every subscription to the source's events uses it. -- **`mcp-sub-`** is one subscription: a connection on the source with the transformation, a filter for the event name and the subscription's arguments, dedupe on `webhook-id` and retries, and a destination at the subscriber's callback URL that signs every attempt with the subscriber's secret. The bridge creates it when an agent subscribes, and deletes it when the subscription ends. +- **`mcp-sub-`** is one subscription: a connection on the source with the transformation, a filter for the event name and the subscription's arguments, dedupe on the event's `eventId` and retries, and a destination at the subscriber's callback URL that signs every attempt with the subscriber's secret. The bridge creates it when an agent subscribes, and deletes it when the subscription ends. - **`bridge-hookdeck-notifications`** receives Event Gateway's issue notifications and forwards them to each deployment, so the bridge hears about failing callbacks and reports them to subscribers. - **`bridge-replay`** (created by the first replay) is a Publish API source: while a subscription made with a cursor catches up, a connection from it, `bridge-replay-`, delivers the replayed events to the subscription's destination, and the bridge deletes it when they're delivered. @@ -343,6 +343,7 @@ Every deployment needs these, whichever sources it uses. | `HOOKDECK_SIGNING_SECRET` | Yes | Verifies Event Gateway's signature on the notifications it sends the bridge | | `BRIDGE_MCP_SECRET` | To run `serve` | The MCP endpoint's secret: sent as `Authorization: Bearer ` to `/mcp`, or in the URL (`/mcp/`) by clients that can't send a header, such as ChatGPT. `setup` generates one, and saves it in `.env` for a local bridge | | `BRIDGE_MCP_SECRET_URL` | No | `false` turns the URL form (`/mcp/`) off, leaving the header; for a bridge no ChatGPT connects to. Default `true` | +| `BRIDGE_WEBHOOK_ID` | No | Which `webhook-id` webhook deliveries carry. `auto` (the default): a per-message id (`msg_...`), as SEP-3415 requires, for a client that declares the events extension in its requests, except TanStack AI, the Vercel AI SDK and OpenClaw by their default client names; the `eventId` for every other client. `event`: always the `eventId`, for clients that reject anything else (set it if one of those three runs under a name of its own). `message`: always per message. `subscriptions.webhookId` in `bridge.config.ts` takes precedence. Applies to a subscription when it's made or refreshed | | `BRIDGE_INBOUND` | No | How Event Gateway's notifications reach the bridge: `cli` (through `hookdeck listen`; also what offers callback URLs to local agents) or `http` (a public URL). Default: `http` on Fly.io, `cli` elsewhere | | `BRIDGE_PUBLIC_URL` | For `http` inbound off Fly.io | The bridge's public URL. Default on Fly.io: `https://$FLY_APP_NAME.fly.dev` | | `BRIDGE_PORT` | No | Listener port (default: `PORT`, else 8080) | @@ -497,7 +498,8 @@ Three TypeScript MCP client libraries have experimental MCP Events support, and | `serve` logs `warning: is a pass-through callback URL` | A subscription uses a callback URL created without a secret | Expected for Hermes Agent and the client libraries; the receiver must verify every delivery | | Subscribing with a callback URL from the bridge fails with `CallbackEndpointError` | The URL was created with a different secret from the one subscribing | Create a callback URL with the secret you subscribe with (one URL holds one secret) | | An event takes a minute or two | `hookdeck listen` occasionally takes ~30s to connect, and Event Gateway occasionally queues a CLI delivery | Wait: the bridge retries missed deliveries itself | -| The same event twice | Two bridges in one Hookdeck project, or a retry | One Hookdeck project per bridge; receivers dedupe by `webhook-id` | +| The same event twice | Two bridges in one Hookdeck project, or a retry | One Hookdeck project per bridge; receivers dedupe by `webhook-id` (a retry keeps it), and by `eventId` for a replayed event, whose per-message `webhook-id` differs from the live delivery's | +| A client library's receiver answers `400` to every delivery | It requires `webhook-id` to equal the `eventId`, and got a per-message id: `serve` logs `: webhook-id per message (...)` | Set `BRIDGE_WEBHOOK_ID=event`, restart `serve`, and have the client subscribe again (or wait for its refresh) | | `setup` or `serve` warns `'s description is ... characters` | A description in `source()` or `defineSource` over 400 characters; ChatGPT has been reported to leave such events out | Shorten it, then refresh the plugin in ChatGPT | | Claude Code (plugin) reports `{"problem": "can't reach the bridge, still retrying: no MCP URL yet ..."}` | The plugin's MCP endpoint isn't set, or was set during this session | Set it, and the secret, with `/plugin configure mcp-events-bridge@hookdeck` in Claude Code (or pipe them to `claude plugin configure mcp-events-bridge@hookdeck --values-stdin`), then start a new session | | Claude Code (plugin) never reports events | The session isn't interactive (`claude -p`), or nothing is watched in this project | Ask "what am I watching?"; plugin monitors run only in interactive sessions | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8850e65..ebbd6d9 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -91,17 +91,19 @@ Event Gateway delivers every MCP Event itself, straight from the service's sourc connection: mcp-sub-, on the service's source bridge- (RESEND, GITHUB, WEBHOOK, STRIPE, ...) rules: transform bridge--envelope, one per source, shared by its subscriptions filter headers: x-mcp-skip absent; body: { name: , data: } - deduplicate headers.webhook-id, 1 hour + deduplicate body.eventId, 1 hour retry exponential, [">=300", "!410", "!413"] destination: mcp-sub-, HTTP, the callback URL, path forwarding off; auth STANDARD_WEBHOOKS with the subscriber's secret -description: {"v":2, principal, event, arguments, expiresAt, createdAt, updatedAt, delivery?, ca, rp?} +description: {"v":2, principal, event, arguments, expiresAt, createdAt, updatedAt, delivery?, ca, rp?, wid?} ``` -- **The transformation** (`src/core/transformation.ts`) is generated from the source's runtime (see "Source definitions"), and written by `setup` and again when `serve` starts, so it matches the running bridge's version and config. It builds the envelope `{ eventId, name, timestamp, data, cursor }`, sets `webhook-id` to the event id and `X-MCP-Subscription-Id` from the connection's name (`context.connection.name`), and clears the sender's query string (the destination doesn't forward the sender's path either). One transformation serves every subscription on the source: it runs for each subscription's connection, before the filter, so each gets its own subscription id (verified). -- **The cursor** is poll's format (see "Poll mode"), built in the transformation from the connection's description: `ca`, the hash of the subscription's arguments, and the time it runs less the look-back. While a replay runs, the description includes `rp`, where the replay started, and every delivery's cursor starts there instead, so a client that saves the latest cursor never skips past events the replay hasn't sent yet (see "Webhook cursors and replay"). The keys are short because the description holds at most 500 characters, with room left for a delivery failure and a replay marker. +- **The transformation** (`src/core/transformation.ts`) is generated from the source's runtime (see "Source definitions"), and written by `setup` and again when `serve` starts, so it matches the running bridge's version and config. It builds the envelope `{ eventId, name, timestamp, data, cursor }`, sets `webhook-id` (see "Which `webhook-id`") and `X-MCP-Subscription-Id` from the connection's name (`context.connection.name`), and clears the sender's query string (the destination doesn't forward the sender's path either). One transformation serves every subscription on the source: it runs for each subscription's connection, before the filter, so each gets its own subscription id (verified). +- **Which `webhook-id`** ([#113](https://github.com/hookdeck/mcp-events-bridge/issues/113), `src/core/webhook-id.ts`). Each subscription has a mode, chosen at every subscribe (so a refresh can change it) and kept in the description as `wid`. **`event`** (no `wid`): `webhook-id` is the `eventId`, for the clients that reject anything else. **`message`** (`"wid":"msg"`): `msg_` and 24 random characters (`crypto.getRandomValues` in the transformation), as SEP-3415 requires. Event Gateway runs the transformation once per event, and automatic and manual retries reuse its headers, so the id stays the same across attempts (verified 13 Nov). The operator setting `BRIDGE_WEBHOOK_ID` (`subscriptions.webhookId`) is `auto` by default: `message` for a client that declares `io.modelcontextprotocol/events` in the request's `_meta` (`io.modelcontextprotocol/clientCapabilities`, which the MCP SDK lifts into `ctx.mcpReq.envelope`), unless its `clientInfo` name is on the legacy list; `event` otherwise. `event` or `message` applies to every subscription. The legacy list holds the default names of the clients that reject a per-message id: `tanstack-ai-mcp` (declares the extension whenever events are on), `ai-sdk-mcp-client` (only if the application passes it) and `openclaw` (declares nothing today). An application that renames its client isn't caught; that deployment sets `BRIDGE_WEBHOOK_ID=event`. +- **Dedupe** is on `body.eventId`, not `webhook-id`: a service resending an event runs the transformation again, which in `message` mode gives a new id. Both are the same in `event` mode. Dedupe on a field the transformation sets works (verified 13 Nov). +- **The cursor** is poll's format (see "Poll mode"), built in the transformation from the connection's description: `ca`, the hash of the subscription's arguments, and the time it runs less the look-back. While a replay runs, the description includes `rp`, where the replay started, and every delivery's cursor starts there instead, so a client that saves the latest cursor never skips past events the replay hasn't sent yet (see "Webhook cursors and replay"). The keys are short because the description holds at most 500 characters, with room left for a delivery failure, a replay marker and `wid`. - **The filter** holds the event name and the subscription's arguments: each event's `filter(args)` (`src/core/filter.ts`), matched against the normalized fields the transformation produces, since Event Gateway's matching is case-sensitive and type-strict. The sources' filters use equality, arrays that contain values (Resend's `to`) and `$or` (GitHub's `actions`), which is lifted to the top of the filter's body (verified). The bridge applies the same filter itself in poll mode. A subscription option that poll can't apply the same way isn't offered ("Decisions", 29 Oct). -- **Skipped events.** The transformation adds an `x-mcp-skip` header to anything that can't be delivered, and every filter requires it to be absent: an event type the source doesn't offer, a request it can't build an event from, an event id containing a period (Standard Webhooks ids can't have one, and Event Gateway fails such an attempt with `DESTINATION_AUTH_FAILED`), and an envelope over 256 KiB. They're recorded as `FILTERED` (verified). A thrown transformation error would instead open an issue for every subscription on every request. +- **Skipped events.** The transformation adds an `x-mcp-skip` header to anything that can't be delivered, and every filter requires it to be absent: an event type the source doesn't offer, a request it can't build an event from, an event id containing a period in `event` mode (Standard Webhooks ids can't have one, and Event Gateway fails such an attempt with `DESTINATION_AUTH_FAILED`; a per-message id never has one), and an envelope over 256 KiB. They're recorded as `FILTERED` (verified). A thrown transformation error would instead open an issue for every subscription on every request. - **The destination** signs each attempt with `webhook-id`, a fresh `webhook-timestamp`, and a `webhook-signature` over the exact body (verified, including manual retries and request retries). That closes the retry gap (conformance row 56), and subscription retries no longer have to fit inside 5 minutes. The connection's description is the subscription's record, as before (see "Data model"); its secret is only in the destination's auth. @@ -793,7 +795,7 @@ Status values: **Conforms**, **Gap**, **Partial**, **N/A** (not applicable: mode Checked on 26 Oct 2026 against `b0efd11` (23 Oct), the SEP's latest commit. The rows above keep `c47fd24`'s line numbers. Three commits changed it: -- **`b0efd11`: `webhook-id` is per message,** not the `eventId` (row 55). **Not followed, on purpose.** OpenAI's guide for ChatGPT says `webhook-id` must be "the same value as the body's `eventId`", and the Vercel AI SDK's webhook handler (`@ai-sdk/mcp` 2.0.84) answers `400` to a delivery whose `webhook-id` isn't its `eventId` (seen 26 Oct, with per-message ids tried on a branch). TanStack AI (`@tanstack/ai-mcp` 1.0.0), which follows SEP-3415 otherwise, checks the same. The bridge keeps `webhook-id` equal to `eventId`, following the clients, and moves to a per-message id once they take on the change (decided 26 Oct). +- **`b0efd11`: `webhook-id` is per message,** not the `eventId` (row 55). **Not followed, on purpose.** OpenAI's guide for ChatGPT says `webhook-id` must be "the same value as the body's `eventId`", and the Vercel AI SDK's webhook handler (`@ai-sdk/mcp` 2.0.84) answers `400` to a delivery whose `webhook-id` isn't its `eventId` (seen 26 Oct, with per-message ids tried on a branch). TanStack AI (`@tanstack/ai-mcp` 1.0.0), which follows SEP-3415 otherwise, checks the same. The bridge kept `webhook-id` equal to `eventId`, following the clients (decided 26 Oct). Since 13 Nov it sends a per-message id to clients that declare the extension and aren't on the legacy list ("Which `webhook-id`"). - **`b0efd11`: dedupe by `eventId` is scoped to a subscription,** since one event can match several. The bridge's own client conforms: `watch` dedupes per watch, which is one name and one set of arguments (`src/host/watch.ts` `runWatch`). - **`2ec39b9`: `Mcp-Name` on `events/poll`, `events/stream`, `events/subscribe` and `events/unsubscribe`** over Streamable HTTP. The client MUST send it, set to `params.name`; the server rejects a missing or different one with `400` and `HeaderMismatch` (`-32020`). **Gap**, on purpose for now: the bridge neither checks nor sends it. The MCP SDK (2.3.1) checks and sends `Mcp-Name` only for `tools/call`, `prompts/get`, `resources/read` and `tasks/*`, and only on 2026-07-28 sessions, so clients built on it (the bridge's `watch` among them) don't send it for `events/*` yet, and requiring it would turn them away. See "Open questions". - **`5da4660`:** conformance suites for the SEP are open for review ([conformance#521](https://github.com/modelcontextprotocol/conformance/pull/521), server; [#541](https://github.com/modelcontextprotocol/conformance/pull/541), client). Not run against the bridge yet. @@ -886,7 +888,7 @@ Checked on 26 Oct 2026 against `b0efd11` (23 Oct), the SEP's latest commit. The | # | SEP § (line) | Requirement | Level | Status | Evidence | Fix (gaps) | | --- | --- | --- | --- | --- | --- | --- | -| 55 | Delivery (533), Signature (638) | Every delivery has `webhook-id` (= `eventId`), `webhook-timestamp` (seconds), `webhook-signature` | MUST | Conforms (via Event Gateway) | The transformation sets `webhook-id` to the `eventId` (`src/core/transformation.ts`); the `STANDARD_WEBHOOKS` destination adds the timestamp and signature on every attempt ("Verified facts") | | +| 55 | Delivery (533), Signature (638) | Every delivery has `webhook-id`, `webhook-timestamp` (seconds), `webhook-signature`; since `b0efd11`, `webhook-id` is per message, kept across retries, never derived from `eventId` | MUST | Conforms for clients that declare the extension; `eventId` for the rest, on purpose | The transformation sets a random `msg_` id in `message` mode and the `eventId` in `event` mode ("Which `webhook-id`"); the `STANDARD_WEBHOOKS` destination adds the timestamp and signature on every attempt, and retries reuse the id ("Verified facts") | Make `message` the default once TanStack AI, the AI SDK and OpenClaw accept it and ChatGPT is checked ([#113](https://github.com/hookdeck/mcp-events-bridge/issues/113)) | | 56 | Delivery (533), Signature (642) | Each retry attempt MUST regenerate timestamp and signature | MUST | Conforms (via Event Gateway) | Since 0.8.0 the destination signs each attempt afresh, including manual and request retries ("Verified facts", 22 Oct). Replayed events and retries of a local agent's missed deliveries go through the same kind of destination | | | 57 | Delivery (535) | Body `cursor` is a safe watermark; MAY be null | MAY | Conforms | Built in the transformation: the time it runs less the look-back, or the replay's start while a replay runs (`src/core/transformation.ts`) | | | 58 | Delivery (536) | Retry each event independently, exponential backoff on non-`2xx`; SHOULD cap attempts and window (3–5 over ≤10–15 min) | SHOULD | Conforms (Event Gateway-dependent) | Retry rule: exponential, `[">=300","!410","!413"]` (`SUBSCRIPTION_RETRY_RULE`, `src/core/hookdeck.ts`); no longer bounded by the 5-minute signature window | Exact Event Gateway spacing not measured in repo (Unknown) | @@ -1022,14 +1024,15 @@ Changed by 22 Oct (probed in production): deliveries are now verified at the edg - `auth_type: STANDARD_WEBHOOKS` with `auth: { webhook_secret_key }`, accepted on HTTP and CLI destinations. The secret must be `whsec_` followed by base64 of 24 to 64 bytes; a 16-byte one is refused with `422`. One key per destination. - Every attempt gets `webhook-id`, a fresh `webhook-timestamp` and one `webhook-signature` over the exact body, and these replace any headers of the same names on the request: a published request with an old timestamp and signature arrived with only the new ones. - `webhook-id` is the request's own `webhook-id` header (or one a transformation set), else Event Gateway's event id. An id containing a period fails the event with `DESTINATION_AUTH_FAILED`, and nothing is sent. +- A transformation runs once per event: a random `webhook-id` it set (`crypto.getRandomValues`), and a `Math.random()` header beside it, were the same on the initial attempt, two automatic retries and a manual retry, each signed with a fresh timestamp. The event's `data.headers` hold the same id (13 Nov, `SPIKES.md`, "Per-message webhook-id (#113)"). A request retry applies only to a request that was rejected or has ignored events (`400` otherwise), so it never re-runs the transformation for an event already made. - A manual retry of an event kept its `webhook-id` and arrived with a timestamp 18 seconds later. A request retry (after an ignored event) and a recovered CLI delivery were signed fresh too (timestamps 0 to 1 seconds old on arrival). - An `MCP_EVENTS` source holding the same secret verified every delivery from such a destination; with a different secret it answered `401`. **Transformations and rules per connection** (22 Oct, probed in production): -- A transformation shared by several connections gets `context.connection` (with `name`) when it runs on an event, and runs for each connection, so each produced its own header value from its own name. `context` has only `connection` (with its name, description, rules, source and destination): no request id, and no time the request arrived. The runtime has `Buffer`, `btoa`, `TextEncoder` and `crypto.subtle` (async), but no synchronous hash (27 Oct). +- A transformation shared by several connections gets `context.connection` (with `name`) when it runs on an event, and runs for each connection, so each produced its own header value from its own name. `context` has only `connection` (with its name, description, rules, source and destination): no request id, and no time the request arrived. The runtime has `Buffer`, `btoa`, `TextEncoder` and `crypto.subtle` (async), but no synchronous hash (27 Oct). It also has a global `crypto` with `getRandomValues` and `randomUUID`, and `require` (13 Nov). - Requests arriving at an `MCP_EVENTS` source from an HTTP destination have no `x-hookdeck-*` headers (27 Oct). -- Filters match the transformation's output: on the event name, on an array containing a value, and on `$or` across values. `$exist: false` on a header the transformation sets drops the event as `FILTERED`. Dedupe on a header the transformation set (`headers.webhook-id`) drops a repeated provider request as `DUPLICATE`. +- Filters match the transformation's output: on the event name, on an array containing a value, and on `$or` across values. `$exist: false` on a header the transformation sets drops the event as `FILTERED`. Dedupe on a header the transformation set (`headers.webhook-id`) drops a repeated provider request as `DUPLICATE`, and so does dedupe on a body field it set (`body.eventId`), even when each run set a different random `webhook-id` (13 Nov). - A request retry (`POST /requests/{id}/retry` with `webhook_ids`) runs the transformation and rules again for that connection: a request first filtered out was delivered after the filter was widened, with the right per-connection header. - A CLI connection records `CLI_DISCONNECTED` before its rules run: with no `listen` session, every request was ignored that way, including ones its filter would drop. Retried once `listen` was back, the filter and dedupe then dropped those. @@ -1130,6 +1133,7 @@ The staged build plan and its status are in [`PLAN.md`](PLAN.md); spike results - **22 Oct, recovery stays in the bridge.** The bridge that runs `listen` for an agent also retries the agent's missed deliveries, rather than the Hookdeck CLI doing it. (How changed on 27 Oct: see above.) - **22 Oct, rotating a callback URL's secret.** Create a new callback URL, until Event Gateway destinations accept a second key. Not a faster secret lookup at Event Gateway's edge. - **26 Oct, `webhook-id` stays the `eventId`.** SEP-3415 changed on 23 Oct (`b0efd11`) to make `webhook-id` per message, never derived from `eventId`. Tried on a branch: Event Gateway's dedupe on `body.eventId` worked ("Verified facts"), but the Vercel AI SDK rejected every delivery, and OpenAI's guide for ChatGPT requires `webhook-id` to equal `eventId`. Reverted before release; row 55 conforms to `c47fd24` and not to `b0efd11`. The bridge follows the clients, and changes once they take on the SEP's rule (Phil, 26 Oct). Stage 8 keeps the transformation setting `webhook-id` to the provider's event id until then. +- **13 Nov, `webhook-id` per subscription** ([#113](https://github.com/hookdeck/mcp-events-bridge/issues/113)). A per-message id for clients that declare the extension in `_meta`, the `eventId` for the rest and for a legacy list by client name, and an operator override. Random, not a hash of the subscription and `eventId`, since the SEP forbids deriving it from `eventId`; the cost is that dedupe moves to `body.eventId`, and that a replayed event and a live delivery of the same event have different ids (receivers already dedupe by `eventId` for that, see "Webhook cursors and replay"). The default stays `auto` until the clients accept a per-message id. - **27 Oct, webhook replay.** Webhook deliveries and subscribe responses include poll's cursors, and a new subscription made with one replays from Event Gateway's history ([#50](https://github.com/hookdeck/mcp-events-bridge/issues/50)). It's the SEP's answer to a client that stopped listening for a while: SEP-3415 has no pause, so a client unsubscribes (or lets its subscription expire) and subscribes again with its cursor. Event Gateway's connection pause (events held, delivered on unpause) wasn't used: MCP Events has no request for it, and holding events past an unsubscribe would break "`cursor: null` = start from now". - **27 Oct, 0.8.0 before the launch.** Stage 8 ships as 0.8.0, and the launch post, diagrams and video use it. Breaking changes are accepted while the bridge is in beta. - **27 Oct, a connection per subscription, still.** Each subscription is a connection on its service's source with its own destination, since an Event Gateway source holds one secret: it's what lets each subscriber's secret sign its own deliveries. @@ -1157,7 +1161,8 @@ The staged build plan and its status are in [`PLAN.md`](PLAN.md); spike results - [ ] Several secrets on one Event Gateway source (an `MCP_EVENTS` source verifying against any of them, or the one for `X-MCP-Subscription-Id`), so pass-through callback URLs can answer the challenge and verify deliveries, for the bridge and a future hosted one. To check: whether Event Gateway's model, API and edge verification can hold and loop several. To request from the Event Gateway team. - [x] Hermes on 0.8.0's pass-through callback URLs: works end to end (27 Oct; see `SPIKES.md`, "Verification (27 Oct)"). - [x] The client libraries (AI SDK, Mastra, TanStack AI) on 0.8.0's pass-through callback URLs: each works end to end (28 Oct; see `SPIKES.md`, "Verification (27 Oct)"). -- [x] `webhook-id`: SEP-3415 (`b0efd11`) wants it per message; ChatGPT's guide, the Vercel AI SDK and TanStack AI want it equal to `eventId`. Decided 26 Oct: follow the clients, and update the bridge once they take on the change. Still open: whether to report the conflict on the SEP's pull request. +- [x] `webhook-id`: SEP-3415 (`b0efd11`) wants it per message; ChatGPT's guide, the Vercel AI SDK and TanStack AI want it equal to `eventId`. Decided 26 Oct: follow the clients, and update the bridge once they take on the change. Since 13 Nov, per subscription ([#113](https://github.com/hookdeck/mcp-events-bridge/issues/113)). Still open: whether to report the conflict on the SEP's pull request. +- [ ] When to make `BRIDGE_WEBHOOK_ID=message` the default, and when to drop each name from the legacy list: once TanStack AI, the AI SDK and OpenClaw release a receiver that accepts a per-message id, and ChatGPT has been checked. Lean: drop each name as its fix ships, and switch the default after ChatGPT. - [x] Stage 8 and webhook cursors: built 27 Oct. The transformation builds poll's cursor from the time it runs and the arguments hash in the connection's description (it needs no request id, since a delivery's cursor has no ids), and the replay's start while a replay runs. Replay publishes through a temporary connection to the subscription's destination. - [x] What ChatGPT does when a paused task resumes: a fresh subscription from now, with a new callback URL and `cursor: null` (27 Oct, 0.7.0), so events sent while it was paused aren't replayed. - [ ] `Mcp-Name` on `events/*` requests (SEP-3415 `2ec39b9`): when to check it. The SEP has the server reject a missing one, but the MCP SDK's clients don't send it for `events/*` yet. Lean: send it from `watch` now, reject a mismatched one, and reject a missing one once the SDK sends it. diff --git a/docs/SPIKES.md b/docs/SPIKES.md index ddd5332..c22af10 100644 --- a/docs/SPIKES.md +++ b/docs/SPIKES.md @@ -339,3 +339,32 @@ Run on the built 0.8.0 branch, in the dedicated project, under deployment names **What it means for the design:** pass-through callback URLs work for a client with a secret per subscription under one base URL, and the migration keeps subscribers' subscriptions and URLs working with no bridge between the service and the subscriber. **Resources:** the `mig07` subscription, callback URL, subscriber callback and notifications connection were deleted by the test (its issue triggers, `bridge-*-mig07`, remain). The Hermes subscription was unsubscribed and its callback URL, `agent-hermes-base`, deleted. `e2e080`'s notifications connection and issue triggers are kept for further e2e runs. + +## Per-message webhook-id (#113) + +Checks for [#113](https://github.com/hookdeck/mcp-events-bridge/issues/113), on 13 Nov 2026: whether Event Gateway keeps a `webhook-id` a transformation generates across retries, whether the runtime has a random source, and what the client libraries declare. + +### What we ran + +- In the bridge's Hookdeck project, a connection `spike-113` from a source `spike-113-in` to an HTTP destination with `STANDARD_WEBHOOKS` auth, at a local receiver behind a cloudflared quick tunnel (Event Gateway had to act on the receiver's status code, which `hookdeck listen` doesn't return to it). Rules: a transformation `spike-113-random-id` that set `webhook-id` to `msg_` and 18 bytes from `crypto.getRandomValues`, a header with `Math.random()`, one with `Date.now()`, and one listing which built-ins exist; and a linear retry rule, 3 retries 20 seconds apart. +- One request, answered `500`, `500`, then `200`. Then a manual retry of the event (`POST /events/{id}/retry`) and a request retry (`POST /requests/{id}/retry`). +- The connection changed to a transformation that sets `body.eventId` from the request, and a dedupe rule on `body.eventId`; requests with keys `A`, `A`, `B`. +- The client libraries' code, read (not run) at vercel/ai `8bc7652` (`@ai-sdk/mcp` 2.0.99), TanStack/ai `1888233` (`@tanstack/ai-mcp` 1.2.0), openclaw/openclaw `94018632` (v2026.11.3: `847611d`), and NousResearch/hermes-agent `9eb9b11`. + +### What we saw + +- The built-ins: `crypto` is an object, with `getRandomValues` and `randomUUID`; `require` exists. +- All four attempts (initial, two automatic, one manual) had the same `webhook-id`, `Math.random()` value and `Date.now()` value, with a fresh `webhook-timestamp` and signature each. The event's `data.headers['webhook-id']` was the same id. The transformation ran once. +- The request retry was refused: `400`, "Request is not eligible for retry because it not rejected or has no ignored events". +- Dedupe on `body.eventId`: the second `A` was ignored as `DUPLICATE`, though its random `webhook-id` differed; `B` was delivered. +- The clients: TanStack AI declares `extensions["io.modelcontextprotocol/events"]` whenever events are enabled (`packages/ai-mcp/src/client.ts:311`, `events/capability.ts:29`), and the MCP TypeScript SDK sends a client's capabilities in every request's `_meta`; the bridge's own test with the SDK client confirmed that the declaration and `clientInfo` reach `ctx.mcpReq.envelope`. The AI SDK sends `_meta` with the capabilities the application passes (none by default; `mcp-client.ts:1071`). OpenClaw sends `clientCapabilities: {}` and `clientInfo.name: "openclaw"` (`src/agents/mcp-event-request.ts:116`). All three still reject a `webhook-id` that isn't the `eventId` (`mcp-event-webhook.ts:211`, `events/webhook.ts:297`, `extensions/mcp-events/src/protocol.ts:179`). Hermes declares nothing and dedupes on `eventId`. Default client names: `tanstack-ai-mcp` and `ai-sdk-mcp-client` (both can be changed by the application), `openclaw`. + +### What it means for the design + +- A random `webhook-id` set in the transformation is stable across retries, so no hash of the subscription and `eventId` is needed (which the SEP forbids anyway). +- Dedupe has to move to `body.eventId`: a service's resend runs the transformation again and gets a new random id. +- The per-request `_meta` declaration alone would break TanStack AI, so the bridge keeps the `eventId` for a legacy list of client names, with `BRIDGE_WEBHOOK_ID=event` for a renamed client. See `ARCHITECTURE.md`, "Which `webhook-id`". + +### Resources + +`spike-113`, `spike-113-in`, `spike-113-dest` and `spike-113-random-id` were deleted after the run. diff --git a/skills/mcp-events-bridge/SKILL.md b/skills/mcp-events-bridge/SKILL.md index 8f4999e..70639e2 100644 --- a/skills/mcp-events-bridge/SKILL.md +++ b/skills/mcp-events-bridge/SKILL.md @@ -110,7 +110,7 @@ Before connecting an agent, check the bridge on its own: from the bridge's folde With an agent: -1. Subscribe an agent (step 4), and check that `serve` logs `subscribed sub_... until ...`. An agent that polls doesn't subscribe: skip to step 2. +1. Subscribe an agent (step 4), and check that `serve` logs `subscribed sub_... until ...`, then `sub_...: webhook-id per message (...)` or `sub_...: webhook-id is the eventId (...)`, saying why. An agent that polls doesn't subscribe: skip to step 2. 2. Trigger a real event: send an email to the Resend receiving address, open a GitHub issue, or have the sender post one. 3. The agent gets it. Events don't pass through the bridge, so `serve` logs nothing for it, except for a local agent: `[listen] agent : ... POST http://localhost:`. 4. In the Event Gateway dashboard, the subscription's connection, `mcp-sub-` on `bridge-`, shows each request: delivered, with its attempts, or `FILTERED` when the subscription's filter or event type didn't match. diff --git a/skills/mcp-events-bridge/references/library-clients.md b/skills/mcp-events-bridge/references/library-clients.md index ebed0c5..4fa2f59 100644 --- a/skills/mcp-events-bridge/references/library-clients.md +++ b/skills/mcp-events-bridge/references/library-clients.md @@ -18,7 +18,7 @@ Three TypeScript MCP client libraries can subscribe to the bridge's events. Each - **With a local bridge, on the same machine:** create one pass-through callback URL, with no secret, since each library generates a secret per subscription: `npx mcp-events-bridge callback-url create --agent --name base --port --path /` from the bridge's directory (or the `create_callback_url` tool with the same arguments). Use a path under the URL it returns as the callback: `https://hkdk.events//mcp-events`. The bridge runs `hookdeck listen` to your port and forwards the path and query string. Use a path under the callback URL, not the URL alone: the AI SDK and TanStack AI add a query string, and the bridge recognizes its URL followed by a path. Event Gateway verifies nothing at a pass-through URL, so the library's own signature check (below) is what protects your receiver. - **The signing secret** is generated by the library, one per subscription, and kept in its store. The store holds secrets: keep it on the server, and make it durable in production (the examples use memory). - **Receivers verify signatures** on the raw body. Pass the request through untouched, as a Web `Request`. -- **`webhook-id`:** the AI SDK and TanStack AI reject a delivery whose `webhook-id` isn't its `eventId`. The bridge sends the `eventId` as `webhook-id`, so this works; a bridge that sent a per-message id, as SEP-3415's latest text asks, wouldn't. +- **`webhook-id`:** the AI SDK and TanStack AI reject a delivery whose `webhook-id` isn't its `eventId`. The bridge sends them the `eventId`: TanStack AI declares the events extension, which would otherwise get a per-message id as SEP-3415 asks, but the bridge keeps the `eventId` for both libraries by their default client names (`tanstack-ai-mcp`, `ai-sdk-mcp-client`). If you rename the client (TanStack AI's `name`, the AI SDK's `clientName`) and declare the extension, set `BRIDGE_WEBHOOK_ID=event` on the bridge. - **Dedupe** by subscription and `eventId`: deliveries are at least once. The examples below wrap a Node `http` request as a Web `Request`. In a framework that already has one (Next.js route handlers, Hono, Remix), pass it straight to the library's handler. @@ -129,5 +129,5 @@ const sub = await mcp.experimental_events.subscribe({ | --- | --- | | Subscribing fails with `CallbackEndpointError` (the bridge's challenge failed) | The callback must be HTTPS and reachable, and answer the challenge. With a local bridge, use a path under a callback URL created without a secret (a URL created with one only accepts that secret) | | The receiver answers `401` | The store lost the subscription (memory store and a restart), or the request was re-serialized: pass the raw body | -| The receiver answers `400` for every delivery | Check the bridge's version: these libraries need `webhook-id` to equal the `eventId`, as the bridge sends it | +| The receiver answers `400` for every delivery | These libraries need `webhook-id` to equal the `eventId`. If `serve` logs `webhook-id per message` for the subscription, the client was renamed: set `BRIDGE_WEBHOOK_ID=event`, restart `serve` and subscribe again | | Mastra or TanStack AI says the server doesn't support events | Both read `extensions["io.modelcontextprotocol/events"]`, which the bridge declares from 0.3.0: upgrade the bridge | diff --git a/skills/mcp-events-bridge/references/receiving-deliveries.md b/skills/mcp-events-bridge/references/receiving-deliveries.md index e5afb01..5a10166 100644 --- a/skills/mcp-events-bridge/references/receiving-deliveries.md +++ b/skills/mcp-events-bridge/references/receiving-deliveries.md @@ -17,7 +17,7 @@ The agent is an MCP client of the bridge, over Streamable HTTP at the MCP URL. I Each delivery is a `POST` to `http://localhost:` (plus any sub-path) with: -- `webhook-id`: the event id. **Dedupe on it**: delivery is at least once. +- `webhook-id`: identifies the delivery, and stays the same across retries. **Dedupe on it**: delivery is at least once. It's a per-message id (`msg_...`) if your client declares the events extension in its requests (SEP-3415), and otherwise the event's `eventId`; the bridge's `BRIDGE_WEBHOOK_ID` overrides that. A per-message id differs between an event's live delivery and its replay, so dedupe on `eventId` too if a replay can overlap live deliveries. - `webhook-timestamp`, `webhook-signature`: [Standard Webhooks](https://www.standardwebhooks.com), signed with your subscription's secret, freshly on every attempt. **Verify every delivery** with a standard library, and reject timestamps more than 5 minutes old. At a pass-through URL this is the only check: anyone who learns the URL can post to your port through it. - `X-MCP-Subscription-Id`: which subscription it's for, so you can pick the secret (or route by path instead). - Body: `{ "eventId", "name", "timestamp", "data", "cursor" }`, at most 256 KiB. `cursor` is a position in the event's history: keep the latest one (from deliveries and subscribe responses) and pass it to `events/subscribe` when you subscribe again, and the bridge replays what you missed. From 280679bf2c6fe2164be6c36f8c13b05b679f10d4 Mon Sep 17 00:00:00 2001 From: Phil Leggetter Date: Fri, 13 Nov 2026 17:44:42 +0000 Subject: [PATCH 3/4] refactor: name the setting BRIDGE_WEBHOOK_ID_FORMAT, with values auto, event-id and per-message BRIDGE_WEBHOOK_ID read as if it held an id. The setting picks what each delivery's webhook-id header holds, so it's now BRIDGE_WEBHOOK_ID_FORMAT (subscriptions.webhookIdFormat), with auto (the default), event-id and per-message. Refs #113 Co-Authored-By: Claude Opus 5.5 --- .env.example | 7 ++-- CHANGELOG.md | 2 +- README.md | 6 +-- docs/ARCHITECTURE.md | 10 ++--- docs/SPIKES.md | 2 +- .../references/library-clients.md | 4 +- .../references/receiving-deliveries.md | 2 +- src/core/config.ts | 22 +++++------ src/core/event-gateway-store.ts | 4 +- src/core/migrate.ts | 2 +- src/core/store.ts | 6 +-- src/core/subscriptions.ts | 16 ++++---- src/core/webhook-id.ts | 39 ++++++++++--------- src/host/server.ts | 2 +- test/core/callbacks.test.ts | 2 +- test/core/config.test.ts | 12 +++--- test/core/event-gateway-store.test.ts | 10 ++--- test/core/notifications.test.ts | 2 +- test/core/store-concurrency.test.ts | 2 +- test/core/webhook-id.test.ts | 28 ++++++------- test/host/bridge.test.ts | 6 +-- 21 files changed, 94 insertions(+), 92 deletions(-) diff --git a/.env.example b/.env.example index 503e2e4..1826f75 100644 --- a/.env.example +++ b/.env.example @@ -14,9 +14,10 @@ HOOKDECK_SIGNING_SECRET= BRIDGE_MCP_SECRET= # `false` turns the URL form (/mcp/) off, for a bridge no ChatGPT connects to. Default true. # BRIDGE_MCP_SECRET_URL= -# Which webhook-id deliveries carry: `auto` (default; per message for clients that declare the events -# extension, except TanStack AI, the AI SDK and OpenClaw), `event` (always the eventId) or `message`. -# BRIDGE_WEBHOOK_ID= +# What each delivery's webhook-id header holds: `event-id` (the event's eventId), `per-message` (a new +# id per delivery, as SEP-3415 requires) or `auto` (default: per-message for clients that declare the +# events extension, except TanStack AI, the AI SDK and OpenClaw; event-id for the rest). +# BRIDGE_WEBHOOK_ID_FORMAT= # How source events reach the bridge: `cli` locally (hookdeck listen, no public URL) or `http` when # deployed (the default on Fly.io). BRIDGE_INBOUND=cli diff --git a/CHANGELOG.md b/CHANGELOG.md index 6657cc6..03bd358 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Added -- **A per-message `webhook-id` for clients that follow SEP-3415:** a webhook delivery's `webhook-id` was always the event's `eventId`. SEP-3415 now requires a per-message id, unique to one event on one subscription and never derived from `eventId`, so a receiver that dedupes on `webhook-id` doesn't drop an event that matches two of its subscriptions. A client that declares the events extension in a request's `_meta` (`io.modelcontextprotocol/clientCapabilities`) now gets `msg_` and 24 random characters, the same on every retry. Every other client still gets the `eventId`, as do TanStack AI, the Vercel AI SDK and OpenClaw by their default client names, since they reject a delivery whose `webhook-id` isn't its `eventId` (TanStack AI declares the extension). `BRIDGE_WEBHOOK_ID` (`subscriptions.webhookId`) is `auto` by default; `event` or `message` applies to every subscription. A subscription's mode is chosen when it's made or refreshed, and `serve` logs it: `: webhook-id per message (client "" declares io.modelcontextprotocol/events)` or `: webhook-id is the eventId (...)`. With a per-message id, an event whose id contains a period is delivered rather than skipped ([#113](https://github.com/hookdeck/mcp-events-bridge/issues/113)). +- **A per-message `webhook-id` for clients that follow SEP-3415:** a webhook delivery's `webhook-id` was always the event's `eventId`. SEP-3415 now requires a per-message id, unique to one event on one subscription and never derived from `eventId`, so a receiver that dedupes on `webhook-id` doesn't drop an event that matches two of its subscriptions. A client that declares the events extension in a request's `_meta` (`io.modelcontextprotocol/clientCapabilities`) now gets `msg_` and 24 random characters, the same on every retry. Every other client still gets the `eventId`, as do TanStack AI, the Vercel AI SDK and OpenClaw by their default client names, since they reject a delivery whose `webhook-id` isn't its `eventId` (TanStack AI declares the extension). `BRIDGE_WEBHOOK_ID_FORMAT` (`subscriptions.webhookIdFormat`) is `auto` by default; `event-id` or `per-message` applies to every subscription. A subscription's format is chosen when it's made or refreshed, and `serve` logs it: `: webhook-id per message (client "" declares io.modelcontextprotocol/events)` or `: webhook-id is the eventId (...)`. With a per-message id, an event whose id contains a period is delivered rather than skipped ([#113](https://github.com/hookdeck/mcp-events-bridge/issues/113)). ### Changed diff --git a/README.md b/README.md index 830c6eb..e81cd56 100644 --- a/README.md +++ b/README.md @@ -248,7 +248,7 @@ The server signs each request's raw body with HMAC-SHA256 and the shared secret, These options work for every `source()`, whatever its type: - **`events`:** the sender's event names (offered as `{id}.{name}`, e.g. `fills.order.filled`), as a list or with a description each. Keep a description under about 400 characters: ChatGPT has been reported to leave out events with longer ones, and `setup` and `serve` warn about them. With more than one, `eventType` says where the sender names the event, `{ header }` or `{ field }` (a dot path into the body), and each event's `value` is the sender's name for it (default: the event name). Requests for other values are ignored. -- **`eventId`:** the sender's id for an event, from `{ header }` or `{ field }`. It becomes the MCP event's `eventId` (and its `webhook-id`, for clients that need them equal: see `BRIDGE_WEBHOOK_ID`), and Event Gateway drops repeats within an hour. Default: a hash of the JSON body (the first 32 hex characters of its SHA-256), so a sender's retry with the same body is dropped as a repeat, and two different events with identical bodies count as one. Set it if your sender has an id. +- **`eventId`:** the sender's id for an event, from `{ header }` or `{ field }`. It becomes the MCP event's `eventId` (and its `webhook-id`, for clients that need them equal: see `BRIDGE_WEBHOOK_ID_FORMAT`), and Event Gateway drops repeats within an hour. Default: a hash of the JSON body (the first 32 hex characters of its SHA-256), so a sender's retry with the same body is dropped as a repeat, and two different events with identical bodies count as one. Set it if your sender has an id. - **`occurredAt`:** a body field with an ISO 8601 or Unix time. Default: when Event Gateway received the request (for a live delivery, when Event Gateway built the event from it, moments later). - **Data:** the JSON body as sent, or only the top-level fields in `fields: [...]`. Bodies must be JSON (anything else is skipped, and stays in Event Gateway), and the event at most 256 KiB. - **`filters`:** top-level body fields subscribers can filter on, by exact match of value and type: `{ "quantity": 100 }` matches the number 100, not the string `"100"`. @@ -343,7 +343,7 @@ Every deployment needs these, whichever sources it uses. | `HOOKDECK_SIGNING_SECRET` | Yes | Verifies Event Gateway's signature on the notifications it sends the bridge | | `BRIDGE_MCP_SECRET` | To run `serve` | The MCP endpoint's secret: sent as `Authorization: Bearer ` to `/mcp`, or in the URL (`/mcp/`) by clients that can't send a header, such as ChatGPT. `setup` generates one, and saves it in `.env` for a local bridge | | `BRIDGE_MCP_SECRET_URL` | No | `false` turns the URL form (`/mcp/`) off, leaving the header; for a bridge no ChatGPT connects to. Default `true` | -| `BRIDGE_WEBHOOK_ID` | No | Which `webhook-id` webhook deliveries carry. `auto` (the default): a per-message id (`msg_...`), as SEP-3415 requires, for a client that declares the events extension in its requests, except TanStack AI, the Vercel AI SDK and OpenClaw by their default client names; the `eventId` for every other client. `event`: always the `eventId`, for clients that reject anything else (set it if one of those three runs under a name of its own). `message`: always per message. `subscriptions.webhookId` in `bridge.config.ts` takes precedence. Applies to a subscription when it's made or refreshed | +| `BRIDGE_WEBHOOK_ID_FORMAT` | No | What the `webhook-id` header of each webhook delivery holds. `event-id`: the event's `eventId`, for clients that reject anything else (set it if TanStack AI, the Vercel AI SDK or OpenClaw runs under a client name of its own). `per-message`: a new id for each delivery (`msg_...`), kept across retries, as SEP-3415 requires. `auto` (the default): `per-message` for a client that declares the events extension in its requests, except TanStack AI, the Vercel AI SDK and OpenClaw by their default client names; `event-id` for every other client. `subscriptions.webhookIdFormat` in `bridge.config.ts` takes precedence. Applies to a subscription when it's made or refreshed | | `BRIDGE_INBOUND` | No | How Event Gateway's notifications reach the bridge: `cli` (through `hookdeck listen`; also what offers callback URLs to local agents) or `http` (a public URL). Default: `http` on Fly.io, `cli` elsewhere | | `BRIDGE_PUBLIC_URL` | For `http` inbound off Fly.io | The bridge's public URL. Default on Fly.io: `https://$FLY_APP_NAME.fly.dev` | | `BRIDGE_PORT` | No | Listener port (default: `PORT`, else 8080) | @@ -499,7 +499,7 @@ Three TypeScript MCP client libraries have experimental MCP Events support, and | Subscribing with a callback URL from the bridge fails with `CallbackEndpointError` | The URL was created with a different secret from the one subscribing | Create a callback URL with the secret you subscribe with (one URL holds one secret) | | An event takes a minute or two | `hookdeck listen` occasionally takes ~30s to connect, and Event Gateway occasionally queues a CLI delivery | Wait: the bridge retries missed deliveries itself | | The same event twice | Two bridges in one Hookdeck project, or a retry | One Hookdeck project per bridge; receivers dedupe by `webhook-id` (a retry keeps it), and by `eventId` for a replayed event, whose per-message `webhook-id` differs from the live delivery's | -| A client library's receiver answers `400` to every delivery | It requires `webhook-id` to equal the `eventId`, and got a per-message id: `serve` logs `: webhook-id per message (...)` | Set `BRIDGE_WEBHOOK_ID=event`, restart `serve`, and have the client subscribe again (or wait for its refresh) | +| A client library's receiver answers `400` to every delivery | It requires `webhook-id` to equal the `eventId`, and got a per-message id: `serve` logs `: webhook-id per message (...)` | Set `BRIDGE_WEBHOOK_ID_FORMAT=event-id`, restart `serve`, and have the client subscribe again (or wait for its refresh) | | `setup` or `serve` warns `'s description is ... characters` | A description in `source()` or `defineSource` over 400 characters; ChatGPT has been reported to leave such events out | Shorten it, then refresh the plugin in ChatGPT | | Claude Code (plugin) reports `{"problem": "can't reach the bridge, still retrying: no MCP URL yet ..."}` | The plugin's MCP endpoint isn't set, or was set during this session | Set it, and the secret, with `/plugin configure mcp-events-bridge@hookdeck` in Claude Code (or pipe them to `claude plugin configure mcp-events-bridge@hookdeck --values-stdin`), then start a new session | | Claude Code (plugin) never reports events | The session isn't interactive (`claude -p`), or nothing is watched in this project | Ask "what am I watching?"; plugin monitors run only in interactive sessions | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ebbd6d9..f328e16 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -99,11 +99,11 @@ description: {"v":2, principal, event, arguments, expiresAt, createdAt, updatedA ``` - **The transformation** (`src/core/transformation.ts`) is generated from the source's runtime (see "Source definitions"), and written by `setup` and again when `serve` starts, so it matches the running bridge's version and config. It builds the envelope `{ eventId, name, timestamp, data, cursor }`, sets `webhook-id` (see "Which `webhook-id`") and `X-MCP-Subscription-Id` from the connection's name (`context.connection.name`), and clears the sender's query string (the destination doesn't forward the sender's path either). One transformation serves every subscription on the source: it runs for each subscription's connection, before the filter, so each gets its own subscription id (verified). -- **Which `webhook-id`** ([#113](https://github.com/hookdeck/mcp-events-bridge/issues/113), `src/core/webhook-id.ts`). Each subscription has a mode, chosen at every subscribe (so a refresh can change it) and kept in the description as `wid`. **`event`** (no `wid`): `webhook-id` is the `eventId`, for the clients that reject anything else. **`message`** (`"wid":"msg"`): `msg_` and 24 random characters (`crypto.getRandomValues` in the transformation), as SEP-3415 requires. Event Gateway runs the transformation once per event, and automatic and manual retries reuse its headers, so the id stays the same across attempts (verified 13 Nov). The operator setting `BRIDGE_WEBHOOK_ID` (`subscriptions.webhookId`) is `auto` by default: `message` for a client that declares `io.modelcontextprotocol/events` in the request's `_meta` (`io.modelcontextprotocol/clientCapabilities`, which the MCP SDK lifts into `ctx.mcpReq.envelope`), unless its `clientInfo` name is on the legacy list; `event` otherwise. `event` or `message` applies to every subscription. The legacy list holds the default names of the clients that reject a per-message id: `tanstack-ai-mcp` (declares the extension whenever events are on), `ai-sdk-mcp-client` (only if the application passes it) and `openclaw` (declares nothing today). An application that renames its client isn't caught; that deployment sets `BRIDGE_WEBHOOK_ID=event`. -- **Dedupe** is on `body.eventId`, not `webhook-id`: a service resending an event runs the transformation again, which in `message` mode gives a new id. Both are the same in `event` mode. Dedupe on a field the transformation sets works (verified 13 Nov). +- **Which `webhook-id`** ([#113](https://github.com/hookdeck/mcp-events-bridge/issues/113), `src/core/webhook-id.ts`). Each subscription has a `webhook-id` format, chosen at every subscribe (so a refresh can change it) and kept in the description as `wid`. **`event-id`** (no `wid`): `webhook-id` is the `eventId`, for the clients that reject anything else. **`per-message`** (`"wid":"msg"`): `msg_` and 24 random characters (`crypto.getRandomValues` in the transformation), as SEP-3415 requires. Event Gateway runs the transformation once per event, and automatic and manual retries reuse its headers, so the id stays the same across attempts (verified 13 Nov). The operator setting `BRIDGE_WEBHOOK_ID_FORMAT` (`subscriptions.webhookIdFormat`) is `auto` by default: `per-message` for a client that declares `io.modelcontextprotocol/events` in the request's `_meta` (`io.modelcontextprotocol/clientCapabilities`, which the MCP SDK lifts into `ctx.mcpReq.envelope`), unless its `clientInfo` name is on the legacy list; `event-id` otherwise. `event-id` or `per-message` applies to every subscription. The legacy list holds the default names of the clients that reject a per-message id: `tanstack-ai-mcp` (declares the extension whenever events are on), `ai-sdk-mcp-client` (only if the application passes it) and `openclaw` (declares nothing today). An application that renames its client isn't caught; that deployment sets `BRIDGE_WEBHOOK_ID_FORMAT=event-id`. +- **Dedupe** is on `body.eventId`, not `webhook-id`: a service resending an event runs the transformation again, which with `per-message` gives a new id. Both are the same with `event-id`. Dedupe on a field the transformation sets works (verified 13 Nov). - **The cursor** is poll's format (see "Poll mode"), built in the transformation from the connection's description: `ca`, the hash of the subscription's arguments, and the time it runs less the look-back. While a replay runs, the description includes `rp`, where the replay started, and every delivery's cursor starts there instead, so a client that saves the latest cursor never skips past events the replay hasn't sent yet (see "Webhook cursors and replay"). The keys are short because the description holds at most 500 characters, with room left for a delivery failure, a replay marker and `wid`. - **The filter** holds the event name and the subscription's arguments: each event's `filter(args)` (`src/core/filter.ts`), matched against the normalized fields the transformation produces, since Event Gateway's matching is case-sensitive and type-strict. The sources' filters use equality, arrays that contain values (Resend's `to`) and `$or` (GitHub's `actions`), which is lifted to the top of the filter's body (verified). The bridge applies the same filter itself in poll mode. A subscription option that poll can't apply the same way isn't offered ("Decisions", 29 Oct). -- **Skipped events.** The transformation adds an `x-mcp-skip` header to anything that can't be delivered, and every filter requires it to be absent: an event type the source doesn't offer, a request it can't build an event from, an event id containing a period in `event` mode (Standard Webhooks ids can't have one, and Event Gateway fails such an attempt with `DESTINATION_AUTH_FAILED`; a per-message id never has one), and an envelope over 256 KiB. They're recorded as `FILTERED` (verified). A thrown transformation error would instead open an issue for every subscription on every request. +- **Skipped events.** The transformation adds an `x-mcp-skip` header to anything that can't be delivered, and every filter requires it to be absent: an event type the source doesn't offer, a request it can't build an event from, an event id containing a period with `event-id` (Standard Webhooks ids can't have one, and Event Gateway fails such an attempt with `DESTINATION_AUTH_FAILED`; a per-message id never has one), and an envelope over 256 KiB. They're recorded as `FILTERED` (verified). A thrown transformation error would instead open an issue for every subscription on every request. - **The destination** signs each attempt with `webhook-id`, a fresh `webhook-timestamp`, and a `webhook-signature` over the exact body (verified, including manual retries and request retries). That closes the retry gap (conformance row 56), and subscription retries no longer have to fit inside 5 minutes. The connection's description is the subscription's record, as before (see "Data model"); its secret is only in the destination's auth. @@ -888,7 +888,7 @@ Checked on 26 Oct 2026 against `b0efd11` (23 Oct), the SEP's latest commit. The | # | SEP § (line) | Requirement | Level | Status | Evidence | Fix (gaps) | | --- | --- | --- | --- | --- | --- | --- | -| 55 | Delivery (533), Signature (638) | Every delivery has `webhook-id`, `webhook-timestamp` (seconds), `webhook-signature`; since `b0efd11`, `webhook-id` is per message, kept across retries, never derived from `eventId` | MUST | Conforms for clients that declare the extension; `eventId` for the rest, on purpose | The transformation sets a random `msg_` id in `message` mode and the `eventId` in `event` mode ("Which `webhook-id`"); the `STANDARD_WEBHOOKS` destination adds the timestamp and signature on every attempt, and retries reuse the id ("Verified facts") | Make `message` the default once TanStack AI, the AI SDK and OpenClaw accept it and ChatGPT is checked ([#113](https://github.com/hookdeck/mcp-events-bridge/issues/113)) | +| 55 | Delivery (533), Signature (638) | Every delivery has `webhook-id`, `webhook-timestamp` (seconds), `webhook-signature`; since `b0efd11`, `webhook-id` is per message, kept across retries, never derived from `eventId` | MUST | Conforms for clients that declare the extension; `eventId` for the rest, on purpose | The transformation sets a random `msg_` id for `per-message` and the `eventId` for `event-id` ("Which `webhook-id`"); the `STANDARD_WEBHOOKS` destination adds the timestamp and signature on every attempt, and retries reuse the id ("Verified facts") | Make `per-message` the default once TanStack AI, the AI SDK and OpenClaw accept it and ChatGPT is checked ([#113](https://github.com/hookdeck/mcp-events-bridge/issues/113)) | | 56 | Delivery (533), Signature (642) | Each retry attempt MUST regenerate timestamp and signature | MUST | Conforms (via Event Gateway) | Since 0.8.0 the destination signs each attempt afresh, including manual and request retries ("Verified facts", 22 Oct). Replayed events and retries of a local agent's missed deliveries go through the same kind of destination | | | 57 | Delivery (535) | Body `cursor` is a safe watermark; MAY be null | MAY | Conforms | Built in the transformation: the time it runs less the look-back, or the replay's start while a replay runs (`src/core/transformation.ts`) | | | 58 | Delivery (536) | Retry each event independently, exponential backoff on non-`2xx`; SHOULD cap attempts and window (3–5 over ≤10–15 min) | SHOULD | Conforms (Event Gateway-dependent) | Retry rule: exponential, `[">=300","!410","!413"]` (`SUBSCRIPTION_RETRY_RULE`, `src/core/hookdeck.ts`); no longer bounded by the 5-minute signature window | Exact Event Gateway spacing not measured in repo (Unknown) | @@ -1162,7 +1162,7 @@ The staged build plan and its status are in [`PLAN.md`](PLAN.md); spike results - [x] Hermes on 0.8.0's pass-through callback URLs: works end to end (27 Oct; see `SPIKES.md`, "Verification (27 Oct)"). - [x] The client libraries (AI SDK, Mastra, TanStack AI) on 0.8.0's pass-through callback URLs: each works end to end (28 Oct; see `SPIKES.md`, "Verification (27 Oct)"). - [x] `webhook-id`: SEP-3415 (`b0efd11`) wants it per message; ChatGPT's guide, the Vercel AI SDK and TanStack AI want it equal to `eventId`. Decided 26 Oct: follow the clients, and update the bridge once they take on the change. Since 13 Nov, per subscription ([#113](https://github.com/hookdeck/mcp-events-bridge/issues/113)). Still open: whether to report the conflict on the SEP's pull request. -- [ ] When to make `BRIDGE_WEBHOOK_ID=message` the default, and when to drop each name from the legacy list: once TanStack AI, the AI SDK and OpenClaw release a receiver that accepts a per-message id, and ChatGPT has been checked. Lean: drop each name as its fix ships, and switch the default after ChatGPT. +- [ ] When to make `BRIDGE_WEBHOOK_ID_FORMAT=per-message` the default, and when to drop each name from the legacy list: once TanStack AI, the AI SDK and OpenClaw release a receiver that accepts a per-message id, and ChatGPT has been checked. Lean: drop each name as its fix ships, and switch the default after ChatGPT. - [x] Stage 8 and webhook cursors: built 27 Oct. The transformation builds poll's cursor from the time it runs and the arguments hash in the connection's description (it needs no request id, since a delivery's cursor has no ids), and the replay's start while a replay runs. Replay publishes through a temporary connection to the subscription's destination. - [x] What ChatGPT does when a paused task resumes: a fresh subscription from now, with a new callback URL and `cursor: null` (27 Oct, 0.7.0), so events sent while it was paused aren't replayed. - [ ] `Mcp-Name` on `events/*` requests (SEP-3415 `2ec39b9`): when to check it. The SEP has the server reject a missing one, but the MCP SDK's clients don't send it for `events/*` yet. Lean: send it from `watch` now, reject a mismatched one, and reject a missing one once the SDK sends it. diff --git a/docs/SPIKES.md b/docs/SPIKES.md index c22af10..dddf672 100644 --- a/docs/SPIKES.md +++ b/docs/SPIKES.md @@ -363,7 +363,7 @@ Checks for [#113](https://github.com/hookdeck/mcp-events-bridge/issues/113), on - A random `webhook-id` set in the transformation is stable across retries, so no hash of the subscription and `eventId` is needed (which the SEP forbids anyway). - Dedupe has to move to `body.eventId`: a service's resend runs the transformation again and gets a new random id. -- The per-request `_meta` declaration alone would break TanStack AI, so the bridge keeps the `eventId` for a legacy list of client names, with `BRIDGE_WEBHOOK_ID=event` for a renamed client. See `ARCHITECTURE.md`, "Which `webhook-id`". +- The per-request `_meta` declaration alone would break TanStack AI, so the bridge keeps the `eventId` for a legacy list of client names, with `BRIDGE_WEBHOOK_ID_FORMAT=event-id` for a renamed client. See `ARCHITECTURE.md`, "Which `webhook-id`". ### Resources diff --git a/skills/mcp-events-bridge/references/library-clients.md b/skills/mcp-events-bridge/references/library-clients.md index 4fa2f59..9cd1a70 100644 --- a/skills/mcp-events-bridge/references/library-clients.md +++ b/skills/mcp-events-bridge/references/library-clients.md @@ -18,7 +18,7 @@ Three TypeScript MCP client libraries can subscribe to the bridge's events. Each - **With a local bridge, on the same machine:** create one pass-through callback URL, with no secret, since each library generates a secret per subscription: `npx mcp-events-bridge callback-url create --agent --name base --port --path /` from the bridge's directory (or the `create_callback_url` tool with the same arguments). Use a path under the URL it returns as the callback: `https://hkdk.events//mcp-events`. The bridge runs `hookdeck listen` to your port and forwards the path and query string. Use a path under the callback URL, not the URL alone: the AI SDK and TanStack AI add a query string, and the bridge recognizes its URL followed by a path. Event Gateway verifies nothing at a pass-through URL, so the library's own signature check (below) is what protects your receiver. - **The signing secret** is generated by the library, one per subscription, and kept in its store. The store holds secrets: keep it on the server, and make it durable in production (the examples use memory). - **Receivers verify signatures** on the raw body. Pass the request through untouched, as a Web `Request`. -- **`webhook-id`:** the AI SDK and TanStack AI reject a delivery whose `webhook-id` isn't its `eventId`. The bridge sends them the `eventId`: TanStack AI declares the events extension, which would otherwise get a per-message id as SEP-3415 asks, but the bridge keeps the `eventId` for both libraries by their default client names (`tanstack-ai-mcp`, `ai-sdk-mcp-client`). If you rename the client (TanStack AI's `name`, the AI SDK's `clientName`) and declare the extension, set `BRIDGE_WEBHOOK_ID=event` on the bridge. +- **`webhook-id`:** the AI SDK and TanStack AI reject a delivery whose `webhook-id` isn't its `eventId`. The bridge sends them the `eventId`: TanStack AI declares the events extension, which would otherwise get a per-message id as SEP-3415 asks, but the bridge keeps the `eventId` for both libraries by their default client names (`tanstack-ai-mcp`, `ai-sdk-mcp-client`). If you rename the client (TanStack AI's `name`, the AI SDK's `clientName`) and declare the extension, set `BRIDGE_WEBHOOK_ID_FORMAT=event-id` on the bridge. - **Dedupe** by subscription and `eventId`: deliveries are at least once. The examples below wrap a Node `http` request as a Web `Request`. In a framework that already has one (Next.js route handlers, Hono, Remix), pass it straight to the library's handler. @@ -129,5 +129,5 @@ const sub = await mcp.experimental_events.subscribe({ | --- | --- | | Subscribing fails with `CallbackEndpointError` (the bridge's challenge failed) | The callback must be HTTPS and reachable, and answer the challenge. With a local bridge, use a path under a callback URL created without a secret (a URL created with one only accepts that secret) | | The receiver answers `401` | The store lost the subscription (memory store and a restart), or the request was re-serialized: pass the raw body | -| The receiver answers `400` for every delivery | These libraries need `webhook-id` to equal the `eventId`. If `serve` logs `webhook-id per message` for the subscription, the client was renamed: set `BRIDGE_WEBHOOK_ID=event`, restart `serve` and subscribe again | +| The receiver answers `400` for every delivery | These libraries need `webhook-id` to equal the `eventId`. If `serve` logs `webhook-id per message` for the subscription, the client was renamed: set `BRIDGE_WEBHOOK_ID_FORMAT=event-id`, restart `serve` and subscribe again | | Mastra or TanStack AI says the server doesn't support events | Both read `extensions["io.modelcontextprotocol/events"]`, which the bridge declares from 0.3.0: upgrade the bridge | diff --git a/skills/mcp-events-bridge/references/receiving-deliveries.md b/skills/mcp-events-bridge/references/receiving-deliveries.md index 5a10166..6d041bd 100644 --- a/skills/mcp-events-bridge/references/receiving-deliveries.md +++ b/skills/mcp-events-bridge/references/receiving-deliveries.md @@ -17,7 +17,7 @@ The agent is an MCP client of the bridge, over Streamable HTTP at the MCP URL. I Each delivery is a `POST` to `http://localhost:` (plus any sub-path) with: -- `webhook-id`: identifies the delivery, and stays the same across retries. **Dedupe on it**: delivery is at least once. It's a per-message id (`msg_...`) if your client declares the events extension in its requests (SEP-3415), and otherwise the event's `eventId`; the bridge's `BRIDGE_WEBHOOK_ID` overrides that. A per-message id differs between an event's live delivery and its replay, so dedupe on `eventId` too if a replay can overlap live deliveries. +- `webhook-id`: identifies the delivery, and stays the same across retries. **Dedupe on it**: delivery is at least once. It's a per-message id (`msg_...`) if your client declares the events extension in its requests (SEP-3415), and otherwise the event's `eventId`; the bridge's `BRIDGE_WEBHOOK_ID_FORMAT` overrides that. A per-message id differs between an event's live delivery and its replay, so dedupe on `eventId` too if a replay can overlap live deliveries. - `webhook-timestamp`, `webhook-signature`: [Standard Webhooks](https://www.standardwebhooks.com), signed with your subscription's secret, freshly on every attempt. **Verify every delivery** with a standard library, and reject timestamps more than 5 minutes old. At a pass-through URL this is the only check: anyone who learns the URL can post to your port through it. - `X-MCP-Subscription-Id`: which subscription it's for, so you can pick the secret (or route by path instead). - Body: `{ "eventId", "name", "timestamp", "data", "cursor" }`, at most 256 KiB. `cursor` is a position in the event's history: keep the latest one (from deliveries and subscribe responses) and pass it to `events/subscribe` when you subscribe again, and the bridge replays what you missed. diff --git a/src/core/config.ts b/src/core/config.ts index f3f881f..7d6c42f 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -1,5 +1,5 @@ import type { SourceDefinition } from './sources/types.js'; -import { WEBHOOK_ID_SETTINGS, type WebhookIdSetting } from './webhook-id.js'; +import { WEBHOOK_ID_FORMATS, type WebhookIdFormatSetting } from './webhook-id.js'; /* * The typed config file, bridge.config.ts: @@ -94,11 +94,11 @@ export interface BridgeConfig { export interface SubscriptionSettings { /** - * Which `webhook-id` deliveries carry: `auto` (per message for a client that declares the events extension in its - * request `_meta`, else the `eventId`), `event` (always the `eventId`) or `message` (always per message). See - * webhook-id.ts. Default: BRIDGE_WEBHOOK_ID, else `auto`. + * What deliveries' `webhook-id` holds: `auto` (`per-message` for a client that declares the events extension in its + * request `_meta`, else `event-id`), `event-id` (always the event's `eventId`) or `per-message` (always a new id per + * delivery). See webhook-id.ts. Default: BRIDGE_WEBHOOK_ID_FORMAT, else `auto`. */ - webhookId: WebhookIdSetting; + webhookIdFormat: WebhookIdFormatSetting; defaultTtlMs: number; minTtlMs: number; maxTtlMs: number; @@ -109,7 +109,7 @@ export interface SubscriptionSettings { } export const DEFAULT_SUBSCRIPTION_SETTINGS: SubscriptionSettings = { - webhookId: 'auto', + webhookIdFormat: 'auto', // Long: ChatGPT sent no ttlMs in the 1 Oct test, and the bridge may be offline when a refresh is due. defaultTtlMs: 30 * 24 * 60 * 60 * 1000, minTtlMs: 60 * 1000, @@ -151,10 +151,10 @@ function parseBoolean(name: string, value: string | undefined, fallback: boolean throw new ConfigError(`${name} must be true or false`); } -function parseWebhookId(value: string | undefined): WebhookIdSetting { - if (value === undefined || value === '') return DEFAULT_SUBSCRIPTION_SETTINGS.webhookId; - if ((WEBHOOK_ID_SETTINGS as readonly string[]).includes(value)) return value as WebhookIdSetting; - throw new ConfigError(`BRIDGE_WEBHOOK_ID (subscriptions.webhookId) must be ${WEBHOOK_ID_SETTINGS.join(', ')}`); +function parseWebhookIdFormat(value: string | undefined): WebhookIdFormatSetting { + if (value === undefined || value === '') return DEFAULT_SUBSCRIPTION_SETTINGS.webhookIdFormat; + if ((WEBHOOK_ID_FORMATS as readonly string[]).includes(value)) return value as WebhookIdFormatSetting; + throw new ConfigError(`BRIDGE_WEBHOOK_ID_FORMAT (subscriptions.webhookIdFormat) must be ${WEBHOOK_ID_FORMATS.join(', ')}`); } /** Resolves env() references and defaults. Missing required variables are collected into one error. */ @@ -215,7 +215,7 @@ export function resolveConfig(config: BridgeConfig, environment: Record record !== undefined && Date.parse(record.expiresAt) > now.getTime(); // Read and written in the store's queue, so a concurrent write (a delivery-failure notification) can't be lost or undo this. const prior: { record?: SubscriptionRecord } = {}; @@ -208,7 +208,7 @@ export class SubscriptionService { replay: cursorCheck && this.deps.cursors && !live(existing) ? cursorCheck.position : live(existing) ? existing!.replay : null, // A refresh is the subscriber's liveness signal: delivery is active again. delivery: healthyDelivery(), - webhookIdMode, + webhookIdFormat, expiresAt: expiresAt.toISOString(), createdAt: existing?.createdAt ?? now.toISOString(), updatedAt: now.toISOString(), @@ -222,7 +222,7 @@ export class SubscriptionService { const existing = prior.record; if (existing && existing.secret !== secret) this.log(`rotated secret for ${id}`); this.log(`${existing ? 'refreshed' : 'subscribed'} ${id} until ${expiresAt.toISOString()}`); - this.log(`${id}: webhook-id ${webhookIdMode === 'message' ? 'per message' : 'is the eventId'} (${describeClient(settings.webhookId, request.meta)})`); + this.log(`${id}: webhook-id ${webhookIdFormat === 'per-message' ? 'per message' : 'is the eventId'} (${describeClient(settings.webhookIdFormat, request.meta)})`); return { id, diff --git a/src/core/webhook-id.ts b/src/core/webhook-id.ts index c01f550..1323896 100644 --- a/src/core/webhook-id.ts +++ b/src/core/webhook-id.ts @@ -1,24 +1,25 @@ import { randomBytes } from 'node:crypto'; /* - * Which `webhook-id` a subscription's deliveries carry (#113). + * The format of a subscription's deliveries' `webhook-id` (#113). * - * event the event's `eventId`, as the bridge has always sent it. The Vercel AI SDK, TanStack AI and OpenClaw reject - * a delivery whose `webhook-id` isn't its `eventId`, and OpenAI's guide for ChatGPT asks for the same. - * message a per-message id, `msg_` and 24 random characters, as SEP-3415 requires: unique to one event on one - * subscription, kept across retries, and never derived from `eventId`. + * event-id the event's `eventId`, as the bridge has always sent it. The Vercel AI SDK, TanStack AI and OpenClaw + * reject a delivery whose `webhook-id` isn't its `eventId`, and OpenAI's guide for ChatGPT asks for the + * same. + * per-message `msg_` and 24 random characters, as SEP-3415 requires: unique to one event on one subscription, kept + * across retries, and never derived from `eventId`. * - * The mode is chosen at subscribe time and kept in the subscription's connection description, where the + * The format is chosen at subscribe time and kept in the subscription's connection description, where the * transformation reads it. Event Gateway runs the transformation once per event and every attempt (automatic or * manual retry) reuses its headers, so a generated id stays the same across retries (verified 13 Nov). */ -export type WebhookIdMode = 'event' | 'message'; +export type WebhookIdFormat = 'event-id' | 'per-message'; /** The operator's choice: `auto` picks per subscription, from what the client declares; the others apply to every subscription. */ -export type WebhookIdSetting = 'auto' | WebhookIdMode; +export type WebhookIdFormatSetting = 'auto' | WebhookIdFormat; -export const WEBHOOK_ID_SETTINGS: readonly WebhookIdSetting[] = ['auto', 'event', 'message']; +export const WEBHOOK_ID_FORMATS: readonly WebhookIdFormatSetting[] = ['auto', 'event-id', 'per-message']; export const EVENTS_EXTENSION = 'io.modelcontextprotocol/events'; const CLIENT_CAPABILITIES_META_KEY = 'io.modelcontextprotocol/clientCapabilities'; @@ -26,7 +27,7 @@ const CLIENT_INFO_META_KEY = 'io.modelcontextprotocol/clientInfo'; /** * Clients that reject a delivery whose `webhook-id` isn't its `eventId`, by their default name in - * `_meta["io.modelcontextprotocol/clientInfo"]`. They get `event` mode under `auto` even if they declare the events + * `_meta["io.modelcontextprotocol/clientInfo"]`. They get `event-id` under `auto` even if they declare the events * extension. Checked 13 Nov: * * tanstack-ai-mcp TanStack AI (`@tanstack/ai-mcp` 1.2.0) declares the extension whenever events are enabled @@ -36,7 +37,7 @@ const CLIENT_INFO_META_KEY = 'io.modelcontextprotocol/clientInfo'; * openclaw OpenClaw (v2026.11.3) declares nothing (`clientCapabilities: {}`); listed in case it starts. * * TanStack AI and the AI SDK let the application rename the client, which this list can't see: such a deployment sets - * BRIDGE_WEBHOOK_ID=event. Remove a client once a release that accepts a per-message id has shipped. + * BRIDGE_WEBHOOK_ID_FORMAT=event-id. Remove a client once a release that accepts a per-message id has shipped. */ export const LEGACY_WEBHOOK_ID_CLIENTS: readonly string[] = ['tanstack-ai-mcp', 'ai-sdk-mcp-client', 'openclaw']; @@ -57,14 +58,14 @@ export function clientName(meta: unknown): string | undefined { } /** - * The mode for a subscribe request. Under `auto`, a client that declares the events extension in the request's - * `_meta` gets `message`, unless it's on the legacy list; any other client gets `event`. + * The format for a subscribe request. Under `auto`, a client that declares the events extension in the request's + * `_meta` gets `per-message`, unless it's on the legacy list; any other client gets `event-id`. */ -export function chooseWebhookIdMode(setting: WebhookIdSetting, meta: unknown, legacyClients: readonly string[] = LEGACY_WEBHOOK_ID_CLIENTS): WebhookIdMode { +export function chooseWebhookIdFormat(setting: WebhookIdFormatSetting, meta: unknown, legacyClients: readonly string[] = LEGACY_WEBHOOK_ID_CLIENTS): WebhookIdFormat { if (setting !== 'auto') return setting; - if (!declaresEventsExtension(meta)) return 'event'; + if (!declaresEventsExtension(meta)) return 'event-id'; const name = clientName(meta); - return name !== undefined && legacyClients.includes(name) ? 'event' : 'message'; + return name !== undefined && legacyClients.includes(name) ? 'event-id' : 'per-message'; } /** A per-message `webhook-id`: `msg_` and 24 characters from [A-Za-z0-9_-] (18 random bytes). The transformation builds the same shape. */ @@ -72,7 +73,7 @@ export function messageId(): string { return `msg_${randomBytes(18).toString('base64url')}`; } -/** The `webhook-id` for one delivery of an event in a mode. */ -export function deliveryWebhookId(mode: WebhookIdMode, eventId: string): string { - return mode === 'message' ? messageId() : eventId; +/** The `webhook-id` for one delivery of an event in a format. */ +export function deliveryWebhookId(format: WebhookIdFormat, eventId: string): string { + return format === 'per-message' ? messageId() : eventId; } diff --git a/src/host/server.ts b/src/host/server.ts index 14c83c7..3d89603 100644 --- a/src/host/server.ts +++ b/src/host/server.ts @@ -156,7 +156,7 @@ export async function createBridgeServer(config: ResolvedConfig, options: Bridge publish: (subscription, envelope) => hookdeck.publish( REPLAY_SOURCE, - { 'content-type': 'application/json', 'webhook-id': deliveryWebhookId(subscription.webhookIdMode, envelope.eventId), 'x-mcp-subscription-id': subscription.id }, + { 'content-type': 'application/json', 'webhook-id': deliveryWebhookId(subscription.webhookIdFormat, envelope.eventId), 'x-mcp-subscription-id': subscription.id }, JSON.stringify(envelope), ), settled: async (connectionId, count, timeoutMs) => { diff --git a/test/core/callbacks.test.ts b/test/core/callbacks.test.ts index e49831a..296f7cc 100644 --- a/test/core/callbacks.test.ts +++ b/test/core/callbacks.test.ts @@ -43,7 +43,7 @@ const subscription = (over: Partial = {}): SubscriptionInput secret: SECRET, replay: null, delivery: healthyDelivery(), - webhookIdMode: 'event', + webhookIdFormat: 'event-id', expiresAt: '2026-11-05T00:00:00.000Z', createdAt: '2026-10-05T16:00:00.000Z', updatedAt: '2026-10-05T16:00:00.000Z', diff --git a/test/core/config.test.ts b/test/core/config.test.ts index d826ad0..81a69ce 100644 --- a/test/core/config.test.ts +++ b/test/core/config.test.ts @@ -79,12 +79,12 @@ describe('resolveConfig', () => { expect(() => resolveConfig(config(), { ...base, BRIDGE_MCP_SECRET_URL: 'no' })).toThrow(/BRIDGE_MCP_SECRET_URL must be true or false/); }); - it('chooses webhook-id per subscription (auto) unless BRIDGE_WEBHOOK_ID or subscriptions.webhookId says event or message', () => { - expect(resolveConfig(config(), base).subscriptions.webhookId).toBe('auto'); - expect(resolveConfig(config(), { ...base, BRIDGE_WEBHOOK_ID: 'event' }).subscriptions.webhookId).toBe('event'); - expect(resolveConfig(config(), { ...base, BRIDGE_WEBHOOK_ID: 'message' }).subscriptions.webhookId).toBe('message'); - expect(resolveConfig(config({ subscriptions: { webhookId: 'event' } }), { ...base, BRIDGE_WEBHOOK_ID: 'message' }).subscriptions.webhookId).toBe('event'); - expect(() => resolveConfig(config(), { ...base, BRIDGE_WEBHOOK_ID: 'sep' })).toThrow(/BRIDGE_WEBHOOK_ID \(subscriptions.webhookId\) must be auto, event, message/); + it('chooses webhook-id per subscription (auto) unless BRIDGE_WEBHOOK_ID_FORMAT or subscriptions.webhookIdFormat says event-id or per-message', () => { + expect(resolveConfig(config(), base).subscriptions.webhookIdFormat).toBe('auto'); + expect(resolveConfig(config(), { ...base, BRIDGE_WEBHOOK_ID_FORMAT: 'event-id' }).subscriptions.webhookIdFormat).toBe('event-id'); + expect(resolveConfig(config(), { ...base, BRIDGE_WEBHOOK_ID_FORMAT: 'per-message' }).subscriptions.webhookIdFormat).toBe('per-message'); + expect(resolveConfig(config({ subscriptions: { webhookIdFormat: 'event-id' } }), { ...base, BRIDGE_WEBHOOK_ID_FORMAT: 'per-message' }).subscriptions.webhookIdFormat).toBe('event-id'); + expect(() => resolveConfig(config(), { ...base, BRIDGE_WEBHOOK_ID_FORMAT: 'sep' })).toThrow(/BRIDGE_WEBHOOK_ID_FORMAT \(subscriptions.webhookIdFormat\) must be auto, event-id, per-message/); }); it('rejects a BRIDGE_MCP_SECRET that isn\'t URL-safe, such as a pasted line with a note after the value', () => { diff --git a/test/core/event-gateway-store.test.ts b/test/core/event-gateway-store.test.ts index 4ec2d9a..1d6183c 100644 --- a/test/core/event-gateway-store.test.ts +++ b/test/core/event-gateway-store.test.ts @@ -17,7 +17,7 @@ const input = (over: Partial = {}): SubscriptionInput => ({ secret: SECRET, replay: null, delivery: healthyDelivery(), - webhookIdMode: 'event', + webhookIdFormat: 'event-id', expiresAt: '2026-11-05T12:00:00.000Z', createdAt: '2026-10-05T12:00:00.000Z', updatedAt: '2026-10-05T12:00:00.000Z', @@ -91,16 +91,16 @@ describe('EventGatewayStore', () => { it('marks a per-message webhook-id with wid in the description, reads it back on load, and drops it when a refresh switches to the eventId', async () => { const { gateway, hookdeck, place, store } = await setup(); - const record = await store.put(input({ webhookIdMode: 'message' })); + const record = await store.put(input({ webhookIdFormat: 'per-message' })); expect(JSON.parse(gateway.connections.get(record.connectionId)!.description!).wid).toBe('msg'); const fresh = new EventGatewayStore(hookdeck, place); await fresh.load(); - expect(fresh.get(record.id)?.webhookIdMode).toBe('message'); - await store.update(record.id, (current) => ({ ...current!, webhookIdMode: 'event' })); + expect(fresh.get(record.id)?.webhookIdFormat).toBe('per-message'); + await store.update(record.id, (current) => ({ ...current!, webhookIdFormat: 'event-id' })); expect(JSON.parse(gateway.connections.get(record.connectionId)!.description!).wid).toBeUndefined(); const again = new EventGatewayStore(hookdeck, place); await again.load(); - expect(again.get(record.id)?.webhookIdMode).toBe('event'); + expect(again.get(record.id)?.webhookIdFormat).toBe('event-id'); }); it('rebuilds the same records on load, reading each secret from destination auth', async () => { diff --git a/test/core/notifications.test.ts b/test/core/notifications.test.ts index 14564ba..38d4286 100644 --- a/test/core/notifications.test.ts +++ b/test/core/notifications.test.ts @@ -37,7 +37,7 @@ const subscription = (over: Partial = {}): SubscriptionInput secret: generateWebhookSecret(), replay: null, delivery: healthyDelivery(), - webhookIdMode: 'event', + webhookIdFormat: 'event-id', expiresAt: '2026-11-05T00:00:00.000Z', createdAt: '2026-10-05T16:00:00.000Z', updatedAt: '2026-10-05T16:00:00.000Z', diff --git a/test/core/store-concurrency.test.ts b/test/core/store-concurrency.test.ts index f69285f..1e5299d 100644 --- a/test/core/store-concurrency.test.ts +++ b/test/core/store-concurrency.test.ts @@ -143,7 +143,7 @@ function input(id: string, from = ''): SubscriptionInput { secret: generateWebhookSecret(), replay: null, delivery: healthyDelivery(), - webhookIdMode: 'event', + webhookIdFormat: 'event-id', expiresAt: '2026-11-04T12:00:00.000Z', createdAt: '2026-10-05T12:00:00.000Z', updatedAt: '2026-10-05T12:00:00.000Z', diff --git a/test/core/webhook-id.test.ts b/test/core/webhook-id.test.ts index fd59fea..f6f45f2 100644 --- a/test/core/webhook-id.test.ts +++ b/test/core/webhook-id.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { chooseWebhookIdMode, clientName, declaresEventsExtension, deliveryWebhookId, LEGACY_WEBHOOK_ID_CLIENTS, messageId } from '../../src/core/webhook-id.js'; +import { chooseWebhookIdFormat, clientName, declaresEventsExtension, deliveryWebhookId, LEGACY_WEBHOOK_ID_CLIENTS, messageId } from '../../src/core/webhook-id.js'; /** A request's `_meta` as a 2026-07-28 client sends it. */ const meta = (options: { events?: boolean; name?: string } = {}) => ({ @@ -8,7 +8,7 @@ const meta = (options: { events?: boolean; name?: string } = {}) => ({ ...(options.name !== undefined && { 'io.modelcontextprotocol/clientInfo': { name: options.name, version: '1.0.0' } }), }); -describe('webhook-id mode', () => { +describe('webhook-id format', () => { it('reads the events extension declaration and the client name from _meta', () => { expect(declaresEventsExtension(meta({ events: true }))).toBe(true); expect(declaresEventsExtension(meta())).toBe(false); @@ -19,29 +19,29 @@ describe('webhook-id mode', () => { }); it('under auto, gives a per-message id to a client that declares the extension, and the eventId to one that does not', () => { - expect(chooseWebhookIdMode('auto', meta({ events: true, name: 'some-sep-client' }))).toBe('message'); - expect(chooseWebhookIdMode('auto', meta({ events: true }))).toBe('message'); - expect(chooseWebhookIdMode('auto', meta({ name: 'openclaw' }))).toBe('event'); - expect(chooseWebhookIdMode('auto', undefined)).toBe('event'); + expect(chooseWebhookIdFormat('auto', meta({ events: true, name: 'some-sep-client' }))).toBe('per-message'); + expect(chooseWebhookIdFormat('auto', meta({ events: true }))).toBe('per-message'); + expect(chooseWebhookIdFormat('auto', meta({ name: 'openclaw' }))).toBe('event-id'); + expect(chooseWebhookIdFormat('auto', undefined)).toBe('event-id'); }); it('under auto, keeps the eventId for a declaring client on the legacy list (TanStack AI declares it, and rejects a per-message id)', () => { expect(LEGACY_WEBHOOK_ID_CLIENTS).toEqual(expect.arrayContaining(['tanstack-ai-mcp', 'ai-sdk-mcp-client', 'openclaw'])); - for (const name of LEGACY_WEBHOOK_ID_CLIENTS) expect(chooseWebhookIdMode('auto', meta({ events: true, name }))).toBe('event'); - expect(chooseWebhookIdMode('auto', meta({ events: true, name: 'x' }), ['x'])).toBe('event'); + for (const name of LEGACY_WEBHOOK_ID_CLIENTS) expect(chooseWebhookIdFormat('auto', meta({ events: true, name }))).toBe('event-id'); + expect(chooseWebhookIdFormat('auto', meta({ events: true, name: 'x' }), ['x'])).toBe('event-id'); }); - it('applies event or message to every subscription when the operator sets it', () => { - expect(chooseWebhookIdMode('event', meta({ events: true, name: 'some-sep-client' }))).toBe('event'); - expect(chooseWebhookIdMode('message', meta({ name: 'tanstack-ai-mcp' }))).toBe('message'); - expect(chooseWebhookIdMode('message', undefined)).toBe('message'); + it('applies event-id or per-message to every subscription when the operator sets it', () => { + expect(chooseWebhookIdFormat('event-id', meta({ events: true, name: 'some-sep-client' }))).toBe('event-id'); + expect(chooseWebhookIdFormat('per-message', meta({ name: 'tanstack-ai-mcp' }))).toBe('per-message'); + expect(chooseWebhookIdFormat('per-message', undefined)).toBe('per-message'); }); it('generates header-safe per-message ids, never the eventId', () => { const ids = new Set(Array.from({ length: 100 }, () => messageId())); expect(ids.size).toBe(100); for (const id of ids) expect(id).toMatch(/^msg_[A-Za-z0-9_-]{24}$/); - expect(deliveryWebhookId('event', 'evt_1')).toBe('evt_1'); - expect(deliveryWebhookId('message', 'evt_1')).toMatch(/^msg_/); + expect(deliveryWebhookId('event-id', 'evt_1')).toBe('evt_1'); + expect(deliveryWebhookId('per-message', 'evt_1')).toMatch(/^msg_/); }); }); diff --git a/test/host/bridge.test.ts b/test/host/bridge.test.ts index 81a7c7c..5494952 100644 --- a/test/host/bridge.test.ts +++ b/test/host/bridge.test.ts @@ -175,7 +175,7 @@ describe('bridge server', () => { const webhookIds: string[] = []; const subscriber = await startSubscriber(port, {}, { declareEvents: true, clientName: 'some-sep-client', onEvent: (_event, headers) => webhookIds.push(String(headers['webhook-id'])) }); const record = bridge.store.get(subscriber.subscription!.id)!; - expect(record.webhookIdMode).toBe('message'); + expect(record.webhookIdFormat).toBe('per-message'); expect(logs).toContain(`${record.id}: webhook-id per message (client "some-sep-client" declares io.modelcontextprotocol/events)`); await deliverFromSource(gateway, subscriber, resendDelivery()); @@ -196,7 +196,7 @@ describe('bridge server', () => { const webhookIds: string[] = []; const subscriber = await startSubscriber(port, { from }, { ...options, onEvent: (_event, headers) => webhookIds.push(String(headers['webhook-id'])) }); const record = bridge.store.get(subscriber.subscription!.id)!; - expect(record.webhookIdMode).toBe('event'); + expect(record.webhookIdFormat).toBe('event-id'); expect(logs).toContain(`${record.id}: webhook-id is the eventId (${reason})`); const email = freshEmail(); await deliverFromSource(gateway, subscriber, { headers: fixture.headers, body: { ...email, data: { ...(email.data as object), from } } }); @@ -264,7 +264,7 @@ describe('bridge server', () => { const store = new MemoryStore(); await store.put({ id: 'sub_old', principal: 'owner', name: 'email.received', arguments: {}, url: 'https://receiver.example.com/hook', - secret: generateWebhookSecret(), replay: null, delivery: healthyDelivery(), webhookIdMode: 'event', + secret: generateWebhookSecret(), replay: null, delivery: healthyDelivery(), webhookIdFormat: 'event-id', expiresAt: '2099-01-01T00:00:00.000Z', createdAt: '2026-10-01T00:00:00.000Z', updatedAt: '2026-10-01T00:00:00.000Z', }); const { logs } = await startBridge({ store }); From 7de61d445ff4cfb992d24573559247260d3c63ba Mon Sep 17 00:00:00 2001 From: Phil Leggetter Date: Fri, 13 Nov 2026 18:35:35 +0000 Subject: [PATCH 4/4] fix: address review of the per-message webhook-id - The description size check counts wid only for a per-message subscription, so an event-id subscription keeps the room it had. - The subscribe log says when the legacy client list chose event-id, and names both places the format setting can come from. - BRIDGE_WEBHOOK_ID_FORMAT values are read in any case. - Tests: a refresh switching format, the size limit with wid, migration giving event-id, and the operator setting in the log. Refs #113 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- docs/ARCHITECTURE.md | 4 ++-- src/core/config.ts | 3 ++- src/core/event-gateway-store.ts | 6 +++--- src/core/subscriptions.ts | 13 +++++++----- test/core/config.test.ts | 1 + test/core/event-gateway-store.test.ts | 15 ++++++++++++++ test/core/migrate.test.ts | 2 ++ test/host/bridge.test.ts | 29 +++++++++++++++++++++++++-- 9 files changed, 61 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 03bd358..3ebbd8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Added -- **A per-message `webhook-id` for clients that follow SEP-3415:** a webhook delivery's `webhook-id` was always the event's `eventId`. SEP-3415 now requires a per-message id, unique to one event on one subscription and never derived from `eventId`, so a receiver that dedupes on `webhook-id` doesn't drop an event that matches two of its subscriptions. A client that declares the events extension in a request's `_meta` (`io.modelcontextprotocol/clientCapabilities`) now gets `msg_` and 24 random characters, the same on every retry. Every other client still gets the `eventId`, as do TanStack AI, the Vercel AI SDK and OpenClaw by their default client names, since they reject a delivery whose `webhook-id` isn't its `eventId` (TanStack AI declares the extension). `BRIDGE_WEBHOOK_ID_FORMAT` (`subscriptions.webhookIdFormat`) is `auto` by default; `event-id` or `per-message` applies to every subscription. A subscription's format is chosen when it's made or refreshed, and `serve` logs it: `: webhook-id per message (client "" declares io.modelcontextprotocol/events)` or `: webhook-id is the eventId (...)`. With a per-message id, an event whose id contains a period is delivered rather than skipped ([#113](https://github.com/hookdeck/mcp-events-bridge/issues/113)). +- **A per-message `webhook-id` for clients that follow SEP-3415:** a webhook delivery's `webhook-id` was always the event's `eventId`. SEP-3415 now requires a per-message id, unique to one event on one subscription and never derived from `eventId`, so a receiver that dedupes on `webhook-id` doesn't drop an event that matches two of its subscriptions. A client that declares the events extension in a request's `_meta` (`io.modelcontextprotocol/clientCapabilities`) now gets `msg_` and 24 random characters, the same on every retry. Every other client still gets the `eventId`, as do TanStack AI, the Vercel AI SDK and OpenClaw by their default client names, since they reject a delivery whose `webhook-id` isn't its `eventId` (TanStack AI declares the extension). `BRIDGE_WEBHOOK_ID_FORMAT` (`subscriptions.webhookIdFormat`) is `auto` by default; `event-id` or `per-message` applies to every subscription. A subscription's format is chosen when it's made or refreshed, and `serve` logs it: `: webhook-id per message (client "" declares io.modelcontextprotocol/events)` or `: webhook-id is the eventId (...)`, giving the reason: what the client declares, the legacy client list, or the setting. With a per-message id, an event whose id contains a period is delivered rather than skipped ([#113](https://github.com/hookdeck/mcp-events-bridge/issues/113)). ### Changed diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f328e16..c0894ee 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -99,9 +99,9 @@ description: {"v":2, principal, event, arguments, expiresAt, createdAt, updatedA ``` - **The transformation** (`src/core/transformation.ts`) is generated from the source's runtime (see "Source definitions"), and written by `setup` and again when `serve` starts, so it matches the running bridge's version and config. It builds the envelope `{ eventId, name, timestamp, data, cursor }`, sets `webhook-id` (see "Which `webhook-id`") and `X-MCP-Subscription-Id` from the connection's name (`context.connection.name`), and clears the sender's query string (the destination doesn't forward the sender's path either). One transformation serves every subscription on the source: it runs for each subscription's connection, before the filter, so each gets its own subscription id (verified). -- **Which `webhook-id`** ([#113](https://github.com/hookdeck/mcp-events-bridge/issues/113), `src/core/webhook-id.ts`). Each subscription has a `webhook-id` format, chosen at every subscribe (so a refresh can change it) and kept in the description as `wid`. **`event-id`** (no `wid`): `webhook-id` is the `eventId`, for the clients that reject anything else. **`per-message`** (`"wid":"msg"`): `msg_` and 24 random characters (`crypto.getRandomValues` in the transformation), as SEP-3415 requires. Event Gateway runs the transformation once per event, and automatic and manual retries reuse its headers, so the id stays the same across attempts (verified 13 Nov). The operator setting `BRIDGE_WEBHOOK_ID_FORMAT` (`subscriptions.webhookIdFormat`) is `auto` by default: `per-message` for a client that declares `io.modelcontextprotocol/events` in the request's `_meta` (`io.modelcontextprotocol/clientCapabilities`, which the MCP SDK lifts into `ctx.mcpReq.envelope`), unless its `clientInfo` name is on the legacy list; `event-id` otherwise. `event-id` or `per-message` applies to every subscription. The legacy list holds the default names of the clients that reject a per-message id: `tanstack-ai-mcp` (declares the extension whenever events are on), `ai-sdk-mcp-client` (only if the application passes it) and `openclaw` (declares nothing today). An application that renames its client isn't caught; that deployment sets `BRIDGE_WEBHOOK_ID_FORMAT=event-id`. +- **Which `webhook-id`** ([#113](https://github.com/hookdeck/mcp-events-bridge/issues/113), `src/core/webhook-id.ts`). Each subscription has a `webhook-id` format, chosen at every subscribe (so a refresh can change it) and kept in the description as `wid`. **`event-id`** (no `wid`): `webhook-id` is the `eventId`, for the clients that reject anything else. **`per-message`** (`"wid":"msg"`): `msg_` and 24 random characters (`crypto.getRandomValues` in the transformation), as SEP-3415 requires. Event Gateway runs the transformation once per event, and automatic and manual retries reuse its headers, so the id stays the same across attempts (verified 13 Nov). The operator setting `BRIDGE_WEBHOOK_ID_FORMAT` (`subscriptions.webhookIdFormat`) is `auto` by default: `per-message` for a client that declares `io.modelcontextprotocol/events` in the request's `_meta` (`io.modelcontextprotocol/clientCapabilities`, which the MCP SDK lifts into `ctx.mcpReq.envelope`), unless its `clientInfo` name is on the legacy list; `event-id` otherwise. `event-id` or `per-message` applies to every subscription. The legacy list holds the default names of the clients that reject a per-message id: `tanstack-ai-mcp` (declares the extension whenever events are on), `ai-sdk-mcp-client` (only if the application passes it) and `openclaw` (declares nothing today). An application that renames its client isn't caught; that deployment sets `BRIDGE_WEBHOOK_ID_FORMAT=event-id`. Only the per-request `_meta` is read: the bridge is stateless, so a client that declares the extension only in `initialize` gets `event-id`. Two clients with the same principal, callback URL, event and arguments share one subscription, and whichever refreshes last sets its format. `serve` logs each subscription's format and why: what the client declares, the legacy list, or the operator setting. - **Dedupe** is on `body.eventId`, not `webhook-id`: a service resending an event runs the transformation again, which with `per-message` gives a new id. Both are the same with `event-id`. Dedupe on a field the transformation sets works (verified 13 Nov). -- **The cursor** is poll's format (see "Poll mode"), built in the transformation from the connection's description: `ca`, the hash of the subscription's arguments, and the time it runs less the look-back. While a replay runs, the description includes `rp`, where the replay started, and every delivery's cursor starts there instead, so a client that saves the latest cursor never skips past events the replay hasn't sent yet (see "Webhook cursors and replay"). The keys are short because the description holds at most 500 characters, with room left for a delivery failure, a replay marker and `wid`. +- **The cursor** is poll's format (see "Poll mode"), built in the transformation from the connection's description: `ca`, the hash of the subscription's arguments, and the time it runs less the look-back. While a replay runs, the description includes `rp`, where the replay started, and every delivery's cursor starts there instead, so a client that saves the latest cursor never skips past events the replay hasn't sent yet (see "Webhook cursors and replay"). The keys are short because the description holds at most 500 characters, with room left for a delivery failure and a replay marker. `wid` is counted only for a per-message subscription, since only a subscribe sets it, so an `event-id` subscription has the room it had before. - **The filter** holds the event name and the subscription's arguments: each event's `filter(args)` (`src/core/filter.ts`), matched against the normalized fields the transformation produces, since Event Gateway's matching is case-sensitive and type-strict. The sources' filters use equality, arrays that contain values (Resend's `to`) and `$or` (GitHub's `actions`), which is lifted to the top of the filter's body (verified). The bridge applies the same filter itself in poll mode. A subscription option that poll can't apply the same way isn't offered ("Decisions", 29 Oct). - **Skipped events.** The transformation adds an `x-mcp-skip` header to anything that can't be delivered, and every filter requires it to be absent: an event type the source doesn't offer, a request it can't build an event from, an event id containing a period with `event-id` (Standard Webhooks ids can't have one, and Event Gateway fails such an attempt with `DESTINATION_AUTH_FAILED`; a per-message id never has one), and an envelope over 256 KiB. They're recorded as `FILTERED` (verified). A thrown transformation error would instead open an issue for every subscription on every request. - **The destination** signs each attempt with `webhook-id`, a fresh `webhook-timestamp`, and a `webhook-signature` over the exact body (verified, including manual retries and request retries). That closes the retry gap (conformance row 56), and subscription retries no longer have to fit inside 5 minutes. diff --git a/src/core/config.ts b/src/core/config.ts index 7d6c42f..3411713 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -153,7 +153,8 @@ function parseBoolean(name: string, value: string | undefined, fallback: boolean function parseWebhookIdFormat(value: string | undefined): WebhookIdFormatSetting { if (value === undefined || value === '') return DEFAULT_SUBSCRIPTION_SETTINGS.webhookIdFormat; - if ((WEBHOOK_ID_FORMATS as readonly string[]).includes(value)) return value as WebhookIdFormatSetting; + const lower = value.toLowerCase(); + if ((WEBHOOK_ID_FORMATS as readonly string[]).includes(lower)) return lower as WebhookIdFormatSetting; throw new ConfigError(`BRIDGE_WEBHOOK_ID_FORMAT (subscriptions.webhookIdFormat) must be ${WEBHOOK_ID_FORMATS.join(', ')}`); } diff --git a/src/core/event-gateway-store.ts b/src/core/event-gateway-store.ts index 0f80477..f06de17 100644 --- a/src/core/event-gateway-store.ts +++ b/src/core/event-gateway-store.ts @@ -163,13 +163,13 @@ export class EventGatewayStore implements SubscriptionStore { ...(input.webhookIdFormat === 'per-message' && { wid: 'msg' as const }), }; const description = JSON.stringify(metadata); - // Checked with the largest delivery block a failure notification can add later, a replay marker and the - // per-message marker, so none of them can overflow it, and a refresh can switch the mode. + // Checked with the largest delivery block a failure notification can add later and a replay marker, so neither + // can overflow it. `wid` is counted only when this write sets it: only a subscribe changes the format, and it runs + // this check, so an event-id subscription keeps the room it had before per-message ids existed. const worstCase = JSON.stringify({ ...metadata, delivery: { active: false, lastError: 'connection_refused', failedSince: input.updatedAt }, rp: { f: 9_999_999_999_999, w: 9_999_999_999_999 }, - wid: 'msg', }); if (worstCase.length > DESCRIPTION_LIMIT) throw new SubscriptionTooLargeError('Subscription arguments are too large to store'); diff --git a/src/core/subscriptions.ts b/src/core/subscriptions.ts index 858e924..614954e 100644 --- a/src/core/subscriptions.ts +++ b/src/core/subscriptions.ts @@ -6,7 +6,7 @@ import { deriveSubscriptionId, verificationKey } from './identity.js'; import { isValidWebhookSecret } from './secret.js'; import type { CallbackRegistry } from './callbacks.js'; import { SubscriptionTooLargeError, healthyDelivery, type CursorPosition, type SubscriptionRecord, type SubscriptionStore } from './store.js'; -import { chooseWebhookIdFormat, clientName, declaresEventsExtension } from './webhook-id.js'; +import { chooseWebhookIdFormat, clientName, declaresEventsExtension, type WebhookIdFormat } from './webhook-id.js'; /* * MCP Events webhook subscriptions: subscribe (and refresh), unsubscribe, @@ -81,11 +81,14 @@ export function describeParams(params: Params): string { } /** Why a subscription got its webhook-id format, for the log. */ -function describeClient(setting: SubscriptionSettings['webhookIdFormat'], meta: unknown): string { - if (setting !== 'auto') return `BRIDGE_WEBHOOK_ID_FORMAT=${setting}`; +function describeClient(setting: SubscriptionSettings['webhookIdFormat'], format: WebhookIdFormat, meta: unknown): string { + if (setting !== 'auto') return `set to ${setting} by BRIDGE_WEBHOOK_ID_FORMAT or subscriptions.webhookIdFormat`; const name = clientName(meta); const client = name === undefined ? 'the client' : `client ${JSON.stringify(name.slice(0, 60))}`; - return `${client} ${declaresEventsExtension(meta) ? 'declares' : "doesn't declare"} io.modelcontextprotocol/events`; + if (!declaresEventsExtension(meta)) return `${client} doesn't declare io.modelcontextprotocol/events`; + return format === 'event-id' + ? `${client} declares io.modelcontextprotocol/events, but is on the legacy client list` + : `${client} declares io.modelcontextprotocol/events`; } /** A callback URL for logs: the query string can include a token, so it's replaced. */ @@ -222,7 +225,7 @@ export class SubscriptionService { const existing = prior.record; if (existing && existing.secret !== secret) this.log(`rotated secret for ${id}`); this.log(`${existing ? 'refreshed' : 'subscribed'} ${id} until ${expiresAt.toISOString()}`); - this.log(`${id}: webhook-id ${webhookIdFormat === 'per-message' ? 'per message' : 'is the eventId'} (${describeClient(settings.webhookIdFormat, request.meta)})`); + this.log(`${id}: webhook-id ${webhookIdFormat === 'per-message' ? 'per message' : 'is the eventId'} (${describeClient(settings.webhookIdFormat, webhookIdFormat, request.meta)})`); return { id, diff --git a/test/core/config.test.ts b/test/core/config.test.ts index 81a69ce..383e11d 100644 --- a/test/core/config.test.ts +++ b/test/core/config.test.ts @@ -83,6 +83,7 @@ describe('resolveConfig', () => { expect(resolveConfig(config(), base).subscriptions.webhookIdFormat).toBe('auto'); expect(resolveConfig(config(), { ...base, BRIDGE_WEBHOOK_ID_FORMAT: 'event-id' }).subscriptions.webhookIdFormat).toBe('event-id'); expect(resolveConfig(config(), { ...base, BRIDGE_WEBHOOK_ID_FORMAT: 'per-message' }).subscriptions.webhookIdFormat).toBe('per-message'); + expect(resolveConfig(config(), { ...base, BRIDGE_WEBHOOK_ID_FORMAT: 'Event-ID' }).subscriptions.webhookIdFormat).toBe('event-id'); expect(resolveConfig(config({ subscriptions: { webhookIdFormat: 'event-id' } }), { ...base, BRIDGE_WEBHOOK_ID_FORMAT: 'per-message' }).subscriptions.webhookIdFormat).toBe('event-id'); expect(() => resolveConfig(config(), { ...base, BRIDGE_WEBHOOK_ID_FORMAT: 'sep' })).toThrow(/BRIDGE_WEBHOOK_ID_FORMAT \(subscriptions.webhookIdFormat\) must be auto, event-id, per-message/); }); diff --git a/test/core/event-gateway-store.test.ts b/test/core/event-gateway-store.test.ts index 1d6183c..6164130 100644 --- a/test/core/event-gateway-store.test.ts +++ b/test/core/event-gateway-store.test.ts @@ -189,6 +189,21 @@ describe('EventGatewayStore', () => { expect(gateway.connections.size).toBe(1); }); + it('keeps the room an event-id subscription had before per-message ids, and counts wid only for a per-message one', async () => { + const { store } = await setup(); + // The largest `from` an event-id subscription takes, as before #113; a per-message one is 12 characters shorter. + let size = 0; + for (let n = 1; n < 400; n++) { + const fits = await store.put(input({ id: `sub_${String(n).padStart(32, '0')}`, arguments: { from: 'x'.repeat(n) } })).then(() => true, () => false); + if (!fits) break; + size = n; + } + expect(size).toBeGreaterThan(0); + await expect(store.put(input({ id: 'sub_e', arguments: { from: 'x'.repeat(size) } }))).resolves.toBeDefined(); + await expect(store.put(input({ id: 'sub_m', arguments: { from: 'x'.repeat(size) }, webhookIdFormat: 'per-message' }))).rejects.toBeInstanceOf(SubscriptionTooLargeError); + await expect(store.put(input({ id: 'sub_n', arguments: { from: 'x'.repeat(size - 12) }, webhookIdFormat: 'per-message' }))).resolves.toBeDefined(); + }); + it('deletes the connection and destination, and leaves the service source', async () => { const { gateway, source, store } = await setup(); const a = await store.put(input()); diff --git a/test/core/migrate.test.ts b/test/core/migrate.test.ts index 332e678..f25cce9 100644 --- a/test/core/migrate.test.ts +++ b/test/core/migrate.test.ts @@ -71,6 +71,8 @@ describe('migrating from 0.7', () => { secret: subscriber, expiresAt: '2026-11-05T00:00:00.000Z', createdAt: '2026-10-20T00:00:00.000Z', + // 0.7 sent the eventId as webhook-id; the client's next refresh picks the format. + webhookIdFormat: 'event-id', }); const resendSource = [...gateway.sources.values()].find((s) => s.name === 'bridge-resend')!; expect(store.get('sub_live')!.sourceId).toBe(resendSource.id); diff --git a/test/host/bridge.test.ts b/test/host/bridge.test.ts index 5494952..285e1a1 100644 --- a/test/host/bridge.test.ts +++ b/test/host/bridge.test.ts @@ -43,7 +43,8 @@ async function startBridge({ store, pollNow, secretUrl, -}: { inbound?: 'cli' | 'http'; store?: MemoryStore; pollNow?: () => number; secretUrl?: 'true' | 'false' } = {}) { + webhookIdFormat, +}: { inbound?: 'cli' | 'http'; store?: MemoryStore; pollNow?: () => number; secretUrl?: 'true' | 'false'; webhookIdFormat?: string } = {}) { const gateway = new FakeEventGateway(); // What setup creates: the service's source, which subscriptions are connections on. gateway.sources.set('src_resend', { id: 'src_resend', name: 'bridge-resend', type: 'RESEND', url: 'https://hkdk.events/src_resend' }); @@ -52,6 +53,7 @@ async function startBridge({ HOOKDECK_SIGNING_SECRET: SIGNING_SECRET, BRIDGE_MCP_SECRET: MCP_SECRET, ...(secretUrl && { BRIDGE_MCP_SECRET_URL: secretUrl }), + ...(webhookIdFormat && { BRIDGE_WEBHOOK_ID_FORMAT: webhookIdFormat }), }); const logs: string[] = []; const bridge = await createBridgeServer(config, { @@ -190,7 +192,7 @@ describe('bridge server', () => { const { gateway, port, bridge, logs } = await startBridge(); const cases = [ { from: 'a@example.com', options: {}, reason: `client "mcp-events-test-subscriber" doesn't declare io.modelcontextprotocol/events` }, - { from: 'b@example.com', options: { declareEvents: true, clientName: 'tanstack-ai-mcp' }, reason: 'client "tanstack-ai-mcp" declares io.modelcontextprotocol/events' }, + { from: 'b@example.com', options: { declareEvents: true, clientName: 'tanstack-ai-mcp' }, reason: 'client "tanstack-ai-mcp" declares io.modelcontextprotocol/events, but is on the legacy client list' }, ]; for (const { from, options, reason } of cases) { const webhookIds: string[] = []; @@ -204,6 +206,29 @@ describe('bridge server', () => { } }); + it("switches a subscription's webhook-id format when a refresh comes from a client that declares differently, with dedupe on eventId either way", async () => { + const { gateway, port, bridge } = await startBridge(); + const connectionOf = (id: string) => [...gateway.connections.values()].find((c) => c.name === `mcp-sub-${id}`)!; + const sep = await startSubscriber(port, { from: 'a@example.com' }, { declareEvents: true, clientName: 'some-sep-client' }); + const id = sep.subscription!.id; + expect(JSON.parse(connectionOf(id).description!).wid).toBe('msg'); + expect(connectionOf(id).rules).toContainEqual(expect.objectContaining({ type: 'deduplicate', include_fields: ['body.eventId'] })); + + // Same principal, URL, event and arguments: the same subscription, refreshed by a client that declares nothing. + const legacy = await startSubscriber(port, { from: 'a@example.com' }); + expect(legacy.subscription!.id).toBe(id); + expect(bridge.store.get(id)!.webhookIdFormat).toBe('event-id'); + expect(JSON.parse(connectionOf(id).description!).wid).toBeUndefined(); + expect(connectionOf(id).rules).toContainEqual(expect.objectContaining({ type: 'deduplicate', include_fields: ['body.eventId'] })); + }); + + it('logs a format set by the operator as the setting, not as something the client declared', async () => { + const { port, bridge, logs } = await startBridge({ webhookIdFormat: 'per-message' }); + const subscriber = await startSubscriber(port, {}, { clientName: 'tanstack-ai-mcp' }); + expect(bridge.store.get(subscriber.subscription!.id)!.webhookIdFormat).toBe('per-message'); + expect(logs).toContain(`${subscriber.subscription!.id}: webhook-id per message (set to per-message by BRIDGE_WEBHOOK_ID_FORMAT or subscriptions.webhookIdFormat)`); + }); + it('lists sources with their event types, as events/list describes them, and how many webhook subscriptions each has', async () => { const { port } = await startBridge(); await startSubscriber(port);