Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion docs/mcp-event-webhooks.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
# MCP Event webhooks

Factorize exposes Event definitions over the authenticated `/mcp` endpoint. A definition's protocol name is `factorize.event.<definition-id>`. 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": "<uuid>" }` 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.<definition-id>` 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

Expand Down
18 changes: 8 additions & 10 deletions packages/api/src/api-service.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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<typeof subscribeEventInput>) {
Expand Down
53 changes: 38 additions & 15 deletions packages/api/src/mcp-event-contracts.ts
Original file line number Diff line number Diff line change
@@ -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<z.infer<typeof unsubscribeEventInput>, "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 = {
Expand Down
15 changes: 11 additions & 4 deletions packages/api/src/mcp-event-subscriptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -68,10 +68,10 @@ async function subscriptionKey(auth: OAuthProps, input: z.infer<typeof unsubscri
tenant_id: auth.tenantId, user_id: auth.userId, grant_id: auth.oauthGrantId, client_id: auth.oauthClientId,
session_version: auth.sessionVersion,
};
// The strict empty arguments schema has one canonical representation.
// Validated arguments have one canonical representation per event and protocol.
const args = JSON.stringify(input.arguments);
const id = "sub_" + await digest(JSON.stringify([auth.tenantId, auth.userId, auth.oauthGrantId, url, input.name, args]));
return { id, url, args, principal, definitionId: eventDefinitionId(input.name) };
return { id, url, args, principal, definitionId: eventDefinitionId(input) };
}

export async function subscribeMcpEvent(env: Env, auth: OAuthProps, input: z.infer<typeof subscribeEventInput>) {
Expand Down Expand Up @@ -162,6 +162,8 @@ type Claim = {
attempts: number;
};
type Subscription = Principal & {
definition_id: string;
arguments: unknown;
generation: string;
status: string;
expires_at: Date;
Expand Down Expand Up @@ -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 {
Expand All @@ -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,
Expand Down
11 changes: 0 additions & 11 deletions packages/api/src/postgres/event-definition-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<RecordedOccurrence>(
`SELECT ${recordedFields} FROM app.event_occurrences WHERE tenant_id=$1 AND id=$2`, [this.tenantId, id],
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/protected-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)));
Expand Down
84 changes: 73 additions & 11 deletions packages/api/test/mcp-events.postgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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 });
Expand Down
Loading
Loading