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
28 changes: 28 additions & 0 deletions docs/mcp-event-webhooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,34 @@ The Worker alarm claims due rows and checks current grant, owner, scope, subscri
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.

## Optional processing acknowledgments

An active OAuth client with `triggers:read` can opt in on its own subscription
using `set_event_processing_acknowledgments`. The standard subscribe,
unsubscribe and webhook payload schemas do not change. The optional timeout
is 30–86400 seconds (default 300). An HTTP-accepted occurrence remains
`awaiting_ack` until durably processed, waived, cancelled or exhausted.

Use `acknowledge_events(subscription_id, event_ids, cooldown_seconds?)` only
after durable completion or handoff. Use exactly the original occurrence IDs
in `data.occurrenceId` regardless of delivery order or how many events appeared
in a wake. The optional cooldown pauses delivery on this subscription and
only changes when at least one ID is newly acknowledged. Duplicate ACKs are
safe and never extend the cooldown. Continue independent client-local pacing;
do not rely on the platform's limits or silently discard unfinished work.

When an ACK times out, the scheduler issues a recovery wake with a fresh
webhook `eventId` and the same original `data.occurrenceId`. Transport retries
of an interrupted recovery reuse its persisted wake ID. There are at most
four automatic recovery attempts per cycle with backoff. Explicit
`replay_unacknowledged_events` can queue exact unresolved original IDs after
inspection, including exhausted recovery, without changing the durable
business event stream. Cooldown applies to replays as well. Diagnostics
report HTTP transport separately from processing state, attempted recoveries
and next recovery time. After disabling, outstanding processing is waived
(not marked complete), unstarted recovery is cancelled, and cooldown is
cleared. A new opt-in starts with future occurrences only.

## Mocked Dot pilot

The mock saves the subscribed definition ID. For a wake with occurrence IDs, it calls `read_event_occurrences` once per ID. For an empty wake, it uses the saved ID and a recent overlapping `since` value, paging until `nextCursor` is null. The mock tracks already summarized occurrence IDs in its context. Without prior context an overlapping window can summarize an occurrence again.
Expand Down
15 changes: 15 additions & 0 deletions packages/api/migrations/0106_mcp_processing_acknowledgments.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
ALTER TABLE app.mcp_event_subscriptions
ADD COLUMN ack_epoch uuid,
ADD COLUMN ack_timeout_seconds integer NOT NULL DEFAULT 300 CHECK (ack_timeout_seconds BETWEEN 30 AND 86400),
ADD COLUMN cooldown_until timestamptz;

ALTER TABLE app.mcp_event_deliveries
ADD COLUMN ack_epoch uuid,
ADD COLUMN ack_state text CHECK (ack_state IN ('pending','awaiting_ack','processed','waived','exhausted','cancelled')),
ADD COLUMN ack_due_at timestamptz,
ADD COLUMN ack_updated_at timestamptz,
ADD COLUMN recovery_event_id uuid,
ADD COLUMN recovery_attempts integer NOT NULL DEFAULT 0 CHECK (recovery_attempts >= 0);

CREATE INDEX mcp_event_deliveries_ack_due ON app.mcp_event_deliveries(ack_due_at,tenant_id,subscription_id,occurrence_id)
WHERE ack_state='awaiting_ack';
7 changes: 5 additions & 2 deletions packages/api/src/alarm-coordinator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { databaseFor } from "./postgres/database";
import { cleanupAgentResponses } from "./agent-api";
import { maintainProxyOperations } from "./proxy-operations";
import type { Env } from "./types";
import { dispatchMcpEvents, mcpEventDispatchBatchSize } from "./mcp-event-subscriptions";
import { dispatchMcpEvents, mcpEventDispatchBatchSize, nextMcpDeliveryDelay } from "./mcp-event-subscriptions";

