From 0e20250ac72264a1d62fd2d1be8ab9188dcd0960 Mon Sep 17 00:00:00 2001 From: Brendan Asselstine Date: Tue, 24 Nov 2026 12:29:45 -0700 Subject: [PATCH] Expose per-occurrence MCP delivery diagnostics --- docs/mcp-event-webhooks.md | 5 +- packages/api/src/api-service.ts | 7 ++ packages/api/src/mcp-event-contracts.ts | 3 + .../postgres/event-definition-repository.ts | 49 ++++++++++++ packages/api/src/protected-api.ts | 3 +- packages/api/test/mcp-events.postgres.test.ts | 74 +++++++++++++++++++ packages/docs/llms-full.txt | 11 +++ packages/docs/mcp/tools.mdx | 11 +++ 8 files changed, 161 insertions(+), 2 deletions(-) diff --git a/docs/mcp-event-webhooks.md b/docs/mcp-event-webhooks.md index d04d6319..9184abc7 100644 --- a/docs/mcp-event-webhooks.md +++ b/docs/mcp-event-webhooks.md @@ -16,7 +16,10 @@ The Factorize Worker sends callbacks directly over HTTPS. It rejects private IP The occurrence and its outbox rows commit together. Subscription activation and occurrence insertion take the same transaction lock per definition. Each outbox row belongs to one activation generation, so refreshing an active subscription keeps its queued deliveries, while reactivating a stopped or expired one starts a new generation. Expiry defaults to 24 hours and is capped at seven days. A replaced secret is the primary signing key immediately, with a five-minute dual-signing window. -The Worker alarm claims due rows and checks current grant, owner, scope, subscription status, and expiry before sending. A retry after an interrupted or uncertain attempt uses the same occurrence ID and a fresh signature. Callback acceptance means the endpoint returned a successful HTTP status. In PostgreSQL, `app.mcp_event_deliveries` records the attempt count, status, last outcome, and HTTP status. +The Worker alarm claims due rows and checks current grant, owner, scope, subscription status, and expiry before sending. A retry after an interrupted or uncertain attempt uses the same occurrence ID and a fresh signature. Callback acceptance means the endpoint returned a successful HTTP status. + +For one exact occurrence, call the read-only `read_event_delivery_diagnostics` MCP tool with an owner credential scoped to `triggers:read`. It distinguishes a missing occurrence (not found) from an existing occurrence with no delivery records. Up to 100 most recently updated rows describe each delivery's opaque subscription ID, status, attempts, allowlisted outcome code, HTTP status, and timestamps. A pending row can include its next attempt time. `truncated` indicates more rows exist. An accepted delivery confirms callback receipt only, not task execution. The diagnostic does not expose callback details or contents, and cannot retry a delivery. +In PostgreSQL, `app.mcp_event_deliveries` records the attempt count, status, last outcome, and HTTP status. ## Mocked Dot pilot diff --git a/packages/api/src/api-service.ts b/packages/api/src/api-service.ts index 3d7a1cfa..4967d5f2 100644 --- a/packages/api/src/api-service.ts +++ b/packages/api/src/api-service.ts @@ -243,6 +243,13 @@ export class ApiService { if (!await repository.get(definitionId)) throw new ServiceError(404, "not_found", "Event not found."); return repository.recordedOccurrences(definitionId, input.since, input.limit, cursor ? [cursor[2], cursor[3]] : undefined); } + async readEventDeliveryDiagnostics(occurrenceId: string) { + if (this.auth.authMethod === "vm") throw new ServiceError(403, "owner_required", "An owner credential is required."); + await this.authorize("triggers:read"); + const result = await this.eventDefinitions().deliveryDiagnostics(occurrenceId); + if (!result) throw new ServiceError(404, "not_found", "Event occurrence not found."); + return result; + } async mcpReadEvent(uri: string) { let parsed: URL; try { parsed = new URL(uri); } catch { throw new ServiceError(400, "invalid_resource", "Expected a Factorize Event resource URI."); } if (parsed.protocol !== "factorize:" || parsed.hostname !== "events" || !/^\/[0-9a-f-]{36}\/occurrences$/.test(parsed.pathname)) throw new ServiceError(400, "invalid_resource", "Expected a Factorize Event occurrence URI."); diff --git a/packages/api/src/mcp-event-contracts.ts b/packages/api/src/mcp-event-contracts.ts index e0c136b9..8e591f74 100644 --- a/packages/api/src/mcp-event-contracts.ts +++ b/packages/api/src/mcp-event-contracts.ts @@ -65,3 +65,6 @@ export const readEventOccurrencesInput = z.union([ }), ]); export type ReadEventOccurrencesInput = z.infer; + + +export const readEventDeliveryDiagnosticsInput = z.strictObject({ occurrenceId: z.uuid() }); diff --git a/packages/api/src/postgres/event-definition-repository.ts b/packages/api/src/postgres/event-definition-repository.ts index d2193fea..c52dc270 100644 --- a/packages/api/src/postgres/event-definition-repository.ts +++ b/packages/api/src/postgres/event-definition-repository.ts @@ -24,6 +24,23 @@ function presentRecorded(row: RecordedOccurrence) { const recordedFields = `id,definition_id,definition_revision,occurred_at,payload, to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS recorded_at`; +type DeliveryStatus = "pending" | "sending" | "accepted" | "failed" | "cancelled"; +interface DeliveryDiagnosticRow { + occurrence_id: string; + subscription_id: string | null; + status: DeliveryStatus | null; + attempts: number; + last_outcome: string | null; + http_status: number | null; + updated_at: Date; + next_attempt_at: Date; +} +const deliveryOutcomeCodes = new Set([ + "accepted", "http_error", "connection_failed", "timeout", "forbidden_destination", + "subscription_inactive", "authorization_inactive", "claim_interrupted", "event_mismatch", +]); +const deliveryDiagnosticsLimit = 100; + export interface EventDefinitionInput { name: string; description?: string; @@ -62,6 +79,38 @@ export class EventDefinitionRepository { return row && presentRecorded(row); } + async deliveryDiagnostics(occurrenceId: string) { + // One tenant-scoped snapshot distinguishes a missing occurrence from an + // existing one with no outbox rows without fetching payload or callback data. + const { rows } = await this.database.pool.query( + `SELECT o.id AS occurrence_id,d.subscription_id,d.status,d.attempts,d.last_outcome,d.http_status,d.updated_at,d.next_attempt_at + FROM app.event_occurrences o LEFT JOIN LATERAL ( + SELECT subscription_id,status,attempts,last_outcome,http_status,updated_at,next_attempt_at + FROM app.mcp_event_deliveries + WHERE tenant_id=o.tenant_id AND occurrence_id=o.id + ORDER BY updated_at DESC,subscription_id LIMIT $3 + ) d ON TRUE + WHERE o.tenant_id=$1 AND o.id=$2 + ORDER BY d.updated_at DESC,d.subscription_id`, [this.tenantId, occurrenceId, deliveryDiagnosticsLimit + 1], + ); + if (!rows.length) return null; + const items = rows.flatMap(row => row.status === null ? [] : [{ + subscriptionId: row.subscription_id && /^sub_[a-f0-9]{64}$/.test(row.subscription_id) ? row.subscription_id : null, + status: row.status, + attempts: row.attempts, + lastOutcome: row.last_outcome === null ? null : deliveryOutcomeCodes.has(row.last_outcome) ? row.last_outcome : "unclassified", + httpStatus: row.http_status !== null && row.http_status >= 100 && row.http_status <= 599 ? row.http_status : null, + updatedAt: row.updated_at.toISOString(), + nextAttemptAt: row.status === "pending" ? row.next_attempt_at.toISOString() : null, + }]); + return { + occurrenceId: rows[0].occurrence_id, + state: items.length ? "delivery_records_present" : "no_delivery_records", + items: items.slice(0, deliveryDiagnosticsLimit), + truncated: items.length > deliveryDiagnosticsLimit, + }; + } + async recordedOccurrences(definitionId: string, since: string, limit: number, boundary?: [string, string]) { const rows = (await this.database.pool.query( `SELECT ${recordedFields} FROM app.event_occurrences diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index 96d11e5b..458f8276 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -1,4 +1,4 @@ -import { listEventsInput, readEventOccurrencesInput, subscribeEventInput, unsubscribeEventInput } from "./mcp-event-contracts"; +import { listEventsInput, readEventDeliveryDiagnosticsInput, readEventOccurrencesInput, subscribeEventInput, unsubscribeEventInput } from "./mcp-event-contracts"; import { appRegistrationInput, appRegistrationUpdate } from "./apps-contracts"; import {createPayloadInput,appendPayloadInput,finalizePayloadInput,attachmentInput} from "./proxy-payloads"; import {operationRef,operationRead} from "./proxy-operations"; @@ -209,6 +209,7 @@ function createMcpServer(service: ApiService, subscriptions = true): McpServer { tool("create_event", "Create a durable Event that one or more Triggers can publish.", eventDefinitionInput, (input:any) => service.createEvent(input)); tool("update_event", "Create a new Event payload schema revision; existing occurrences retain their original revision.", eventDefinitionUpdate.extend({eventId:z.uuid()}), ({eventId,...input}:any) => service.updateEvent(eventId,input)); tool("delete_event", "Permanently delete an Event, all its Triggers and input configurations, and its occurrence history.", z.object({eventId:z.uuid()}), ({eventId}:any) => service.deleteEvent(eventId)); + tool("read_event_delivery_diagnostics", "Read safe outbound MCP webhook delivery diagnostics for one exact occurrence ID. This does not return payloads or callback details and does not retry deliveries.", readEventDeliveryDiagnosticsInput, ({ occurrenceId }: z.infer) => service.readEventDeliveryDiagnostics(occurrenceId), false, true); tool("read_event_occurrences", "Read committed Event payloads by occurrenceId or by definitionId and an inclusive recorded-time since value. Follow nextCursor with the same definitionId and since. Reads do not consume history.", readEventOccurrencesInput, (input: z.infer) => service.readEventOccurrences(input), false, true); tool("list_event_occurrences", "Read durable Event occurrences in reverse order.", z.object({eventId:z.uuid(),...eventOccurrenceQuery.shape}), ({eventId,limit,cursor}:any) => service.listEventOccurrences(eventId,limit,cursor)); tool("list_triggers", "List triggers and their parent Events", z.object({}), () => service.listTriggers()); diff --git a/packages/api/test/mcp-events.postgres.test.ts b/packages/api/test/mcp-events.postgres.test.ts index 279e731f..9b5f62e7 100644 --- a/packages/api/test/mcp-events.postgres.test.ts +++ b/packages/api/test/mcp-events.postgres.test.ts @@ -153,6 +153,80 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP event webhook lifecycl expect((await get()).structuredContent.sources).toEqual(updated); }); + it("reports safe outbound delivery diagnostics for exactly one owner-authorized occurrence", async () => { + const toolInfo = (await request("tools/list")).message.result.tools.find((item: { name: string }) => + item.name === "read_event_delivery_diagnostics"); + expect(toolInfo.annotations.readOnlyHint).toBe(true); + const diagnosis = (occurrenceId: string, identity = auth) => + tool("read_event_delivery_diagnostics", { occurrenceId }, identity); + const detail = async (occurrenceId: string) => { + const result = await diagnosis(occurrenceId); + expect(result.isError, JSON.stringify(result)).not.toBe(true); + return result.structuredContent; + }; + + const empty = (await fire("no-subscription", { text: "payload-that-must-not-be-returned" })).occurrenceId; + expect(await detail(empty)).toEqual({ occurrenceId: empty, state: "no_delivery_records", items: [], truncated: false }); + const missing = await diagnosis(crypto.randomUUID()); + expect(missing.isError).toBe(true); + expect(JSON.stringify(missing.content)).toContain("Event occurrence not found."); + + const other = await f.seedEventTrigger(f.otherTenant); + const otherMatch = await new EventMatchRepository(f.db).match({ + tenantId: f.otherTenant, triggerId: other.triggerId, triggerRevision: 1, sourceIdentity: "isolated-test", + deduplicationKey: "other-occurrence", evidence: { text: "private" }, decision: "matched", + }); + const crossTenant = await diagnosis(otherMatch.occurrence!.id); + expect(crossTenant.isError).toBe(true); + expect(crossTenant.content).toEqual(missing.content); + expect((await diagnosis(empty, { ...auth, scopes: [] })).isError).toBe(true); + expect((await diagnosis(empty, { ...auth, userId: crypto.randomUUID() })).isError).toBe(true); + + const subscriptionId = (await subscribe()).message.result.id; + expect(subscriptionId).toMatch(/^sub_/); + const accepted = (await fire("accepted")).occurrenceId; + const pending = await detail(accepted); + expect(pending).toEqual({ + occurrenceId: accepted, state: "delivery_records_present", truncated: false, + items: [{ subscriptionId, status: "pending", attempts: 0, lastOutcome: null, httpStatus: null, + updatedAt: expect.any(String), nextAttemptAt: expect.any(String) }], + }); + await dispatchMcpEvents(f.env); + expect((await detail(accepted)).items).toEqual([{ + subscriptionId, status: "accepted", attempts: 1, lastOutcome: "accepted", httpStatus: 200, + updatedAt: expect.any(String), nextAttemptAt: null, + }]); + + const rejected = (await fire("rejected")).occurrenceId; + statuses.push(410); + await dispatchMcpEvents(f.env); + expect((await detail(rejected)).items).toMatchObject([{ status: "failed", lastOutcome: "http_error", httpStatus: 410, attempts: 1 }]); + // Unrecognized stored text is not echoed even if a future writer stores it. + await f.db.pool.query("UPDATE app.mcp_event_deliveries SET last_outcome=$2 WHERE occurrence_id=$1", + [rejected, "raw-error-with-private-response-body"]); + const redacted = await detail(rejected); + expect(redacted.items[0].lastOutcome).toBe("unclassified"); + expect(JSON.stringify(redacted)).not.toContain("raw-error-with-private-response-body"); + + const removed = (await fire("cancel-after-unsubscribe")).occurrenceId; + await unsubscribe(); + await dispatchMcpEvents(f.env); + expect((await detail(removed)).items).toMatchObject([{ status: "cancelled", lastOutcome: "subscription_inactive", httpStatus: null, attempts: 0 }]); + + expect((await subscribe()).message.result.id).toBeDefined(); + const denied = (await fire("cancel-after-grant-revocation")).occurrenceId; + grantActive = false; + await dispatchMcpEvents(f.env); + grantActive = true; + expect((await detail(denied)).items).toMatchObject([{ status: "cancelled", lastOutcome: "authorization_inactive", httpStatus: null, attempts: 0 }]); + + const retry = (await fire("retry")).occurrenceId; + statuses.push(503); + await dispatchMcpEvents(f.env); + expect((await detail(retry)).items).toMatchObject([{ status: "pending", lastOutcome: "http_error", httpStatus: 503, attempts: 1, nextAttemptAt: expect.any(String) }]); + expect(await detail(empty)).toEqual({ occurrenceId: empty, state: "no_delivery_records", items: [], truncated: false }); + }); + 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([{ diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index 999acd72..872de826 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -266,6 +266,7 @@ its input and enforces the operation's required scope. | `list_apps` | Purpose-specific scope enforced by the server | Validated tool-specific JSON input | | `list_cloudflare_tail_integrations` | Purpose-specific scope enforced by the server | Validated tool-specific JSON input | | `list_event_occurrences` | Purpose-specific scope enforced by the server | Validated tool-specific JSON input | +| `read_event_delivery_diagnostics` | Owner credential with `triggers:read` | Read safe outbound MCP webhook delivery diagnostics for one occurrence ID | | `read_event_occurrences` | `triggers:read` | An `occurrenceId`, or a `definitionId` and inclusive `since` with optional `cursor` and `limit` | | `list_events` | Purpose-specific scope enforced by the server | Validated tool-specific JSON input | | `list_exe_connections` | Purpose-specific scope enforced by the server | Validated tool-specific JSON input | @@ -310,6 +311,16 @@ time, and follow `nextCursor` with the same definition and time. Windowed reads use recorded time so recent arrivals with older source timestamps appear. Reads leave history intact. +Use `read_event_delivery_diagnostics` with an exact `occurrenceId` to +inspect outbound MCP webhook delivery. `no_delivery_records` means the +occurrence exists but no delivery rows are recorded; a missing occurrence +returns not found. Rows distinguish pending/sending, accepted, failed, and +cancelled delivery. They show opaque subscription IDs, attempt counts, safe outcome codes, HTTP status, +and timestamps, never payloads or callback details. Callback acceptance is +not proof that a downstream task ran. This is separate from inbound webhook +delivery tools and cannot retry an outbound message. + + `delete_event` permanently removes the Event, all attached Triggers and input configurations, and all stored occurrences. diff --git a/packages/docs/mcp/tools.mdx b/packages/docs/mcp/tools.mdx index 2076594e..a066760a 100644 --- a/packages/docs/mcp/tools.mdx +++ b/packages/docs/mcp/tools.mdx @@ -37,6 +37,7 @@ its input and enforces the operation's required scope. | `list_apps` | Purpose-specific scope enforced by the server | Validated tool-specific JSON input | | `list_cloudflare_tail_integrations` | Purpose-specific scope enforced by the server | Validated tool-specific JSON input | | `list_event_occurrences` | Purpose-specific scope enforced by the server | Validated tool-specific JSON input | +| `read_event_delivery_diagnostics` | Owner credential with `triggers:read` | Read safe outbound MCP webhook delivery diagnostics for one occurrence ID | | `read_event_occurrences` | `triggers:read` | An `occurrenceId`, or a `definitionId` and inclusive `since` with optional `cursor` and `limit` | | `list_events` | Purpose-specific scope enforced by the server | Validated tool-specific JSON input | | `list_exe_connections` | Purpose-specific scope enforced by the server | Validated tool-specific JSON input | @@ -81,6 +82,16 @@ time, and follow `nextCursor` with the same definition and time. Windowed reads use recorded time so recent arrivals with older source timestamps appear. Reads leave history intact. +Use `read_event_delivery_diagnostics` with an exact `occurrenceId` to +inspect outbound MCP webhook delivery. `no_delivery_records` means the +occurrence exists but no delivery rows are recorded; a missing occurrence +returns not found. Rows distinguish pending/sending, accepted, failed, and +cancelled delivery. They show opaque subscription IDs, attempt counts, safe outcome codes, HTTP status, +and timestamps, never payloads or callback details. Callback acceptance is +not proof that a downstream task ran. This is separate from inbound webhook +delivery tools and cannot retry an outbound message. + + `delete_event` permanently removes the Event, all attached Triggers and input configurations, and all stored occurrences.