diff --git a/docs/mcp-event-webhooks.md b/docs/mcp-event-webhooks.md index 9184abc7..3fd342f3 100644 --- a/docs/mcp-event-webhooks.md +++ b/docs/mcp-event-webhooks.md @@ -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. diff --git a/packages/api/migrations/0106_mcp_processing_acknowledgments.sql b/packages/api/migrations/0106_mcp_processing_acknowledgments.sql new file mode 100644 index 00000000..f5031d11 --- /dev/null +++ b/packages/api/migrations/0106_mcp_processing_acknowledgments.sql @@ -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'; diff --git a/packages/api/src/alarm-coordinator.ts b/packages/api/src/alarm-coordinator.ts index 110779c1..aa6f86c3 100644 --- a/packages/api/src/alarm-coordinator.ts +++ b/packages/api/src/alarm-coordinator.ts @@ -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 { @@ -41,7 +41,10 @@ export class AlarmCoordinator extends DurableObject { } 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; diff --git a/packages/api/src/api-service.ts b/packages/api/src/api-service.ts index 4967d5f2..fc57d076 100644 --- a/packages/api/src/api-service.ts +++ b/packages/api/src/api-service.ts @@ -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"; @@ -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, @@ -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) { + await this.authorize("triggers:read"); + return setProcessingAcknowledgments(this.env, this.auth, input); + } + async acknowledgeEventProcessing(input: z.infer) { + 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(); diff --git a/packages/api/src/generated/builtin-skills.ts b/packages/api/src/generated/builtin-skills.ts index f0a8e2e2..79f45da5 100644 --- a/packages/api/src/generated/builtin-skills.ts +++ b/packages/api/src/generated/builtin-skills.ts @@ -1,5 +1,5 @@ // 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", @@ -7,8 +7,8 @@ export const builtinSkillDocuments = [ "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; diff --git a/packages/api/src/mcp-event-contracts.ts b/packages/api/src/mcp-event-contracts.ts index 8e591f74..d07dc618 100644 --- a/packages/api/src/mcp-event-contracts.ts +++ b/packages/api/src/mcp-event-contracts.ts @@ -68,3 +68,20 @@ export type ReadEventOccurrencesInput = z.infer 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 }); diff --git a/packages/api/src/mcp-event-subscriptions.ts b/packages/api/src/mcp-event-subscriptions.ts index 87ff7890..2a67efb8 100644 --- a/packages/api/src/mcp-event-subscriptions.ts +++ b/packages/api/src/mcp-event-subscriptions.ts @@ -2,16 +2,18 @@ import { ProtocolError, ProtocolErrorCode } from "@modelcontextprotocol/server"; import type { z } from "zod"; import { normalizeScopes } from "./access-tokens"; import { decrypt, encrypt } from "./crypto"; -import { eventDefinitionId, deliveryEventName, type subscribeEventInput, type unsubscribeEventInput } from "./mcp-event-contracts"; +import { eventDefinitionId, deliveryEventName, type subscribeEventInput, type unsubscribeEventInput, type setProcessingAcknowledgmentsInput, type acknowledgeEventsInput } 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"; +import { wakeMcpDeliveries } from "./postgres/event-match-repository"; import { lockEventOutbox, lockMcpEventGrant } from "./postgres/mcp-event-outbox"; import type { Env, OAuthProps } from "./types"; const defaultLifetime = 24 * 60 * 60 * 1000; const maxLifetime = 7 * defaultLifetime; const maxAttempts = 5; +const maxRecoveryAttempts = 4; const retryInterval = 15_000; type Principal = { @@ -134,6 +136,8 @@ export async function subscribeMcpEvent(env: Env, auth: OAuthProps, input: z.inf rotated_at=CASE WHEN s.status<>'active' OR s.expires_at<=clock_timestamp() THEN NULL WHEN s.secret_fingerprint<>excluded.secret_fingerprint THEN clock_timestamp() ELSE s.rotated_at END, encrypted_secret=excluded.encrypted_secret, secret_fingerprint=excluded.secret_fingerprint, verified_at=excluded.verified_at, + ack_epoch=CASE WHEN s.status='active' AND s.expires_at>clock_timestamp() THEN s.ack_epoch END, + cooldown_until=CASE WHEN s.status='active' AND s.expires_at>clock_timestamp() THEN s.cooldown_until END, generation=CASE WHEN s.status='active' AND s.expires_at>clock_timestamp() THEN s.generation ELSE excluded.generation END, status='active', expires_at=clock_timestamp()+$13*interval '1 millisecond' RETURNING expires_at`, @@ -147,12 +151,145 @@ export async function subscribeMcpEvent(env: Env, auth: OAuthProps, input: z.inf export async function unsubscribeMcpEvent(env: Env, auth: OAuthProps, input: z.infer) { const { id } = await subscriptionKey(auth, input); await databaseFor(env).pool.query( - `UPDATE app.mcp_event_subscriptions SET status='stopped', previous_encrypted_secret=NULL, rotated_at=NULL + `UPDATE app.mcp_event_subscriptions SET status='stopped', previous_encrypted_secret=NULL, rotated_at=NULL, cooldown_until=NULL WHERE tenant_id=$1 AND id=$2 AND status='active'`, [auth.tenantId, id], ); return {}; } +type ProcessingSubscription = Principal & { + id: string; definition_id: string; generation: string; + status: string; expires_at: Date; + ack_epoch: string | null; ack_timeout_seconds: number; cooldown_until: Date | null; +}; + +async function withProcessingSubscription(env: Env, auth: OAuthProps, id: string, + action: (sql: DatabaseClient, subscription: ProcessingSubscription) => Promise) { + if (auth.authMethod !== "oauth" || !auth.oauthGrantId || !auth.oauthClientId || + !auth.scopes.includes("triggers:read")) throw forbidden(); + const principal: Principal = { + tenant_id: auth.tenantId, user_id: auth.userId, grant_id: auth.oauthGrantId, + client_id: auth.oauthClientId, session_version: auth.sessionVersion, + }; + const scoped = [auth.tenantId, id, auth.userId, auth.oauthGrantId, auth.oauthClientId]; + const owns = "tenant_id=$1 AND id=$2 AND user_id=$3 AND grant_id=$4 AND client_id=$5"; + return databaseFor(env).transaction(async sql => { + await lockMcpEventGrant(sql, auth.tenantId, auth.oauthGrantId!); + const { rows: [current] } = await sql.query<{ definition_id: string }>( + `SELECT definition_id FROM app.mcp_event_subscriptions WHERE ${owns}`, scoped, + ); + if (!current) throw forbidden(); + await lockEventOutbox(sql, auth.tenantId, current.definition_id); + const { rows: [row] } = await sql.query( + `SELECT * FROM app.mcp_event_subscriptions WHERE ${owns} AND status='active' + AND expires_at>clock_timestamp() AND session_version=$6 FOR NO KEY UPDATE`, + [...scoped, auth.sessionVersion], + ); + const scopes = row && await activeGrantScopes(env, principal); + if (!scopes || !await authorized(sql, principal, scopes)) throw forbidden(); + return action(sql, row); + }); +} + +function processingSettings(row: ProcessingSubscription) { + return { + subscriptionId: row.id, enabled: row.ack_epoch !== null, + ackTimeoutSeconds: row.ack_timeout_seconds, cooldownUntil: row.cooldown_until?.toISOString() ?? null, + }; +} + +export async function getProcessingAcknowledgments(env: Env, auth: OAuthProps, subscriptionId: string) { + return withProcessingSubscription(env, auth, subscriptionId, async (_sql, row) => processingSettings(row)); +} + +export async function setProcessingAcknowledgments(env: Env, auth: OAuthProps, input: z.infer) { + if (!input.enabled && input.ack_timeout_seconds !== undefined) { + throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Set an acknowledgment timeout only when enabling acknowledgments."); + } + const result = await withProcessingSubscription(env, auth, input.subscription_id, async (sql, row) => { + if (!input.enabled && row.ack_epoch) { + await sql.query(`UPDATE app.mcp_event_deliveries SET ack_state='waived',ack_due_at=NULL, + ack_updated_at=clock_timestamp(),recovery_event_id=NULL, + claim_id=CASE WHEN status='accepted' THEN NULL ELSE claim_id END + WHERE tenant_id=$1 AND subscription_id=$2 AND generation=$3 AND ack_epoch=$4 + AND ack_state IN ('pending','awaiting_ack','exhausted')`, [row.tenant_id, row.id, row.generation, row.ack_epoch]); + } + const { rows: [updated] } = await sql.query( + `UPDATE app.mcp_event_subscriptions SET + ack_epoch=CASE WHEN $3 THEN COALESCE(ack_epoch,gen_random_uuid()) ELSE NULL END, + ack_timeout_seconds=COALESCE($4,ack_timeout_seconds), + cooldown_until=CASE WHEN $3 THEN cooldown_until END + WHERE tenant_id=$1 AND id=$2 RETURNING *`, + [row.tenant_id, row.id, input.enabled, input.ack_timeout_seconds ?? null], + ); + return processingSettings(updated); + }); + await wakeMcpDeliveries(env).catch(() => {}); + return result; +} + +export async function acknowledgeEvents(env: Env, auth: OAuthProps, input: z.infer) { + const result = await withProcessingSubscription(env, auth, input.subscription_id, async (sql, row) => { + const { rows } = await sql.query<{ occurrence_id: string }>( + `UPDATE app.mcp_event_deliveries SET ack_state='processed',ack_due_at=NULL,ack_updated_at=clock_timestamp(), + recovery_event_id=NULL,claim_id=CASE WHEN status='accepted' THEN NULL ELSE claim_id END + WHERE tenant_id=$1 AND subscription_id=$2 AND generation=$3 AND ack_epoch=$4 + AND occurrence_id=ANY($5::uuid[]) AND ack_state IN ('pending','awaiting_ack','exhausted') + AND (last_outcome IS NOT NULL OR status='accepted') RETURNING occurrence_id`, + [row.tenant_id, row.id, row.generation, row.ack_epoch, input.event_ids], + ); + const changed = new Set(rows.map(item => item.occurrence_id)); + const { rows: processed } = await sql.query<{ occurrence_id: string }>( + `SELECT occurrence_id FROM app.mcp_event_deliveries + WHERE tenant_id=$1 AND subscription_id=$2 AND generation=$3 AND occurrence_id=ANY($4::uuid[]) + AND ack_state='processed'`, [row.tenant_id, row.id, row.generation, input.event_ids], + ); + let cooldownUntil = row.cooldown_until; + if (changed.size && input.cooldown_seconds) { + const { rows: [updated] } = await sql.query<{ cooldown_until: Date }>( + `UPDATE app.mcp_event_subscriptions + SET cooldown_until=GREATEST(cooldown_until,clock_timestamp()+make_interval(secs=>$3)) + WHERE tenant_id=$1 AND id=$2 RETURNING cooldown_until`, + [row.tenant_id, row.id, input.cooldown_seconds], + ); + cooldownUntil = updated.cooldown_until; + } + const done = new Set(processed.map(item => item.occurrence_id)); + return { + subscriptionId: row.id, acknowledged: input.event_ids.filter(id => changed.has(id)), + alreadyAcknowledged: input.event_ids.filter(id => done.has(id) && !changed.has(id)), + notAcknowledged: input.event_ids.filter(id => !done.has(id)), + cooldownUntil: cooldownUntil?.toISOString() ?? null, + }; + }); + await wakeMcpDeliveries(env).catch(() => {}); + return result; +} + +export async function replayUnacknowledgedEvents(env: Env, auth: OAuthProps, subscriptionId: string, eventIds: string[]) { + const result = await withProcessingSubscription(env, auth, subscriptionId, async (sql, row) => { + const { rows } = await sql.query<{ occurrence_id: string }>( + `UPDATE app.mcp_event_deliveries SET + next_attempt_at=CASE WHEN status='failed' THEN clock_timestamp() ELSE next_attempt_at END, + attempts=CASE WHEN status='failed' THEN 0 ELSE attempts END, + status=CASE WHEN status='failed' THEN 'pending' ELSE status END, + ack_due_at=CASE WHEN status='accepted' THEN clock_timestamp() END,ack_updated_at=clock_timestamp(), + recovery_attempts=CASE WHEN ack_state='exhausted' THEN 0 ELSE recovery_attempts END, + ack_state=CASE WHEN status='accepted' THEN 'awaiting_ack' ELSE 'pending' END + WHERE tenant_id=$1 AND subscription_id=$2 AND generation=$3 AND ack_epoch=$4 + AND occurrence_id=ANY($5::uuid[]) AND claim_id IS NULL AND ( + (status='accepted' AND (ack_state='exhausted' OR (ack_state='awaiting_ack' AND ack_due_at>clock_timestamp()))) + OR (status='failed' AND ack_state='pending') + ) + RETURNING occurrence_id`, [row.tenant_id, row.id, row.generation, row.ack_epoch, eventIds], + ); + const replay = new Set(rows.map(item => item.occurrence_id)); + return { subscriptionId, queued: eventIds.filter(id => replay.has(id)), notQueued: eventIds.filter(id => !replay.has(id)) }; + }); + await wakeMcpDeliveries(env).catch(() => {}); + return result; +} + type Claim = { tenant_id: string; subscription_id: string; @@ -160,33 +297,60 @@ type Claim = { claim_id: string; generation: string; attempts: number; + recovery: boolean; + recovery_event_id: string | null; + recovery_attempts: number; }; -type Subscription = Principal & { - definition_id: string; +type Subscription = ProcessingSubscription & { arguments: unknown; - generation: string; - status: string; - expires_at: Date; callback_url: string; encrypted_secret: string; previous_encrypted_secret: string | null; rotated_at: Date | null; }; +const deliveryReady = `( + (d.status IN ('pending','sending') AND d.ack_state IS DISTINCT FROM 'processed') + OR (d.status='accepted' AND d.ack_state='awaiting_ack') +)`; +const deliveryDue = `CASE WHEN d.status='accepted' THEN d.ack_due_at ELSE d.next_attempt_at END`; +const pacedDue = `CASE WHEN s.generation=d.generation AND s.status='active' AND s.expires_at>statement_timestamp() + THEN GREATEST(${deliveryDue},s.cooldown_until) ELSE ${deliveryDue} END`; + async function claimDelivery(sql: DatabaseClient) { const { rows: [claim] } = await sql.query( `WITH due AS ( - SELECT tenant_id,subscription_id,occurrence_id FROM app.mcp_event_deliveries - WHERE status IN ('pending','sending') AND next_attempt_at<=statement_timestamp() - ORDER BY next_attempt_at,tenant_id,subscription_id,occurrence_id LIMIT 1 FOR UPDATE SKIP LOCKED + SELECT d.tenant_id,d.subscription_id,d.occurrence_id,(d.status='accepted') AS recovery + FROM app.mcp_event_deliveries d JOIN app.mcp_event_subscriptions s + ON (s.tenant_id,s.id)=(d.tenant_id,d.subscription_id) + WHERE ${deliveryReady} AND ${pacedDue}<=statement_timestamp() + ORDER BY ${pacedDue},d.tenant_id,d.subscription_id,d.occurrence_id LIMIT 1 FOR UPDATE OF d SKIP LOCKED ) - UPDATE app.mcp_event_deliveries d SET status='sending',attempts=least(attempts+1,${maxAttempts + 1}),claim_id=gen_random_uuid(),next_attempt_at=clock_timestamp()+interval '60 seconds',updated_at=clock_timestamp() + UPDATE app.mcp_event_deliveries d SET + status=CASE WHEN due.recovery THEN d.status ELSE 'sending' END, + attempts=CASE WHEN due.recovery THEN d.attempts ELSE least(d.attempts+1,${maxAttempts + 1}) END, + recovery_attempts=CASE WHEN due.recovery THEN least(d.recovery_attempts+1,${maxRecoveryAttempts + 1}) ELSE d.recovery_attempts END, + recovery_event_id=CASE WHEN due.recovery THEN COALESCE(d.recovery_event_id,gen_random_uuid()) ELSE NULL END, + ack_due_at=CASE WHEN due.recovery THEN clock_timestamp()+interval '60 seconds' ELSE d.ack_due_at END, + claim_id=gen_random_uuid(), + next_attempt_at=CASE WHEN due.recovery THEN d.next_attempt_at ELSE clock_timestamp()+interval '60 seconds' END, + updated_at=CASE WHEN due.recovery THEN d.updated_at ELSE clock_timestamp() END FROM due WHERE (d.tenant_id,d.subscription_id,d.occurrence_id)=(due.tenant_id,due.subscription_id,due.occurrence_id) - RETURNING d.tenant_id,d.subscription_id,d.occurrence_id,d.claim_id,d.generation,d.attempts`, + RETURNING d.tenant_id,d.subscription_id,d.occurrence_id,d.claim_id,d.generation,d.attempts, + due.recovery,d.recovery_event_id,d.recovery_attempts`, ); return claim; } +export async function nextMcpDeliveryDelay(env: Env) { + const { rows: [row] } = await databaseFor(env).pool.query<{ due_at: Date | null }>( + `SELECT min(${pacedDue}) AS due_at FROM app.mcp_event_deliveries d JOIN app.mcp_event_subscriptions s + ON (s.tenant_id,s.id)=(d.tenant_id,d.subscription_id) + WHERE ${deliveryReady} AND (d.ack_epoch IS NOT NULL OR s.cooldown_until IS NOT NULL)`, + ); + return row?.due_at ? Math.max(100, row.due_at.getTime() - Date.now()) : 60_000; +} + function subscriptionActive(subscription: Subscription, claim: Claim) { return subscription.status === "active" && subscription.generation === claim.generation && subscription.expires_at.getTime() > Date.now(); } @@ -202,37 +366,81 @@ function deliveryOutcome(outcome: WebhookOutcome, attempts: number) { async function dispatchClaim(env: Env, claim: Claim, now: () => number) { const db = databaseFor(env); const key = [claim.tenant_id, claim.subscription_id, claim.occurrence_id, claim.claim_id]; - const finish = (sql: DatabaseClient, status: string, attempts: number, reason: string, httpStatus?: number) => sql.query( - `UPDATE app.mcp_event_deliveries SET status=$5,claim_id=NULL,attempts=$6,last_outcome=$7,http_status=$8, - next_attempt_at=clock_timestamp()+$9*interval '1 millisecond',updated_at=clock_timestamp() - WHERE tenant_id=$1 AND subscription_id=$2 AND occurrence_id=$3 AND claim_id=$4`, - [...key, status, attempts, reason, httpStatus ?? null, retryInterval * 2 ** Math.max(attempts - 1, 0)], - ); await db.transaction(async sql => { const { rows: [subscription] } = await sql.query( `SELECT * FROM app.mcp_event_subscriptions WHERE tenant_id=$1 AND id=$2 FOR NO KEY UPDATE`, key.slice(0, 2), ); if (!subscription) return; - const { rows: [record] } = await sql.query<{ occurred_at: Date; definition_id: string }>( - `SELECT o.occurred_at,o.definition_id FROM app.mcp_event_deliveries d + const { rows: [record] } = await sql.query<{ occurred_at: Date; definition_id: string; ack_epoch: string | null; ack_state: string | null }>( + `SELECT o.occurred_at,o.definition_id,d.ack_epoch,d.ack_state FROM app.mcp_event_deliveries d JOIN app.event_occurrences o ON o.tenant_id=d.tenant_id AND o.id=d.occurrence_id WHERE d.tenant_id=$1 AND d.subscription_id=$2 AND d.occurrence_id=$3 AND d.claim_id=$4 FOR UPDATE OF d`, key, ); if (!record) return; + const optIn = record.ack_epoch !== null && subscription.ack_epoch === record.ack_epoch; + const finishOriginal = (status: string, attempts: number, reason: string, httpStatus?: number) => sql.query( + `UPDATE app.mcp_event_deliveries SET status=$5,claim_id=NULL,attempts=$6,last_outcome=$7,http_status=$8, + next_attempt_at=clock_timestamp()+$9*interval '1 millisecond',updated_at=clock_timestamp(), + ack_state=CASE WHEN ack_state='pending' AND $5='cancelled' THEN 'cancelled' + WHEN ack_state='pending' AND $5='accepted' AND $10 THEN 'awaiting_ack' ELSE ack_state END, + ack_due_at=CASE WHEN ack_state='pending' AND $5='accepted' AND $10 + THEN clock_timestamp()+make_interval(secs=>$11) ELSE ack_due_at END, + ack_updated_at=CASE WHEN ack_state='pending' AND ($5='cancelled' OR ($5='accepted' AND $10)) + THEN clock_timestamp() ELSE ack_updated_at END + WHERE tenant_id=$1 AND subscription_id=$2 AND occurrence_id=$3 AND claim_id=$4`, + [...key, status, attempts, reason, httpStatus ?? null, retryInterval * 2 ** Math.max(attempts - 1, 0), + optIn, subscription.ack_timeout_seconds], + ); + const finishRecovery = (state: "awaiting_ack" | "cancelled" | "exhausted", delaySeconds = 0, retainId = false) => + sql.query(`UPDATE app.mcp_event_deliveries SET claim_id=NULL,ack_state=$5,ack_updated_at=clock_timestamp(), + ack_due_at=CASE WHEN $5='awaiting_ack' THEN clock_timestamp()+make_interval(secs=>$6) END, + recovery_event_id=CASE WHEN $7 THEN recovery_event_id END + WHERE tenant_id=$1 AND subscription_id=$2 AND occurrence_id=$3 AND claim_id=$4 AND ack_state='awaiting_ack'`, + [...key, state, delaySeconds, retainId]); + async function cancel(reason: string) { + if (claim.recovery) { + await finishRecovery("cancelled"); + } else { + await finishOriginal("cancelled", claim.attempts - 1, reason); + } + } + if (record.ack_state === "processed") { + await sql.query(`UPDATE app.mcp_event_deliveries SET claim_id=NULL + WHERE tenant_id=$1 AND subscription_id=$2 AND occurrence_id=$3 AND claim_id=$4`, key); + return; + } if (!subscriptionActive(subscription, claim)) { - await finish(sql, "cancelled", claim.attempts - 1, "subscription_inactive"); + await cancel("subscription_inactive"); + return; + } + if (claim.recovery && (!optIn || record.ack_state !== "awaiting_ack")) { + await finishRecovery("cancelled"); return; } - if (claim.attempts > maxAttempts) { - await finish(sql, "failed", maxAttempts, "claim_interrupted"); + if (subscription.cooldown_until && subscription.cooldown_until.getTime() > Date.now()) { + await sql.query(`UPDATE app.mcp_event_deliveries SET claim_id=NULL, + status=CASE WHEN $5 THEN status ELSE 'pending' END, + attempts=CASE WHEN $5 THEN attempts ELSE greatest(attempts-1,0) END, + recovery_attempts=CASE WHEN $5 THEN greatest(recovery_attempts-1,0) ELSE recovery_attempts END, + ack_due_at=CASE WHEN $5 THEN clock_timestamp() ELSE ack_due_at END, + next_attempt_at=CASE WHEN $5 THEN next_attempt_at ELSE clock_timestamp() END + WHERE tenant_id=$1 AND subscription_id=$2 AND occurrence_id=$3 AND claim_id=$4`, [...key, claim.recovery]); + return; + } + if (claim.recovery && claim.recovery_attempts > maxRecoveryAttempts) { + await finishRecovery("exhausted"); + return; + } + if (!claim.recovery && claim.attempts > maxAttempts) { + await finishOriginal("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"); + await cancel("event_mismatch"); return; } - const attempts = claim.attempts; + const eventId = claim.recovery ? claim.recovery_event_id! : claim.occurrence_id; let result: WebhookOutcome; try { const secrets = [await decrypt(subscription.encrypted_secret, env.CREDENTIAL_ENCRYPTION_KEY)]; @@ -241,15 +449,15 @@ async function dispatchClaim(env: Env, claim: Claim, now: () => number) { } const scopes = await activeGrantScopes(env, subscription); if (!scopes || !await authorized(sql, subscription, scopes) || !subscriptionActive(subscription, claim)) { - await finish(sql, "cancelled", claim.attempts - 1, "authorization_inactive"); + await cancel("authorization_inactive"); return; } result = await sendMcpWebhook(env.APP_ORIGIN, { url: subscription.callback_url, subscriptionId: claim.subscription_id, - id: claim.occurrence_id, + id: eventId, payload: { - eventId: claim.occurrence_id, name, timestamp: record.occurred_at.toISOString(), + eventId, name, timestamp: record.occurred_at.toISOString(), data: { occurrenceId: claim.occurrence_id, definitionId: record.definition_id }, cursor: null, }, secrets, @@ -258,8 +466,22 @@ async function dispatchClaim(env: Env, claim: Claim, now: () => number) { } catch { result = { reason: "connection_failed" }; } - const outcome = deliveryOutcome(result, attempts); - await finish(sql, outcome.status, attempts, outcome.reason, result.status); + if (claim.recovery) { + const delivered = callbackAccepted(result); + const retryable = deliveryOutcome(result, claim.recovery_attempts).status === "pending"; + if (delivered) { + const delay = subscription.ack_timeout_seconds + + Math.min(3600, subscription.ack_timeout_seconds * (2 ** (claim.recovery_attempts - 1) - 1)); + await finishRecovery("awaiting_ack", delay); + } else if (retryable && claim.recovery_attempts < maxRecoveryAttempts) { + await finishRecovery("awaiting_ack", 15 * 2 ** (claim.recovery_attempts - 1), true); + } else { + await finishRecovery("exhausted"); + } + } else { + const outcome = deliveryOutcome(result, claim.attempts); + await finishOriginal(outcome.status, claim.attempts, outcome.reason, result.status); + } }); } diff --git a/packages/api/src/postgres/event-definition-repository.ts b/packages/api/src/postgres/event-definition-repository.ts index c52dc270..f240392f 100644 --- a/packages/api/src/postgres/event-definition-repository.ts +++ b/packages/api/src/postgres/event-definition-repository.ts @@ -34,6 +34,10 @@ interface DeliveryDiagnosticRow { http_status: number | null; updated_at: Date; next_attempt_at: Date; + ack_state: string | null; + ack_due_at: Date | null; + ack_updated_at: Date | null; + recovery_attempts: number; } const deliveryOutcomeCodes = new Set([ "accepted", "http_error", "connection_failed", "timeout", "forbidden_destination", @@ -83,9 +87,9 @@ export class EventDefinitionRepository { // 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 + `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,d.ack_state,d.ack_due_at,d.ack_updated_at,d.recovery_attempts FROM app.event_occurrences o LEFT JOIN LATERAL ( - SELECT subscription_id,status,attempts,last_outcome,http_status,updated_at,next_attempt_at + SELECT subscription_id,status,attempts,last_outcome,http_status,updated_at,next_attempt_at,ack_state,ack_due_at,ack_updated_at,recovery_attempts 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 @@ -102,6 +106,11 @@ export class EventDefinitionRepository { 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, + ...(row.ack_state === null ? {} : { processing: { + state: row.ack_state, recoveryAttempts: Math.min(row.recovery_attempts, 4), + updatedAt: row.ack_updated_at?.toISOString() ?? null, + nextRecoveryAt: row.ack_due_at?.toISOString() ?? null, + } }), }]); return { occurrenceId: rows[0].occurrence_id, diff --git a/packages/api/src/postgres/mcp-event-outbox.ts b/packages/api/src/postgres/mcp-event-outbox.ts index c52ec86c..148fcddc 100644 --- a/packages/api/src/postgres/mcp-event-outbox.ts +++ b/packages/api/src/postgres/mcp-event-outbox.ts @@ -7,8 +7,9 @@ export async function lockEventOutbox(sql: DatabaseClient, tenantId: string, def } export async function enqueueMcpDeliveries(sql: DatabaseClient, tenantId: string, definitionId: string, occurrenceId: string) { - const result = await sql.query(`INSERT INTO app.mcp_event_deliveries(tenant_id,subscription_id,occurrence_id,generation) - SELECT tenant_id,id,$3,generation FROM app.mcp_event_subscriptions + const result = await sql.query(`INSERT INTO app.mcp_event_deliveries(tenant_id,subscription_id,occurrence_id,generation,ack_epoch,ack_state,ack_updated_at) + SELECT tenant_id,id,$3,generation,ack_epoch,CASE WHEN ack_epoch IS NOT NULL THEN 'pending' END, + CASE WHEN ack_epoch IS NOT NULL THEN clock_timestamp() END FROM app.mcp_event_subscriptions WHERE tenant_id=$1 AND definition_id=$2 AND status='active' AND expires_at>clock_timestamp()`, [tenantId, definitionId, occurrenceId]); return !!result.rowCount; diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index a636c227..90abfbd8 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -150,6 +150,9 @@ export const mcpEventSubscriptions = app.table("mcp_event_subscriptions", { clientId: text("client_id").notNull(), definitionId: uuid("definition_id").notNull(), arguments: jsonb("arguments").$type>().notNull(), + ackEpoch: uuid("ack_epoch"), + ackTimeoutSeconds: integer("ack_timeout_seconds").notNull().default(300), + cooldownUntil: timestamp("cooldown_until", { withTimezone: true }), callbackUrl: text("callback_url").notNull(), encryptedSecret: text("encrypted_secret").notNull(), secretFingerprint: text("secret_fingerprint").notNull(), @@ -163,6 +166,7 @@ export const mcpEventSubscriptions = app.table("mcp_event_subscriptions", { primaryKey({ columns: [t.tenantId, t.id] }), foreignKey({ columns: [t.tenantId, t.definitionId], foreignColumns: [eventDefinitions.tenantId, eventDefinitions.id] }).onDelete("cascade"), check("mcp_event_subscriptions_status_check", sql`${t.status} IN ('active','stopped')`), + check("mcp_event_subscriptions_ack_timeout_seconds_check", sql`${t.ackTimeoutSeconds} BETWEEN 30 AND 86400`), index("mcp_event_subscriptions_active").on(t.tenantId, t.definitionId, t.expiresAt).where(sql`${t.status}='active'`), index("mcp_event_subscriptions_verification").on(t.tenantId, t.userId, t.grantId, t.callbackUrl, t.secretFingerprint, t.verifiedAt.desc()), ]); @@ -175,6 +179,12 @@ export const mcpEventDeliveries = app.table("mcp_event_deliveries", { status: text("status", { enum: ["pending", "sending", "accepted", "failed", "cancelled"] }).notNull().default("pending"), attempts: integer("attempts").notNull().default(0), nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull().default(sql`clock_timestamp()`), + ackEpoch: uuid("ack_epoch"), + ackState: text("ack_state", { enum: ["pending", "awaiting_ack", "processed", "waived", "exhausted", "cancelled"] }), + ackDueAt: timestamp("ack_due_at", { withTimezone: true }), + ackUpdatedAt: timestamp("ack_updated_at", { withTimezone: true }), + recoveryEventId: uuid("recovery_event_id"), + recoveryAttempts: integer("recovery_attempts").notNull().default(0), claimId: uuid("claim_id"), httpStatus: integer("http_status"), lastOutcome: text("last_outcome"), @@ -188,6 +198,10 @@ export const mcpEventDeliveries = app.table("mcp_event_deliveries", { index("mcp_event_deliveries_due").on(t.nextAttemptAt, t.tenantId, t.subscriptionId, t.occurrenceId) .where(sql`${t.status} IN ('pending','sending')`), index("mcp_event_deliveries_occurrence").on(t.tenantId, t.occurrenceId), + check("mcp_event_deliveries_ack_state_check", sql`${t.ackState} IN ('pending','awaiting_ack','processed','waived','exhausted','cancelled')`), + check("mcp_event_deliveries_recovery_attempts_check", sql`${t.recoveryAttempts} >= 0`), + index("mcp_event_deliveries_ack_due").on(t.ackDueAt, t.tenantId, t.subscriptionId, t.occurrenceId) + .where(sql`${t.ackState}='awaiting_ack'`), ]); export const triggerMatches = app.table("trigger_matches", { tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), triggerId: uuid("trigger_id").notNull(), triggerRevision: integer("trigger_revision").notNull(), sourceIdentity: text("source_identity").notNull(), deduplicationKey: text("deduplication_key").notNull(), evidence: jsonb("evidence").notNull(), outcome: text("outcome").$type<"matched"|"pending"|"excluded"|"failed">().notNull(), pendingReason: text("pending_reason"), occurrenceId: uuid("occurrence_id"), createdAt: createdAt(), updatedAt: updatedAt(), diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index 458f8276..4baf1d40 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -1,4 +1,4 @@ -import { listEventsInput, readEventDeliveryDiagnosticsInput, readEventOccurrencesInput, subscribeEventInput, unsubscribeEventInput } from "./mcp-event-contracts"; +import { listEventsInput, getProcessingAcknowledgmentsInput, setProcessingAcknowledgmentsInput, acknowledgeEventsInput, replayUnacknowledgedEventsInput, 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,9 +209,21 @@ 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)); + const processingAction = async (action: () => Promise) => { + try { return await action(); } + catch (error) { + if (error instanceof ProtocolError && error.code === -32024) throw new ServiceError(403, "not_authorized", "An active subscription for this OAuth grant is required."); + if (error instanceof ProtocolError && error.code === ProtocolErrorCode.InvalidParams) throw new ServiceError(400, "invalid_request", error.message); + throw error; + } + }; + tool("get_event_processing_acknowledgments", "Read optional processing acknowledgment settings for your exact active MCP subscription. Off by default; independent of HTTP receipt and client-side throttling.", getProcessingAcknowledgmentsInput, (input: z.infer) => processingAction(() => service.getEventProcessing(input.subscription_id)), false, true); + tool("set_event_processing_acknowledgments", "Opt in to processing acknowledgments for future occurrences on your exact MCP subscription. Turning off waives unresolved acknowledgments and clears cooldown; does not alter standard MCP subscription behavior.", setProcessingAcknowledgmentsInput, (input: z.infer) => processingAction(() => service.setEventProcessing(input))); + tool("acknowledge_events", "After durable completion or handoff, acknowledge exact original data.occurrenceId UUIDs on your opted-in subscription. Never pass a recovery wake ID or assume an ordered range. Ack successful work promptly; optional cooldown applies only when a new ID is acknowledged, not on retries. Keep client-local pacing and don't drop unfinished work.", acknowledgeEventsInput, (input: z.infer) => processingAction(() => service.acknowledgeEventProcessing(input))); + tool("replay_unacknowledged_events", "Queue exact unresolved original occurrence IDs on your opted-in subscription, without duplicating business events or bypassing cooldown. Recovery wakes can have fresh event IDs; deduplicate by their original data.occurrenceId.", replayUnacknowledgedEventsInput, (input: z.infer) => processingAction(() => service.replayEventProcessing(input.subscription_id, input.event_ids))); + tool("read_event_delivery_diagnostics", "Read separate safe HTTP and optional processing diagnostics for one original occurrence ID. A 2xx receipt is not acknowledgment. Does not return payloads or callback details or 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. Read recovery wakes by original data.occurrenceId, not their fresh eventId. Reads do not consume history or acknowledge processing; handle out-of-order work by exact ID.", readEventOccurrencesInput, (input: z.infer) => service.readEventOccurrences(input), false, true); + tool("list_event_occurrences", "Read durable Event occurrences in reverse recorded order, not UUID order. Reads do not acknowledge processing or define a task batch.", 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()); tool("get_trigger", "Get a Trigger, its parent Event, and input configuration", triggerIdSchema, ({ triggerId }: any) => service.getTrigger(triggerId)); tool("create_trigger", "Create an input Trigger attached to an Event. Credentials are never accepted or returned.", mcpTriggerInputSchema, (input: TriggerInput) => service.createTrigger(input)); diff --git a/packages/api/test/mcp-events.postgres.test.ts b/packages/api/test/mcp-events.postgres.test.ts index 9b5f62e7..6326d2fb 100644 --- a/packages/api/test/mcp-events.postgres.test.ts +++ b/packages/api/test/mcp-events.postgres.test.ts @@ -227,6 +227,144 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP event webhook lifecycl expect(await detail(empty)).toEqual({ occurrenceId: empty, state: "no_delivery_records", items: [], truncated: false }); }); + const processing = async (toolName: string, subscriptionId: string, args: Record = {}, identity = auth) => + tool(toolName, { subscription_id: subscriptionId, ...args }, identity); + const configure = (id: string, enabled: boolean) => + processing("set_event_processing_acknowledgments", id, { enabled, ...(enabled ? { ack_timeout_seconds: 30 } : {}) }); + const ack = (id: string, events: string[], cooldown?: number) => + processing("acknowledge_events", id, { event_ids: events, ...(cooldown ? { cooldown_seconds: cooldown } : {}) }); + const replay = (id: string, events: string[]) => + processing("replay_unacknowledged_events", id, { event_ids: events }); + const inspectProcessing = async (occurrenceId: string) => + (await tool("read_event_delivery_diagnostics", { occurrenceId })).structuredContent.items[0]; + const makeRecoveryDue = (occurrenceId: string) => f.db.pool.query( + "UPDATE app.mcp_event_deliveries SET ack_due_at=now()-interval '1 second' WHERE occurrence_id=$1", [occurrenceId]); + + it("acknowledges exact durable work and recovers only the unresolved original occurrence", async () => { + const id = (await subscribe()).message.result.id; + expect((await processing("get_event_processing_acknowledgments", id)).structuredContent.enabled).toBe(false); + const defaultEvent = (await fire("default-delivery")).occurrenceId; + await dispatchMcpEvents(f.env); + expect(await inspectProcessing(defaultEvent)).not.toHaveProperty("processing"); + + expect((await configure(id, true)).structuredContent).toMatchObject({ enabled: true, ackTimeoutSeconds: 30 }); + const a = (await fire("ack-a")).occurrenceId; + const b = (await fire("ack-b")).occurrenceId; + const c = (await fire("ack-c")).occurrenceId; + expect((await ack(id, [a])).structuredContent.notAcknowledged).toEqual([a]); + await dispatchMcpEvents(f.env); + expect(await inspectProcessing(b)).toMatchObject({ status: "accepted", processing: { state: "awaiting_ack", recoveryAttempts: 0 } }); + expect((await ack(id, [c, a, a], 20)).structuredContent.acknowledged).toEqual([c, a]); + const cooldown = (await processing("get_event_processing_acknowledgments", id)).structuredContent.cooldownUntil; + expect((await ack(id, [a], 300)).structuredContent).toMatchObject({ alreadyAcknowledged: [a], cooldownUntil: cooldown }); + + await makeRecoveryDue(b); + expect(await dispatchMcpEvents(f.env)).toBe(0); + const storage = { get: vi.fn(), getAlarm: async () => null, setAlarm: vi.fn() }; + const alarm = new AlarmCoordinator({ storage } as unknown as DurableObjectState, f.env); + await alarm.alarm(); + expect(storage.setAlarm).toHaveBeenCalledOnce(); + expect(Math.abs(Number(storage.setAlarm.mock.calls[0][0]) - Date.parse(cooldown))).toBeLessThan(50); + await f.db.pool.query("UPDATE app.mcp_event_subscriptions SET cooldown_until=now()-interval '1 second' WHERE id=$1", [id]); + + const originalCount = deliveries.length; + await alarm.alarm(); // No new event arrived to wake the scheduler. + const recovered = deliveries.slice(originalCount); + expect(recovered).toHaveLength(1); + expect(recovered[0].event.data.occurrenceId).toBe(b); + expect(recovered[0].id).not.toBe(b); + expect((await ack(id, [recovered[0].id])).structuredContent.notAcknowledged).toEqual([recovered[0].id]); + expect((await ack(id, [b])).structuredContent.acknowledged).toEqual([b]); + expect((await replay(id, [a, b, c])).structuredContent.queued).toEqual([]); + expect((await f.db.pool.query("SELECT 1 FROM app.event_occurrences WHERE tenant_id=$1", [f.tenantId])).rowCount).toBe(4); + }); + + it("serializes acknowledgments and policy disable with in-flight HTTP, and fences old generations", async () => { + const id = (await subscribe()).message.result.id; + await configure(id, true); + const second = (await subscribe(otherReceiver)).message.result.id; + await configure(second, true); + const event = (await fire("ack-race")).occurrenceId; + let entered!: () => void, release!: () => void; + const started = new Promise(resolve => { entered = resolve; }); + holdDelivery = () => { entered(); return new Promise(resolve => { release = resolve; }); }; + // Only the intended subscription is due; the other's copy cannot be acknowledged. + await f.db.pool.query("UPDATE app.mcp_event_deliveries SET next_attempt_at=now()+interval '1 hour' WHERE subscription_id=$1", [second]); + const send = dispatchMcpEvents(f.env); + await started; + expect((await ack(second, [event])).structuredContent.notAcknowledged).toEqual([event]); + const racingAck = ack(id, [event], 40); + release(); + await send; + expect((await racingAck).structuredContent.acknowledged).toEqual([event]); + + const waived = (await fire("waive-race")).occurrenceId; + await f.db.pool.query("UPDATE app.mcp_event_deliveries SET next_attempt_at=now()+interval '1 hour' WHERE subscription_id=$1", [second]); + await f.db.pool.query("UPDATE app.mcp_event_subscriptions SET cooldown_until=NULL WHERE id=$1", [id]); + const startedAgain = new Promise(resolve => { entered = resolve; }); + const sendAgain = dispatchMcpEvents(f.env); + await startedAgain; + const turningOff = configure(id, false); + release(); + await sendAgain; + expect((await turningOff).structuredContent).toMatchObject({ enabled: false, cooldownUntil: null }); + holdDelivery = undefined; + expect(await inspectProcessing(waived)).toMatchObject({ status: "accepted", processing: { state: "waived", nextRecoveryAt: null } }); + expect(await inspectProcessing(event)).toMatchObject({ status: "accepted", processing: { state: "processed" } }); + await configure(id, true); + expect((await ack(id, [waived])).structuredContent.notAcknowledged).toEqual([waived]); + expect((await replay(id, [waived])).structuredContent.queued).toEqual([]); + await unsubscribe(); + expect((await ack(id, [event])).isError).toBe(true); + expect((await subscribe()).message.result.id).toBe(id); + await configure(id, true); + expect((await ack(id, [event])).structuredContent.notAcknowledged).toEqual([event]); + expect((await processing("get_event_processing_acknowledgments", id, {}, { ...auth, oauthGrantId: "other-grant" })).isError).toBe(true); + }); + + it("off clears a claimed but unstarted recovery and does not opt in old occurrences again", async () => { + const id = (await subscribe()).message.result.id; + await configure(id, true); + const occurrence = (await fire("unstarted-recovery")).occurrenceId; + await dispatchMcpEvents(f.env); + await f.db.pool.query(`UPDATE app.mcp_event_deliveries SET claim_id=gen_random_uuid(),recovery_event_id=gen_random_uuid() + WHERE occurrence_id=$1`, [occurrence]); + await f.db.pool.query("UPDATE app.mcp_event_subscriptions SET cooldown_until=now()+interval '1 hour' WHERE id=$1", [id]); + expect((await configure(id, false)).structuredContent.cooldownUntil).toBeNull(); + expect((await f.db.pool.query("SELECT claim_id,recovery_event_id FROM app.mcp_event_deliveries WHERE occurrence_id=$1", [occurrence])).rows) + .toEqual([{ claim_id: null, recovery_event_id: null }]); + await configure(id, true); + await makeRecoveryDue(occurrence); + expect(await dispatchMcpEvents(f.env)).toBe(0); + expect(deliveries).toHaveLength(1); + expect(await inspectProcessing(occurrence)).toMatchObject({ status: "accepted", processing: { state: "waived" } }); + }); + + it("recovers a persisted interrupted claim and caps automatic recovery attempts", async () => { + const id = (await subscribe()).message.result.id; + await configure(id, true); + const occurrence = (await fire("bounded-recovery")).occurrenceId; + await dispatchMcpEvents(f.env); + const interrupted = crypto.randomUUID(); + await f.db.pool.query("UPDATE app.mcp_event_deliveries SET claim_id=gen_random_uuid(),recovery_event_id=$2,recovery_attempts=1 WHERE occurrence_id=$1", + [occurrence, interrupted]); + await makeRecoveryDue(occurrence); + await dispatchMcpEvents(f.env); + expect(deliveries.at(-1)).toMatchObject({ id: interrupted, event: { data: { occurrenceId: occurrence } } }); + for (let i = 0; i < 3; i++) { + await makeRecoveryDue(occurrence); + await dispatchMcpEvents(f.env); + } + expect(deliveries).toHaveLength(4); // Initial delivery and three recoveries; the interrupted claim also counts. + expect(new Set(deliveries.map(d => d.id)).size).toBe(4); + expect(await inspectProcessing(occurrence)).toMatchObject({ status: "accepted", processing: { state: "exhausted", recoveryAttempts: 4 } }); + expect((await replay(id, [occurrence])).structuredContent.queued).toEqual([occurrence]); + expect((await replay(id, [occurrence])).structuredContent.queued).toEqual([]); + await dispatchMcpEvents(f.env); + expect(deliveries.at(-1)?.event.data.occurrenceId).toBe(occurrence); + expect(deliveries).toHaveLength(5); + }); + 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 872de826..25b1e3ec 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -242,6 +242,7 @@ its input and enforces the operation's required scope. | Tool | Authorization | Input | | --- | --- | --- | +| `acknowledge_events` | Same active OAuth grant with `triggers:read` | Record durable processing of exact original occurrence UUIDs; optionally pace future delivery on this subscription | | `append_payload_chunk` | Purpose-specific scope enforced by the server | Validated tool-specific JSON input | | `cancel_api_operation` | Purpose-specific scope enforced by the server | Validated tool-specific JSON input | | `create_app` | Purpose-specific scope enforced by the server | Validated tool-specific JSON input | @@ -266,6 +267,9 @@ 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 | +| `get_event_processing_acknowledgments` | Same active OAuth grant with `triggers:read` | Read the processing policy and cooldown for the active subscription owned by this OAuth grant | +| `replay_unacknowledged_events` | Same active OAuth grant with `triggers:read` | Queue recovery for exact unresolved original occurrence UUIDs on this subscription | +| `set_event_processing_acknowledgments` | Same active OAuth grant with `triggers:read` | Enable processing acknowledgment for future occurrences or waive outstanding acknowledgments on this subscription | | `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 | @@ -324,6 +328,43 @@ delivery tools and cannot retry an outbound message. `delete_event` permanently removes the Event, all attached Triggers and input configurations, and all stored occurrences. +### Optional processing acknowledgments + +The standard MCP subscription request and HTTP delivery behavior are unchanged. +HTTP 2xx means the callback accepted the wake, not that a task ran. Opt in for +future occurrences on the exact subscription using +`set_event_processing_acknowledgments` after subscribing. The setting is off +by default. The same active OAuth grant with `triggers:read` can read it with +`get_event_processing_acknowledgments`. + +- Acknowledge promptly **after** durable processing or handoff. Call + `acknowledge_events` with the exact `subscription_id` and successful original + `event_ids` from `data.occurrenceId`. Arrays accept 1–100 UUIDs. An ACK + reports newly processed, already processed, and not acknowledged IDs; do not + treat the last group as completed work. +- A wake may arrive out of order or contain only part of the work. A recovery + webhook may use a fresh top-level `eventId`; read and deduplicate by the + unchanged original `data.occurrenceId`. UUIDs do not imply ordering or a + high-water mark. Do not assume a platform batch window, run cap, or check + cadence. Page durable history by its documented cursor and retain any work + you cannot complete; do not silently drop it. +- To rate limit, pace in your client first. An optional `cooldown_seconds` + (1–3600) on an ACK with newly completed work pauses delivery only on that + subscription. Retrying the same ACK does not extend cooldown. Delayed + delivery remains durable and resumes when cooldown expires even without a + new event. +- If the ACK timeout expires, Factorize sends bounded recovery wakes for that + original occurrence. Use `read_event_delivery_diagnostics` to distinguish HTTP + acceptance from awaiting ACK, processed, waived, cancelled, and exhausted. + `replay_unacknowledged_events` queues exact unresolved IDs on your active + opted-in subscription, subject to cooldown; it does not create business + occurrences or replay completed work. +- Turning off waives unresolved acknowledgments, cancels unstarted recovery, + and clears subscription cooldown. Turning it on again applies only to + future occurrences. A reactivated subscription is a fresh generation and + starts with acknowledgments off. + + ## Triggers A Trigger belongs to one Event and watches a schedule, signed webhook/provider diff --git a/packages/docs/mcp/tools.mdx b/packages/docs/mcp/tools.mdx index a066760a..cfd304ff 100644 --- a/packages/docs/mcp/tools.mdx +++ b/packages/docs/mcp/tools.mdx @@ -13,6 +13,7 @@ its input and enforces the operation's required scope. | Tool | Authorization | Input | | --- | --- | --- | +| `acknowledge_events` | Same active OAuth grant with `triggers:read` | Record durable processing of exact original occurrence UUIDs; optionally pace future delivery on this subscription | | `append_payload_chunk` | Purpose-specific scope enforced by the server | Validated tool-specific JSON input | | `cancel_api_operation` | Purpose-specific scope enforced by the server | Validated tool-specific JSON input | | `create_app` | Purpose-specific scope enforced by the server | Validated tool-specific JSON input | @@ -37,6 +38,9 @@ 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 | +| `get_event_processing_acknowledgments` | Same active OAuth grant with `triggers:read` | Read the processing policy and cooldown for the active subscription owned by this OAuth grant | +| `replay_unacknowledged_events` | Same active OAuth grant with `triggers:read` | Queue recovery for exact unresolved original occurrence UUIDs on this subscription | +| `set_event_processing_acknowledgments` | Same active OAuth grant with `triggers:read` | Enable processing acknowledgment for future occurrences or waive outstanding acknowledgments on this subscription | | `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 | @@ -95,6 +99,43 @@ delivery tools and cannot retry an outbound message. `delete_event` permanently removes the Event, all attached Triggers and input configurations, and all stored occurrences. +### Optional processing acknowledgments + +The standard MCP subscription request and HTTP delivery behavior are unchanged. +HTTP 2xx means the callback accepted the wake, not that a task ran. Opt in for +future occurrences on the exact subscription using +`set_event_processing_acknowledgments` after subscribing. The setting is off +by default. The same active OAuth grant with `triggers:read` can read it with +`get_event_processing_acknowledgments`. + +- Acknowledge promptly **after** durable processing or handoff. Call + `acknowledge_events` with the exact `subscription_id` and successful original + `event_ids` from `data.occurrenceId`. Arrays accept 1–100 UUIDs. An ACK + reports newly processed, already processed, and not acknowledged IDs; do not + treat the last group as completed work. +- A wake may arrive out of order or contain only part of the work. A recovery + webhook may use a fresh top-level `eventId`; read and deduplicate by the + unchanged original `data.occurrenceId`. UUIDs do not imply ordering or a + high-water mark. Do not assume a platform batch window, run cap, or check + cadence. Page durable history by its documented cursor and retain any work + you cannot complete; do not silently drop it. +- To rate limit, pace in your client first. An optional `cooldown_seconds` + (1–3600) on an ACK with newly completed work pauses delivery only on that + subscription. Retrying the same ACK does not extend cooldown. Delayed + delivery remains durable and resumes when cooldown expires even without a + new event. +- If the ACK timeout expires, Factorize sends bounded recovery wakes for that + original occurrence. Use `read_event_delivery_diagnostics` to distinguish HTTP + acceptance from awaiting ACK, processed, waived, cancelled, and exhausted. + `replay_unacknowledged_events` queues exact unresolved IDs on your active + opted-in subscription, subject to cooldown; it does not create business + occurrences or replay completed work. +- Turning off waives unresolved acknowledgments, cancels unstarted recovery, + and clears subscription cooldown. Turning it on again applies only to + future occurrences. A reactivated subscription is a fresh generation and + starts with acknowledgments off. + + ## Triggers A Trigger belongs to one Event and watches a schedule, signed webhook/provider diff --git a/skills/manage-triggers/SKILL.md b/skills/manage-triggers/SKILL.md index 3b33f7e5..5ed8c398 100644 --- a/skills/manage-triggers/SKILL.md +++ b/skills/manage-triggers/SKILL.md @@ -12,6 +12,28 @@ Use `list_events` and `get_event` to inspect Events and their payload schema rev MCP 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. +## Optional webhook processing acknowledgments + +Use the stable `factorize.occurrence` type with the exact Event UUID in +`event_id`. HTTP 2xx is only callback acceptance. If the user opted in, +read the exact subscription policy with `get_event_processing_acknowledgments` +and change it with `set_event_processing_acknowledgments`. Standard +subscriptions are off by default. This is separate from task run limits. + +After durable completion or handoff, promptly call `acknowledge_events` with +your `subscription_id` and exact original `event_ids` from +`data.occurrenceId`. Use the original ID to read and deduplicate; recovery +may use a fresh webhook `eventId`. IDs do not encode ordering, and wakes can +be partial or out of order. Never assume a batching window or rate cap. +Pace work locally, persist unfinished work instead of dropping it, and do not +acknowledge it until durable. Optional `cooldown_seconds` pauses future +delivery on that subscription only, and duplicate ACKs do not extend it. + +Use `read_event_delivery_diagnostics` for HTTP versus processing status, and +`replay_unacknowledged_events` for exact unresolved original IDs only. Turning +off waives unresolved ACKs and clears cooldown; re-enabling applies forward. + + ## Triggers Each 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.