/** Wakes provider and schedule Triggers and maintains bounded proxy records. */
export class AlarmCoordinator extends DurableObject<Env> {
Expand Down Expand Up @@ -41,7 +41,10 @@ export class AlarmCoordinator extends DurableObject<Env> {
} finally {
backlog = await dispatchMcpEvents(this.eventEnv()) === mcpEventDispatchBatchSize;
}
} finally { await this.schedule(backlog ? 100 : 60_000); }
} finally {
const delay = backlog ? 100 : await nextMcpDeliveryDelay(this.eventEnv()).catch(() => 60_000);
await this.schedule(Math.min(60_000, delay));
}
}
private async schedule(delay = 60_000) {
const current = await this.ctx.storage.getAlarm(), desired = Date.now() + delay;
Expand Down
22 changes: 19 additions & 3 deletions packages/api/src/api-service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { initialIntegrationOverrides, lockOAuthPolicy } from "./oauth-reconnect";
import { lockMcpEventGrant } from "./postgres/mcp-event-outbox";
import { eventPayloadSchema, occurrenceEventName, occurrenceInputSchema, type ReadEventOccurrencesInput, type subscribeEventInput, type unsubscribeEventInput } from "./mcp-event-contracts";
import { subscribeMcpEvent, unsubscribeMcpEvent } from "./mcp-event-subscriptions";
import { eventPayloadSchema, occurrenceEventName, occurrenceInputSchema, type ReadEventOccurrencesInput, type subscribeEventInput, type unsubscribeEventInput, type setProcessingAcknowledgmentsInput, type acknowledgeEventsInput } from "./mcp-event-contracts";
import { subscribeMcpEvent, unsubscribeMcpEvent, getProcessingAcknowledgments, setProcessingAcknowledgments, acknowledgeEvents, replayUnacknowledgedEvents } from "./mcp-event-subscriptions";
import { vmGrantInput, vmGrantList, vmGrantResult, vmRevokeResult } from "./vm-grant-contracts";
import { VmGrantRepository, vmGrantActor, type VmGrant } from "./postgres/vm-grant-repository";
import { provisionVmGrant } from "./vm-enrollment";
Expand Down Expand Up @@ -213,7 +213,7 @@ export class ApiService {
events: [{
name: occurrenceEventName,
title: "Factorize occurrence",
description: "A new occurrence for the selected Factorize Event. Use its UUID as event_id.",
description: "A wake for the selected Factorize Event UUID. HTTP 2xx confirms callback acceptance, not processing. Optional subscription acknowledgments use exact original data.occurrenceId, never UUID ordering; recovery wakes may have a fresh eventId.",
delivery: ["webhook"],
inputSchema: occurrenceInputSchema,
payloadSchema: eventPayloadSchema,
Expand All @@ -228,6 +228,22 @@ export class ApiService {
await this.authorize("triggers:read");
return unsubscribeMcpEvent(this.env, this.auth, input);
}
async getEventProcessing(subscriptionId: string) {
await this.authorize("triggers:read");
return getProcessingAcknowledgments(this.env, this.auth, subscriptionId);
}
async setEventProcessing(input: z.infer<typeof setProcessingAcknowledgmentsInput>) {
await this.authorize("triggers:read");
return setProcessingAcknowledgments(this.env, this.auth, input);
}
async acknowledgeEventProcessing(input: z.infer<typeof acknowledgeEventsInput>) {
await this.authorize("triggers:read");
return acknowledgeEvents(this.env, this.auth, input);
}
async replayEventProcessing(subscriptionId: string, ids: string[]) {
await this.authorize("triggers:read");
return replayUnacknowledgedEvents(this.env, this.auth, subscriptionId, ids);
}
async readEventOccurrences(input: ReadEventOccurrencesInput) {
await this.authorize("triggers:read");
const repository = this.eventDefinitions();
Expand Down
8 changes: 4 additions & 4 deletions packages/api/src/generated/builtin-skills.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
// Generated by scripts/generate-builtin-skills.mjs; edit skills/*/SKILL.md.
export const builtinSkillsVersion = "163ea346fac491851d1b2a846bc319895c60945bc9ce63d3922b7bf2aaee8f1c";
export const builtinSkillsVersion = "843d82f53f31fc88aea8e94f09aa3af7f40b1986feae89467f6d82bd8f24b3e8";
export const builtinSkillDocuments = [
{
"name": "manage-triggers",
"frontmatter": {
"name": "manage-triggers",
"description": "Configure input Triggers that publish durable Factorize Events."
},
"text": "---\nname: manage-triggers\ndescription: Configure input Triggers that publish durable Factorize Events.\n---\n# Manage Events and Triggers\n\nCall `get_api_reflection` to inspect current identity and permissions. An Event describes a durable payload stream. A Trigger watches one or more input sources and publishes matching occurrences.\n\n## Events\n\nUse `list_events` and `get_event` to inspect Events and their payload schema revisions. Create an Event with `create_event`, including a lowercase stable `name`, optional description, and JSON Schema object in `payloadSchema`. Use `update_event` with the current `expectedRevision` to add a schema revision. Existing occurrences keep their original revision. `delete_event` permanently deletes the Event, all attached Triggers and input configurations, and all occurrence history.\n\nMCP subscribers read `factorize://events/{eventId}/occurrences`. Subscribe through `subscriptions/listen`; on resource update, read the occurrence resource. Occurrences are durable, so reconnecting clients can read missed records. Use `list_event_occurrences` to page through stored occurrences.\n\n## Triggers\n\nEach Trigger belongs to one Event; multiple Triggers may publish the same Event. Configure a Trigger with an existing `eventId`, or let the API create its initial Event. Trigger inputs can be manual, scheduled, or provider webhooks. Schedules use cron and an IANA timezone. Webhook inputs select a provider and provider-specific filters. Use `list_github_installations` and `list_cloudflare_tail_integrations` to discover saved provider setup.\n\nUse `list_triggers` and `get_trigger` to inspect Triggers. `create_trigger` and `update_trigger` require `triggers:write`; read before editing and preserve stable IDs for entries in the `sources` array. A successful input match writes one schema-validated Event occurrence. Reuse `idempotencyKey` when retrying `fire_trigger`; duplicate source deliveries do not create duplicate occurrences. `enable_trigger` and `disable_trigger` control future input processing. `delete_trigger` removes its future automation.\n\nWebhook `conditions` are optional and can be checked with `test_trigger_webhook_conditions` against representative prepared data; this does not verify provider authentication or delivery. Use `list_trigger_webhook_activity`, `list_webhook_deliveries`, and `get_webhook_delivery` to inspect safe input-processing results.\n",
"digest": "sha256:f7a22768ab75a8674d8e8586cc61e399a4c86bed1c972f6dd03049169d7ed3dd",
"size": 2416
"text": "---\nname: manage-triggers\ndescription: Configure input Triggers that publish durable Factorize Events.\n---\n# Manage Events and Triggers\n\nCall `get_api_reflection` to inspect current identity and permissions. An Event describes a durable payload stream. A Trigger watches one or more input sources and publishes matching occurrences.\n\n## Events\n\nUse `list_events` and `get_event` to inspect Events and their payload schema revisions. Create an Event with `create_event`, including a lowercase stable `name`, optional description, and JSON Schema object in `payloadSchema`. Use `update_event` with the current `expectedRevision` to add a schema revision. Existing occurrences keep their original revision. `delete_event` permanently deletes the Event, all attached Triggers and input configurations, and all occurrence history.\n\nMCP subscribers read `factorize://events/{eventId}/occurrences`. Subscribe through `subscriptions/listen`; on resource update, read the occurrence resource. Occurrences are durable, so reconnecting clients can read missed records. Use `list_event_occurrences` to page through stored occurrences.\n\n## Optional webhook processing acknowledgments\n\nUse the stable `factorize.occurrence` type with the exact Event UUID in\n`event_id`. HTTP 2xx is only callback acceptance. If the user opted in,\nread the exact subscription policy with `get_event_processing_acknowledgments`\nand change it with `set_event_processing_acknowledgments`. Standard\nsubscriptions are off by default. This is separate from task run limits.\n\nAfter durable completion or handoff, promptly call `acknowledge_events` with\nyour `subscription_id` and exact original `event_ids` from\n`data.occurrenceId`. Use the original ID to read and deduplicate; recovery\nmay use a fresh webhook `eventId`. IDs do not encode ordering, and wakes can\nbe partial or out of order. Never assume a batching window or rate cap.\nPace work locally, persist unfinished work instead of dropping it, and do not\nacknowledge it until durable. Optional `cooldown_seconds` pauses future\ndelivery on that subscription only, and duplicate ACKs do not extend it.\n\nUse `read_event_delivery_diagnostics` for HTTP versus processing status, and\n`replay_unacknowledged_events` for exact unresolved original IDs only. Turning\noff waives unresolved ACKs and clears cooldown; re-enabling applies forward.\n\n\n## Triggers\n\nEach Trigger belongs to one Event; multiple Triggers may publish the same Event. Configure a Trigger with an existing `eventId`, or let the API create its initial Event. Trigger inputs can be manual, scheduled, or provider webhooks. Schedules use cron and an IANA timezone. Webhook inputs select a provider and provider-specific filters. Use `list_github_installations` and `list_cloudflare_tail_integrations` to discover saved provider setup.\n\nUse `list_triggers` and `get_trigger` to inspect Triggers. `create_trigger` and `update_trigger` require `triggers:write`; read before editing and preserve stable IDs for entries in the `sources` array. A successful input match writes one schema-validated Event occurrence. Reuse `idempotencyKey` when retrying `fire_trigger`; duplicate source deliveries do not create duplicate occurrences. `enable_trigger` and `disable_trigger` control future input processing. `delete_trigger` removes its future automation.\n\nWebhook `conditions` are optional and can be checked with `test_trigger_webhook_conditions` against representative prepared data; this does not verify provider authentication or delivery. Use `list_trigger_webhook_activity`, `list_webhook_deliveries`, and `get_webhook_delivery` to inspect safe input-processing results.\n",
"digest": "sha256:fb1c710e560d91647149b59ecb5d5042491667ab50d9a453134dd20779671529",
"size": 3648
}
] as const;
17 changes: 17 additions & 0 deletions packages/api/src/mcp-event-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,20 @@ export type ReadEventOccurrencesInput = z.infer<typeof readEventOccurrencesInput


export const readEventDeliveryDiagnosticsInput = z.strictObject({ occurrenceId: z.uuid() });


const subscriptionId = z.string().regex(/^sub_[a-f0-9]{64}$/).describe("Exact subscription ID returned by events/subscribe.");
const eventIds = z.array(z.uuid().transform(id => id.toLowerCase())).min(1).max(100)
.transform(ids => [...new Set(ids)])
.describe("Exact original occurrence UUIDs from webhook data.occurrenceId; never recovery webhook IDs, an ordered range, or a batch inferred from a wake.");
export const getProcessingAcknowledgmentsInput = z.strictObject({ subscription_id: subscriptionId });
export const setProcessingAcknowledgmentsInput = z.strictObject({
subscription_id: subscriptionId,
enabled: z.boolean(),
ack_timeout_seconds: z.number().int().min(30).max(86400).optional(),
});
export const acknowledgeEventsInput = z.strictObject({
subscription_id: subscriptionId, event_ids: eventIds,
cooldown_seconds: z.number().int().min(1).max(3600).optional(),
});
export const replayUnacknowledgedEventsInput = z.strictObject({ subscription_id: subscriptionId, event_ids: eventIds });
Loading
Loading