diff --git a/docs/mcp-event-webhooks.md b/docs/mcp-event-webhooks.md index 5fadb6a0..d04d6319 100644 --- a/docs/mcp-event-webhooks.md +++ b/docs/mcp-event-webhooks.md @@ -1,6 +1,12 @@ # MCP Event webhooks -Factorize exposes Event definitions over the authenticated `/mcp` endpoint. A definition's protocol name is `factorize.event.`. The catalog uses the current name and description. Subscriptions use the connected OAuth grant, require `triggers:read`, and receive newly recorded occurrences after activation. The webhook contains `occurrenceId` and `definitionId`. Use `read_event_occurrences` for the committed payload and its definition revision. +Factorize exposes one stable MCP Events type, `factorize.occurrence`, over the authenticated `/mcp` endpoint. Its required `event_id` argument is the UUID from `create_event` or `list_events`, not a name or a catalog enum. Create an Event and use its UUID immediately; creating or renaming Event definitions never changes the MCP catalog. Subscriptions use the connected OAuth grant, require `triggers:read` in the definition's tenant, and receive only newly recorded occurrences for that definition. + +Use `events/subscribe` with `name: "factorize.occurrence"`, `arguments: { "event_id": "" }` and the client's verified webhook delivery configuration. Repeat the same name, arguments and callback URL to refresh or unsubscribe. An occurrence can be delivered to several distinct matching subscriptions. All carry `name: "factorize.occurrence"` and the same `occurrenceId` and `definitionId` in `data`; subscription IDs are distinct. Use `read_event_occurrences` for the committed payload and its definition revision. + +## One-time rollout + +After the updated server is deployed, refresh the installed MCP plugin's metadata once and verify it exposes `factorize.occurrence` with the UUID argument. No further refresh is needed to subscribe to a newly created Factorize Event. Keep existing subscriptions in place: legacy `factorize.event.` subscriptions keep their original signed envelope name and may renew or unsubscribe with their original empty arguments. The new catalog does not list those names. If migrating a client, confirm the new subscription receives the intended definition before stopping the old one, and deduplicate overlapping deliveries by occurrence ID. ## Webhook egress diff --git a/packages/api/src/api-service.ts b/packages/api/src/api-service.ts index 396e4296..3d7a1cfa 100644 --- a/packages/api/src/api-service.ts +++ b/packages/api/src/api-service.ts @@ -1,6 +1,6 @@ import { initialIntegrationOverrides, lockOAuthPolicy } from "./oauth-reconnect"; import { lockMcpEventGrant } from "./postgres/mcp-event-outbox"; -import { eventPayloadSchema, eventProtocolName, type ReadEventOccurrencesInput, type subscribeEventInput, type unsubscribeEventInput } from "./mcp-event-contracts"; +import { eventPayloadSchema, occurrenceEventName, occurrenceInputSchema, type ReadEventOccurrencesInput, type subscribeEventInput, type unsubscribeEventInput } from "./mcp-event-contracts"; import { subscribeMcpEvent, unsubscribeMcpEvent } from "./mcp-event-subscriptions"; import { vmGrantInput, vmGrantList, vmGrantResult, vmRevokeResult } from "./vm-grant-contracts"; import { VmGrantRepository, vmGrantActor, type VmGrant } from "./postgres/vm-grant-repository"; @@ -207,19 +207,17 @@ export class ApiService { async updateEvent(id: string, input: unknown) { await this.authorize("triggers:write"); const parsed = eventDefinitionUpdate.parse(input); try { const result = await this.eventDefinitions().update(id, parsed, parsed.expectedRevision); if (!result) throw new ServiceError(404, "not_found", "Event not found"); return publicValue(eventDefinitionResponse, result); } catch (error) { if (error instanceof EventDefinitionConflict) throw new ServiceError(409, "stale_event", "Event changed since it was loaded."); throw error; } } async deleteEvent(id: string) { await this.authorize("triggers:write"); if (!await this.eventDefinitions().delete(id)) throw new ServiceError(404, "not_found", "Event not found"); return { id, deleted: true as const }; } async listEventOccurrences(id: string, limit: number, cursor?: string) { await this.authorize("triggers:read"); const result = await this.eventDefinitions().occurrences(id, limit, cursor); if (!result) throw new ServiceError(404, "not_found", "Event not found"); return publicValue(eventOccurrencePage, result); } - async mcpEventCatalog(cursor?: string) { + async mcpEventCatalog() { await this.authorize("triggers:read"); - const page = await this.eventDefinitions().mcpCatalog(cursor); return { - events: page.events.map(event => ({ - name: eventProtocolName(event.id), - title: event.name, - description: event.description, + events: [{ + name: occurrenceEventName, + title: "Factorize occurrence", + description: "A new occurrence for the selected Factorize Event. Use its UUID as event_id.", delivery: ["webhook"], - inputSchema: { type: "object", properties: {}, additionalProperties: false }, + inputSchema: occurrenceInputSchema, payloadSchema: eventPayloadSchema, - })), - nextCursor: page.nextCursor, + }], }; } async mcpSubscribeEvent(input: z.infer) { diff --git a/packages/api/src/mcp-event-contracts.ts b/packages/api/src/mcp-event-contracts.ts index 92bd326c..e0c136b9 100644 --- a/packages/api/src/mcp-event-contracts.ts +++ b/packages/api/src/mcp-event-contracts.ts @@ -1,25 +1,48 @@ import { z } from "zod"; const meta = z.record(z.string(), z.unknown()).optional(); -const eventName = z.templateLiteral(["factorize.event.", z.uuid()]).refine(name => name === name.toLowerCase()); -export const eventProtocolName = (definitionId: string) => `factorize.event.${definitionId}`; -export const eventDefinitionId = (name: string) => name.slice("factorize.event.".length); - -const argumentsSchema = z.strictObject({}); +export const occurrenceEventName = "factorize.occurrence"; +const legacyPrefix = "factorize.event."; +const legacyName = z.templateLiteral([legacyPrefix, z.uuid()]).refine(name => name === name.toLowerCase()); +const occurrenceArguments = z.strictObject({ event_id: z.uuid().transform(id => id.toLowerCase()) }); +const legacyArguments = z.strictObject({}); const target = z.object({ mode: z.literal("webhook"), url: z.string().max(2048) }); -const subscriptionIdentity = { - name: eventName, arguments: argumentsSchema.default({}), _meta: meta, -}; -export const subscribeEventInput = z.strictObject({ - ...subscriptionIdentity, +const stableIdentity = { name: z.literal(occurrenceEventName), arguments: occurrenceArguments, _meta: meta }; +const legacyIdentity = { name: legacyName, arguments: legacyArguments.default({}), _meta: meta }; +const subscribeFields = { delivery: target.extend({ secret: z.string().max(100) }).strict(), cursor: z.null().optional(), ttlMs: z.number().int().positive().nullable().optional(), -}); -export const unsubscribeEventInput = z.strictObject({ - ...subscriptionIdentity, - delivery: target.partial({ mode: true }).strict(), -}); +}; +const unsubscribeFields = { delivery: target.partial({ mode: true }).strict() }; +export const subscribeEventInput = z.union([ + z.strictObject({ ...stableIdentity, ...subscribeFields }), + z.strictObject({ ...legacyIdentity, ...subscribeFields }), +]); +export const unsubscribeEventInput = z.union([ + z.strictObject({ ...stableIdentity, ...unsubscribeFields }), + z.strictObject({ ...legacyIdentity, ...unsubscribeFields }), +]); + +type SubscriptionIdentity = Pick, "name" | "arguments">; +export function eventDefinitionId(input: SubscriptionIdentity) { + return "event_id" in input.arguments ? input.arguments.event_id : input.name.slice(legacyPrefix.length); +} + +// Empty persisted arguments identify the legacy protocol. Keep its signed +// envelope name unchanged while existing subscriptions migrate organically. +export function deliveryEventName(definitionId: string, args: unknown) { + const stable = occurrenceArguments.safeParse(args); + if (stable.success) return stable.data.event_id === definitionId ? occurrenceEventName : null; + return legacyArguments.safeParse(args).success ? legacyPrefix + definitionId : null; +} +export const occurrenceInputSchema = { + type: "object", + properties: { event_id: { type: "string", format: "uuid", description: "Factorize Event UUID from create_event or list_events." } }, + required: ["event_id"], + additionalProperties: false, +}; + export const listEventsInput = z.strictObject({ cursor: z.uuid().optional(), _meta: meta }); export const eventPayloadSchema = { diff --git a/packages/api/src/mcp-event-subscriptions.ts b/packages/api/src/mcp-event-subscriptions.ts index f3a94d1f..87ff7890 100644 --- a/packages/api/src/mcp-event-subscriptions.ts +++ b/packages/api/src/mcp-event-subscriptions.ts @@ -2,7 +2,7 @@ import { ProtocolError, ProtocolErrorCode } from "@modelcontextprotocol/server"; import type { z } from "zod"; import { normalizeScopes } from "./access-tokens"; import { decrypt, encrypt } from "./crypto"; -import { eventDefinitionId, eventProtocolName, type subscribeEventInput, type unsubscribeEventInput } from "./mcp-event-contracts"; +import { eventDefinitionId, deliveryEventName, type subscribeEventInput, type unsubscribeEventInput } from "./mcp-event-contracts"; import { callbackAccepted, canonicalCallbackURL, canonicalWebhookSecret, sendMcpWebhook, validChallenge, type WebhookOutcome } from "./mcp-webhook"; import { applyConnectionScopes, type ConnectionScopePolicy } from "./oauth-connection-settings"; import { databaseFor, type DatabaseClient } from "./postgres/database"; @@ -68,10 +68,10 @@ async function subscriptionKey(auth: OAuthProps, input: z.infer) { @@ -162,6 +162,8 @@ type Claim = { attempts: number; }; type Subscription = Principal & { + definition_id: string; + arguments: unknown; generation: string; status: string; expires_at: Date; @@ -225,6 +227,11 @@ async function dispatchClaim(env: Env, claim: Claim, now: () => number) { await finish(sql, "failed", maxAttempts, "claim_interrupted"); return; } + const name = deliveryEventName(subscription.definition_id, subscription.arguments); + if (record.definition_id !== subscription.definition_id || !name) { + await finish(sql, "cancelled", claim.attempts - 1, "event_mismatch"); + return; + } const attempts = claim.attempts; let result: WebhookOutcome; try { @@ -242,7 +249,7 @@ async function dispatchClaim(env: Env, claim: Claim, now: () => number) { subscriptionId: claim.subscription_id, id: claim.occurrence_id, payload: { - eventId: claim.occurrence_id, name: eventProtocolName(record.definition_id), timestamp: record.occurred_at.toISOString(), + eventId: claim.occurrence_id, name, timestamp: record.occurred_at.toISOString(), data: { occurrenceId: claim.occurrence_id, definitionId: record.definition_id }, cursor: null, }, secrets, diff --git a/packages/api/src/postgres/event-definition-repository.ts b/packages/api/src/postgres/event-definition-repository.ts index 2b14c621..d2193fea 100644 --- a/packages/api/src/postgres/event-definition-repository.ts +++ b/packages/api/src/postgres/event-definition-repository.ts @@ -55,17 +55,6 @@ export class EventDefinitionRepository { return rows.rows.map(row => ({ id: row.id, name: row.name, description: row.description, revision: row.current_revision, payloadSchema: row.payload_schema, triggerCount: row.trigger_count, occurrenceCount: row.occurrence_count, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() })); } - async mcpCatalog(cursor?: string) { - const limit = 100; - const rows = (await this.database.pool.query<{ id: string; name: string; description: string }>( - `SELECT id,name,description FROM app.event_definitions - WHERE tenant_id=$1 AND ($2::uuid IS NULL OR id>$2) ORDER BY id LIMIT $3`, - [this.tenantId, cursor ?? null, limit + 1], - )).rows; - const events = rows.slice(0, limit); - return { events, nextCursor: rows.length > limit ? events.at(-1)?.id : undefined }; - } - async occurrence(id: string) { const row = (await this.database.pool.query( `SELECT ${recordedFields} FROM app.event_occurrences WHERE tenant_id=$1 AND id=$2`, [this.tenantId, id], diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index 4397ae28..96d11e5b 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -168,7 +168,7 @@ function createMcpServer(service: ApiService, subscriptions = true): McpServer { throw new ProtocolError(ProtocolErrorCode.InternalError, "Factorize could not complete this Events request."); } }; - server.server.setRequestHandler("events/list", { params: listEventsInput }, params => eventAction(() => service.mcpEventCatalog(params.cursor))); + server.server.setRequestHandler("events/list", { params: listEventsInput }, () => eventAction(() => service.mcpEventCatalog())); server.server.setRequestHandler("events/subscribe", { params: subscribeEventInput }, params => eventAction(() => service.mcpSubscribeEvent(params))); server.server.setRequestHandler("events/unsubscribe", { params: unsubscribeEventInput }, params => eventAction(() => service.mcpUnsubscribeEvent(params))); server.server.setRequestHandler("skills/list",{params:z.object({cursor:z.guid().optional(),_meta:z.record(z.string(),z.unknown()).optional()})},params=>resourceAction(()=>service.mcpListSkills(params.cursor))); diff --git a/packages/api/test/mcp-events.postgres.test.ts b/packages/api/test/mcp-events.postgres.test.ts index 2dd50d82..279e731f 100644 --- a/packages/api/test/mcp-events.postgres.test.ts +++ b/packages/api/test/mcp-events.postgres.test.ts @@ -15,6 +15,7 @@ vi.mock("cloudflare:workers", () => ({ vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); const receiver = "https://receiver.example.com/inbound"; +const otherReceiver = "https://receiver.example.com/second"; const key = Buffer.alloc(32, 9), replacement = Buffer.alloc(32, 12); const secret = (signingKey: Buffer) => `whsec_${signingKey.toString("base64")}`; type Captured = { @@ -61,7 +62,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP event webhook lifecycl request = mcpRequest(f.env, auth); vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => { try { - expect(url).toBe(receiver); + expect([receiver, otherReceiver]).toContain(url); expect(init?.method).toBe("POST"); expect(init?.redirect).toBe("manual"); const headers = new Headers(init?.headers); @@ -152,18 +153,79 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP event webhook lifecycl expect((await get()).structuredContent.sources).toEqual(updated); }); + it("discovers one stable type and fans out only matching occurrences without breaking legacy subscriptions", async () => { + const catalog = (await request("events/list")).message.result; + expect(catalog.events).toEqual([{ + name: "factorize.occurrence", title: "Factorize occurrence", description: expect.any(String), + delivery: ["webhook"], + inputSchema: { + type: "object", properties: { event_id: { type: "string", format: "uuid", description: expect.any(String) } }, + required: ["event_id"], additionalProperties: false, + }, + payloadSchema: { + type: "object", additionalProperties: false, required: ["occurrenceId", "definitionId"], + properties: { occurrenceId: { type: "string", format: "uuid" }, definitionId: { type: "string", format: "uuid" } }, + }, + }]); + expect(catalog.nextCursor).toBeUndefined(); + const legacy = (await subscribe()).message.result; + const subscribeTo = (definitionId: string, url = receiver) => request("events/subscribe", { + name: catalog.events[0].name, arguments: { event_id: definitionId }, + delivery: { mode: "webhook", url, secret: secret(signingKey) }, + }); + const triggerFor = async (eventName: string) => { + const event = (await tool("create_event", { name: eventName })).structuredContent; + const trigger = (await tool("create_trigger", { + name: eventName, eventId: event.id, sources: [{ kind: "manual", config: {} }], + })).structuredContent; + return { eventId: event.id, triggerId: trigger.id }; + }; + const first = await triggerFor("dynamic-alpha"); + const second = await triggerFor("dynamic-beta"); + expect((await request("events/list")).message.result.events).toEqual(catalog.events); + const alpha = (await subscribeTo(first.eventId)).message.result; + const duplicate = (await subscribeTo(first.eventId.toUpperCase())).message.result; + expect(duplicate.id).toBe(alpha.id); + const alphaFanout = (await subscribeTo(first.eventId, otherReceiver)).message.result; + const beta = (await subscribeTo(second.eventId)).message.result; + const companion = (await subscribeTo(source.definitionId)).message.result; + expect(new Set([alpha.id, alphaFanout.id, beta.id, companion.id, legacy.id]).size).toBe(5); + const otherTenant = await f.seedEventTrigger(f.otherTenant); + expect((await subscribeTo(otherTenant.definitionId)).message.error.code).toBe(-32023); + expect((await subscribeTo("not-a-uuid")).message.error).toBeDefined(); + + const fireAt = async (triggerId: string, idempotencyKey: string) => + (await tool("fire_trigger", { triggerId, idempotencyKey })).structuredContent.occurrenceId; + const alphaOccurrence = await fireAt(first.triggerId, "alpha"); + const betaOccurrence = await fireAt(second.triggerId, "beta"); + const legacyOccurrence = (await fire("legacy-and-stable")).occurrenceId; + await dispatchMcpEvents(f.env); + const observed = (id: string) => deliveries.filter(d => d.id === id) + .map(d => [d.subscriptionId, d.event.name, d.event.data.definitionId]).sort(); + expect(observed(alphaOccurrence)).toEqual([ + [alpha.id, "factorize.occurrence", first.eventId], + [alphaFanout.id, "factorize.occurrence", first.eventId], + ].sort()); + expect(observed(betaOccurrence)).toEqual([[beta.id, "factorize.occurrence", second.eventId]]); + expect(observed(legacyOccurrence)).toEqual([ + [legacy.id, name, source.definitionId], + [companion.id, "factorize.occurrence", source.definitionId], + ].sort()); + + expect((await subscribe()).message.result.id).toBe(legacy.id); + expect((await unsubscribe()).message.result).toBeDefined(); + const stopAlpha = { name: catalog.events[0].name, arguments: { event_id: first.eventId.toUpperCase() }, delivery: { url: receiver } }; + expect((await request("events/unsubscribe", stopAlpha)).message.result).toBeDefined(); + expect((await request("events/unsubscribe", stopAlpha)).message.result).toBeDefined(); + const remainingAlpha = await fireAt(first.triggerId, "alpha-again"); + const remainingLegacy = (await fire("after-legacy-stop")).occurrenceId; + await dispatchMcpEvents(f.env); + expect(observed(remainingAlpha)).toEqual([[alphaFanout.id, "factorize.occurrence", first.eventId]]); + expect(observed(remainingLegacy)).toEqual([[companion.id, "factorize.occurrence", source.definitionId]]); + }); + it("discovers, subscribes, commits, dispatches and reads a deduplicated occurrence", async () => { expect((await request("server/discover")).message.result.capabilities).toMatchObject({ events: {}, resources: { subscribe: true } }); - expect((await request("events/list")).message.result.events).toEqual([{ - name, title: "fixture-event", description: "", delivery: ["webhook"], - inputSchema: { type: "object", properties: {}, additionalProperties: false }, - payloadSchema: { - type: "object", additionalProperties: false, required: ["occurrenceId", "definitionId"], - properties: { occurrenceId: { type: "string", format: "uuid" }, definitionId: { type: "string", format: "uuid" } }, - }, - }]); - await f.db.pool.query("UPDATE app.event_definitions SET name='renamed',description='Updated description' WHERE tenant_id=$1 AND id=$2", [f.tenantId, source.definitionId]); - expect((await request("events/list")).message.result.events[0]).toMatchObject({ name, title: "renamed", description: "Updated description" }); await fire("before-subscribe"); const active = (await subscribe()).message.result; expect(active).toMatchObject({ id: expect.stringMatching(/^sub_/), refreshBefore: expect.any(String), cursor: null, truncated: false }); diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index 11cff27b..21ec0de1 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -297,8 +297,12 @@ subscription support. After a resource-updated notification, read the resource to retrieve durable data. `list_event_occurrences` lets a reconnecting client recover stored records. -MCP Events clients can call `events/list` to discover webhook-capable -definitions and `events/subscribe` to start delivery through their OAuth grant. +MCP Events clients discover the stable `factorize.occurrence` type with +`events/list` and subscribe using `arguments: { "event_id": "" }`. +Get the UUID from `create_event` or `list_events`; no plugin refresh is +needed for new Event definitions after the one-time catalog refresh. Reuse the +same name, arguments, and callback to renew or unsubscribe. Existing per-Event +subscriptions keep their original names and continue receiving webhooks. Each notification includes the occurrence and definition IDs. Call `read_event_occurrences` with `occurrenceId` for the committed payload. For a wake without an ID, call it with the saved `definitionId` and a recent `since` diff --git a/packages/docs/mcp/tools.mdx b/packages/docs/mcp/tools.mdx index 6b132d71..2076594e 100644 --- a/packages/docs/mcp/tools.mdx +++ b/packages/docs/mcp/tools.mdx @@ -68,8 +68,12 @@ subscription support. After a resource-updated notification, read the resource to retrieve durable data. `list_event_occurrences` lets a reconnecting client recover stored records. -MCP Events clients can call `events/list` to discover webhook-capable -definitions and `events/subscribe` to start delivery through their OAuth grant. +MCP Events clients discover the stable `factorize.occurrence` type with +`events/list` and subscribe using `arguments: { "event_id": "" }`. +Get the UUID from `create_event` or `list_events`; no plugin refresh is +needed for new Event definitions after the one-time catalog refresh. Reuse the +same name, arguments, and callback to renew or unsubscribe. Existing per-Event +subscriptions keep their original names and continue receiving webhooks. Each notification includes the occurrence and definition IDs. Call `read_event_occurrences` with `occurrenceId` for the committed payload. For a wake without an ID, call it with the saved `definitionId` and a recent `since` diff --git a/scripts/oauth-runtime.mjs b/scripts/oauth-runtime.mjs index e88c60d3..e645e4d6 100644 --- a/scripts/oauth-runtime.mjs +++ b/scripts/oauth-runtime.mjs @@ -119,8 +119,9 @@ export async function checkOAuth({ read: send, stream, db, tenantId, userId, coo const discovery = await modernRpc("server/discover", {}); assert.deepEqual(discovery.capabilities.events, {}); const catalog = await modernRpc("events/list", {}); - assert.ok(catalog.events.some(definition => definition.name === `factorize.event.${event.id}` && - definition.title === "review.requested" && definition.delivery.includes("webhook"))); + assert.deepEqual(catalog.events.map(definition => definition.name), ["factorize.occurrence"]); + assert.deepEqual(catalog.events[0].inputSchema.required, ["event_id"]); + assert.equal(catalog.events[0].inputSchema.properties.event_id.format, "uuid"); const trigger = await tool("create_trigger", { name: "manual-review", eventId: event.id, sources: [{ kind: "manual", config: {} }], });