Skip to content

Commit 7dc9e70

Browse files
author
exe.dev user
committed
Deliver durable MCP Events for Factorize
1 parent b137e82 commit 7dc9e70

28 files changed

Lines changed: 1611 additions & 30 deletions

‎EVENT_TODO_md‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# MCP Events for ChatGPT Dots
2+
3+
Use Factorize’s existing `/mcp` endpoint, durable event occurrences, and Worker alarm. An authenticated subscription starts webhook delivery for one Event definition. The first pilot summarizes events using a read tool that works with either an occurrence ID or a saved definition ID and time window.
4+
5+
## 1. Add the MCP Events contract
6+
7+
- [x] Advertise `capabilities.events` in MCP `2026-07-28` discovery and register `events/list`, `events/subscribe`, and `events/unsubscribe` on `/mcp`. Follow the request, response, routing header, and error conventions in the [OpenAI MCP Events guide](https://developers.openai.com/plugins/build/mcp-events).
8+
- [x] List the caller’s authorized Factorize Event definitions under stable protocol names derived from their definition IDs. Use the current display name and description for discovery. Advertise webhook delivery and a small payload schema for the occurrence reference and definition ID. Keep revision-specific payloads in the occurrence store.
9+
- [x] Reuse `triggers:read` and existing tenant authorization. Keep the current resource subscriptions, tools, and REST history available through their existing entry points.
10+
11+
**Acceptance criteria**
12+
13+
- A `server/discover` request advertises Events, and `events/list` returns the expected definition and webhook schema. Renaming a definition preserves its protocol name.
14+
- A caller without `triggers:read` cannot subscribe or discover tenant event definitions. Cross-tenant definition IDs cannot be used to subscribe.
15+
- Existing MCP resource subscriptions and REST occurrence history continue to pass their tests.
16+
17+
## 2. Persist subscriptions and verify callbacks
18+
19+
- [x] Add a subscription table with tenant and OAuth grant identity, the Event definition, canonical subscription arguments, callback URL, encrypted signing secret, status, and expiration. Make subscription identity deterministic so a refresh updates the existing subscription and returns its ID and `refreshBefore`.
20+
- [x] Before activation, send a signed verification challenge with a timeout and require the returned challenge to match. Require HTTPS, forbid redirects, and enforce public destination validation at connection time for verification and delivery. Validate that the chosen egress path preserves TLS hostname verification when connecting to the validated address.
21+
- [x] Make unsubscribe idempotent. Recheck current grant validity, owner membership, effective scope, subscription status, and expiration before each dispatch. Keep callback URLs, signing secrets, and payloads out of delivery logs.
22+
23+
**Acceptance criteria**
24+
25+
- A valid signed challenge activates the subscription. A wrong challenge or forbidden destination leaves it inactive.
26+
- A refresh keeps the same subscription ID and updates its expiry. A replacement signing secret is used for subsequent sends.
27+
- Unsubscribed, expired, or revoked subscriptions cannot start new sends, including sends queued before the change. An ordinary access-token refresh preserves the OAuth grant’s subscription.
28+
29+
## 3. Dispatch durable deliveries through the existing alarm
30+
31+
- [x] Add a delivery table keyed by subscription and occurrence, with status, attempt count, and next attempt time. In the `EventMatchRepository` transaction, insert deliveries for matching active subscriptions only when the occurrence is new. Define the subscribe-versus-insert boundary so new subscriptions receive new occurrences consistently.
32+
- [x] Reuse the Worker’s Durable Object alarm to dispatch after commit and sweep for due work if a wake is missed. Claim deliveries so overlapping dispatches do not normally send the same row. Keep interrupted claims recoverable.
33+
- [x] Send one compact JSON event per POST. Use the occurrence ID for both `eventId` and `webhook-id`, with the event name, occurrence timestamp, and data matching the advertised schema. Sign the message ID, signing timestamp, and exact serialized body with Standard Webhooks HMAC. Send `webhook-id`, `webhook-timestamp`, `webhook-signature`, and `X-MCP-Subscription-Id`. See the [OpenAI MCP Events guide](https://developers.openai.com/plugins/build/mcp-events) and [Standard Webhooks specification](https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md).
34+
- [x] Treat `2xx` as callback acceptance. Retry transient failures with bounded backoff and a fresh signing timestamp and signature. Treat `410` and `413` as terminal for the delivery. Record delivery status, attempts, and HTTP outcome for diagnosis.
35+
36+
**Acceptance criteria**
37+
38+
- A rolled-back occurrence produces no delivery. Repeating the same producer input creates one occurrence and one delivery per matching subscription. Other definitions and pre-subscription history produce no delivery.
39+
- A missed immediate wake leaves the row available to the alarm sweep. Retrying preserves the event ID even when the receiver could have accepted a prior attempt.
40+
- An independent receiver validates the signature against the exact body received. Each body is within OpenAI’s 256 KiB limit.
41+
42+
## 4. Add one read-only recovery tool
43+
44+
- [x] Add `read_event_occurrences` on `/mcp`. Accept either an exact `occurrenceId` or an Event definition ID with `since`, an optional cursor, and a bounded page size. Use the existing occurrence store and authorize both modes with the same tenant and scope checks as current occurrence reads.
45+
- [x] Return the stable occurrence ID, definition revision, timestamps, and payload. Order windowed reads by recorded time and a stable tie-breaker, and keep the cursor bound to the same definition and window. Use recorded time so late arrivals with older source timestamps are still discoverable.
46+
- [x] Set up the pilot Dot task with a saved Event definition ID. On a wake with an occurrence ID, fetch the exact record. If the wake provides no ID, read a recent overlapping window, page through it, and use occurrence IDs to recognize repeats where prior context is available.
47+
48+
**Acceptance criteria**
49+
50+
- Exact lookup returns the committed payload. Windowed lookup returns matching records across pages, including late arrivals, and excludes records outside the definition or time window.
51+
- The read-only tool works when both the event ID and payload are absent from the Dot’s wake. Reads do not advance or consume history. Overlapping runs may repeat a summary.
52+
53+
## 5. Add local end-to-end coverage and run a mocked Dot smoke test
54+
55+
- [x] Add one PostgreSQL-backed suite using the existing MCP request fixture. Exercise the real MCP handler, occurrence writes, and delivery dispatcher. Use an in-process receiver that independently verifies raw-body signatures, echoes challenges, and returns scripted responses. Fail unexpected outbound requests with no network fallback. Make retry rows due in the fixture or advance a controlled clock instead of sleeping through backoff.
56+
57+
| Local scenario | Pass criteria |
58+
| --- | --- |
59+
| Subscribe, deliver, and read | Discover and list the event, complete a signed challenge, fire a manual trigger, verify the signed delivery, and fetch the committed payload by occurrence ID. Repeating the trigger with its original idempotency key adds no delivery. |
60+
| Recover from an empty wake | Discard the webhook body. Use only the saved definition ID and `since` time to read two matching occurrences across pages. Include a late-arriving record and exclude one from another definition. |
61+
| Retry a transient failure | Return `503`, then `200`. Verify one persisted delivery is retried with the same event ID and a valid signature for the new attempt. |
62+
| Refresh and stop | Refresh the same subscription, then unsubscribe with a queued delivery and confirm no send. Repeat the no-send check with a revoked grant and verify another tenant cannot read the occurrence. |
63+
64+
- [x] Add small boundary checks for a failed challenge and a forbidden callback destination. Include the suite in the existing backend lane and run `npm test` on the documented validation runner after the final code change. See [Factorize validation and release instructions](docs/package-migration.md).
65+
- [x] Run the mocked Dot pilot with a saved Event definition ID. Cover a normal wake, a burst, and a wake where the mock discards the supplied payload. Verify the real MCP read call and expected summary. Record occurrence commit, callback acceptance, first tool read, and summary completion separately. See the [mock smoke record](docs/mcp-event-webhooks.md#mocked-dot-pilot).

‎docs/mcp-event-webhooks.md‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# MCP Event webhooks
2+
3+
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.
4+
5+
## Webhook egress
6+
7+
Deploy the image built from `services/mcp-webhook-egress` behind HTTPS. Set `MCP_EVENT_EGRESS_TOKEN` to the same randomly generated secret of at least 32 characters on the egress service and the Factorize Worker. Set the Worker's `MCP_EVENT_EGRESS_URL` to the service's HTTPS origin. Apply the repository's normal database migration before serving the new Worker code.
8+
9+
The Worker signs each serialized webhook body and calls the egress service's authenticated `POST /send`. The service validates all DNS answers on every outbound connection, dials a validated public address, and uses the original hostname for SNI and certificate verification. It returns only the HTTP status or a failure category, and a bounded challenge echo for verification. The service does not follow redirects or log request or response data. Subscription verification fails closed when egress is unconfigured. [MCP Events callback requirements](https://developers.openai.com/plugins/build/mcp-events), [Cloudflare production socket limitation](https://github.com/cloudflare/workerd/issues/6903)
10+
11+
Run `go test ./...` from `services/mcp-webhook-egress` to check TLS name verification using the pinned connection, redirect handling, and rejection of private destinations.
12+
13+
## Delivery and recovery
14+
15+
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.
16+
17+
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.
18+
19+
## Mocked Dot pilot
20+
21+
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.
22+
23+
The PostgreSQL suite uses the real MCP handler, occurrence writes, and dispatcher, with an in-process callback receiver that verifies signatures independently. The mock calls the real read tool and checks the visible summary. This fixture records commit observation at the successful producer response and callback acceptance at the receiver response.
24+
25+
| Wake | Commit observed (UTC) | Callback accepted (UTC) | First tool read (UTC) | Summary completed (UTC) |
26+
| --- | --- | --- | --- | --- |
27+
| Normal | 05:40:27.800 | 05:40:27.850 | 05:40:27.868 | 05:40:27.904 |
28+
| Burst of three | 05:40:27.998–05:40:28.144 | 05:40:28.183–05:40:28.226 | 05:40:28.243 | 05:40:28.412 |
29+
| Empty | 05:40:28.509 | 05:40:28.584 | 05:40:28.621 | 05:40:29.109 |
30+
31+
These timestamps are from the November 24, 2026 mock run. Set `FACTORIZE_MOCK_DOT_TIMELINE=1` when running `test/mcp-events.postgres.test.ts` to print the per-occurrence timestamps. No live ChatGPT workspace or Dot was used.
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
CREATE TABLE app.mcp_event_subscriptions (
2+
tenant_id uuid NOT NULL,
3+
id text NOT NULL,
4+
user_id uuid NOT NULL,
5+
session_version integer NOT NULL,
6+
grant_id text NOT NULL,
7+
client_id text NOT NULL,
8+
definition_id uuid NOT NULL,
9+
arguments jsonb NOT NULL,
10+
callback_url text NOT NULL,
11+
encrypted_secret text NOT NULL,
12+
secret_fingerprint text NOT NULL,
13+
verified_at timestamptz NOT NULL,
14+
previous_encrypted_secret text,
15+
rotated_at timestamptz,
16+
generation uuid NOT NULL,
17+
status text NOT NULL CHECK (status IN ('active','stopped')),
18+
expires_at timestamptz NOT NULL,
19+
PRIMARY KEY (tenant_id,id),
20+
FOREIGN KEY (tenant_id,definition_id) REFERENCES app.event_definitions(tenant_id,id) ON DELETE CASCADE
21+
);
22+
23+
CREATE INDEX mcp_event_subscriptions_active
24+
ON app.mcp_event_subscriptions(tenant_id,definition_id,expires_at) WHERE status='active';
25+
CREATE INDEX mcp_event_subscriptions_verification
26+
ON app.mcp_event_subscriptions(tenant_id,user_id,grant_id,callback_url,secret_fingerprint,verified_at DESC);
27+
28+
CREATE TABLE app.mcp_event_deliveries (
29+
tenant_id uuid NOT NULL,
30+
subscription_id text NOT NULL,
31+
occurrence_id uuid NOT NULL,
32+
generation uuid NOT NULL,
33+
status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','sending','accepted','failed','cancelled')),
34+
attempts integer NOT NULL DEFAULT 0 CHECK (attempts >= 0),
35+
next_attempt_at timestamptz NOT NULL DEFAULT clock_timestamp(),
36+
claim_id uuid,
37+
http_status integer,
38+
last_outcome text,
39+
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
40+
PRIMARY KEY (tenant_id,subscription_id,occurrence_id),
41+
FOREIGN KEY (tenant_id,subscription_id) REFERENCES app.mcp_event_subscriptions(tenant_id,id) ON DELETE CASCADE,
42+
FOREIGN KEY (tenant_id,occurrence_id) REFERENCES app.event_occurrences(tenant_id,id) ON DELETE CASCADE
43+
);
44+
45+
CREATE INDEX mcp_event_deliveries_due ON app.mcp_event_deliveries(next_attempt_at,tenant_id,subscription_id,occurrence_id)
46+
WHERE status IN ('pending','sending');
47+
CREATE INDEX mcp_event_deliveries_occurrence ON app.mcp_event_deliveries(tenant_id,occurrence_id);
48+
CREATE INDEX event_occurrences_recorded ON app.event_occurrences(tenant_id,definition_id,created_at,id);

‎packages/api/src/alarm-coordinator.ts‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@ import { databaseFor } from "./postgres/database";
55
import { cleanupAgentResponses } from "./agent-api";
66
import { maintainProxyOperations } from "./proxy-operations";
77
import type { Env } from "./types";
8+
import { dispatchMcpEvents, mcpEventDispatchBatchSize } from "./mcp-event-subscriptions";
89

910
/** Wakes provider and schedule Triggers and maintains bounded proxy records. */
1011
export class AlarmCoordinator extends DurableObject<Env> {
12+
protected eventEnv(): Env { return this.env; }
1113
async fetch(request: Request): Promise<Response> {
1214
const path = new URL(request.url).pathname;
1315
if (request.method === "POST" && path === "/operation") {
@@ -20,20 +22,29 @@ export class AlarmCoordinator extends DurableObject<Env> {
2022
if (await this.ctx.storage.getAlarm() === null) await this.ctx.storage.setAlarm(Date.now() + 100);
2123
return Response.json({ scheduled: true });
2224
}
25+
if (request.method === "POST" && path === "/mcp-events") {
26+
await this.schedule(100);
27+
return Response.json({ scheduled: true });
28+
}
2329
if (request.method !== "POST" || path !== "/wake") return new Response("Not found", { status: 404 });
2430
await this.schedule(); return Response.json({ scheduled: true });
2531
}
2632
async alarm(): Promise<void> {
2733
const operation = await this.ctx.storage.get<{ tenantId: string; operationId: string }>("operation");
2834
if (operation) { await processProxyOperation(this.env, operation.tenantId, operation.operationId); return; }
35+
let backlog = false;
2936
try {
30-
await new AutomationScheduler(databaseFor(this.env), this.env).process();
31-
await maintainProxyOperations(this.env);
32-
await cleanupAgentResponses(this.env);
33-
} finally { await this.schedule(); }
37+
try {
38+
await new AutomationScheduler(databaseFor(this.env), this.env).process();
39+
await maintainProxyOperations(this.env);
40+
await cleanupAgentResponses(this.env);
41+
} finally {
42+
backlog = await dispatchMcpEvents(this.eventEnv()) === mcpEventDispatchBatchSize;
43+
}
44+
} finally { await this.schedule(backlog ? 100 : 60_000); }
3445
}
35-
private async schedule() {
36-
const current = await this.ctx.storage.getAlarm(), desired = Date.now() + 60_000;
46+
private async schedule(delay = 60_000) {
47+
const current = await this.ctx.storage.getAlarm(), desired = Date.now() + delay;
3748
if (current === null || current > desired) await this.ctx.storage.setAlarm(desired);
3849
}
3950
}

0 commit comments

Comments
 (0)