From 944b1c64d702f3a6e28d9ff9814e4954ba56281f Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Fri, 13 Nov 2026 08:32:06 -0600 Subject: [PATCH] feat(mcp): keep long provider calls durable with the MCP Tasks extension (#21263) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents use connected apps through Paperclip's MCP client in the tool gateway > - Some provider actions run for minutes: CI runs, deploys, batch jobs > - Today such a call is lost if it outlives the tool timeout or if Paperclip restarts or deploys mid-call, and a retry can start the work a second time > - Recovery must just work, and the target rate of runs that need a manual retry is 0% > - This pull request implements the MCP Tasks extension (`io.modelcontextprotocol/tasks`, 2026-07-28) in the MCP client > - The benefit is that a long provider call becomes a durable task: it survives timeouts, restarts, and deploys, and it is never started twice ## Linked Issues or Issue Description **Problem** A long provider tool call holds an HTTP request open. When it passes the tool timeout, or when Paperclip restarts or deploys during the call, the result is lost. The agent then often repeats the call, and the provider does the work again. **Proposed solution** Implement the client side of the MCP Tasks extension. Declare it on stateless tool calls. Store each returned task durably, wait on it during the call, keep polling it in the background after the call ends, and let the same call attach to the stored task instead of sending `tools/call` again. **Why it matters** CI, deploy, and batch actions are where agents lose the most work today. A durable task handle makes these actions safe across timeouts, restarts, and deploys, without a person. Refs #21119, Refs #21140, Refs #21219 (the MCP Apps, stateless MCP client, and MCP Skills work this builds on). ## What Changed - **Off by default:** MCP Tasks are behind the new instance experimental setting `enableMcpTasks` ("Durable app actions (MCP Tasks)"), default off. When it is off, Paperclip never declares the extension, nothing attaches to or polls tasks, pending rows do not block idle sleep, and behavior matches master. A test covers the off state. - `mcp-http.ts`: the tasks extension is declared per request, only on HTTP `tools/call` and `tasks/*`. Discovery, listings, and stdio servers do not declare it. `tasks/*` requests put the task ID in `Mcp-Name`. - New `mcp-tasks.ts`: parses task results, bounds the server's timing hints, sends `tasks/get`, `tasks/update`, and `tasks/cancel`, and seals task IDs at rest (AES-256-GCM, bound to company and connection; a keyed hash gives uniqueness). - New company-scoped table `tool_mcp_tasks` (migration `0475`, online-compatible). It links the task to the call, run, task, connection, and grant. It stores no provider result. - `tool-gateway.ts`: - A returned task is recorded, then polled up to the normal tool timeout. Its result goes through the same validation, redaction, and recording as a direct result. - Past the timeout, or when the caller disconnects, the agent gets `provider_task_pending` ("call again with the same arguments"). The task stays durable. - A call with the same endpoint, tool, full arguments, grant, agent, task, and actor attaches to the undelivered task. A retry with the same idempotency key also attaches, and it can never start different work under that key. - Input: URL requests show the provider link (Paperclip never answers them). Form requests become a question card; only the person's answer is sent with `tasks/update`. Other requests stop with a clear "needs input" error. - Stopping the run sends `tasks/cancel` and marks the task cancelled. A caller that only disconnects keeps the task. - `failed` becomes a tool error with the provider's message. An unknown task or a passed TTL becomes `provider_task_expired`. Every task stops being tracked at its TTL, or after 7 days at most. - Audit entries: `tool_gateway.task_started`, `task_input_sent`, `task_cancelled`. - New `mcp-task-work.ts`, registered at startup with the shared deadline scheduler: it resumes polling pending tasks after a restart, cancels tasks whose task closed or run was stopped, and wakes the assignee once when a task settles after its run ended. - Docs: `doc/connections/MCP-TASKS.md`, linked from `doc/connections/README.md`. Background work (per `rules/sleep-aware-background-work.mdc`): trigger is a task row write or release (`mcp-tasks` queue) and one startup pass. The deadline is the earliest `next_poll_at`. Cadence is the server's `pollIntervalMs` within 5 s – 5 min, with backoff; 5 min while waiting for a person. It is quiet when no row has a next poll. This is the narrow external-source exception: providers give no wake Paperclip can receive, and polling stops with the task. ## Verification - `server/src/__tests__/mcp-tasks.test.ts`: 20 tests with a fake 2026-07-28 server that returns tasks only to a client that declares the extension and checks `Mcp-Name`. They cover: - polling to completion, with the result identical to a synchronous call; - timeout, then an attaching call with no second `tools/call`; - a keyed retry, and a reused key with different arguments (refused); - restart mid-task: a fresh gateway with no in-memory state polls the row, wakes the agent once, and the recovered run gets the result once with no second `tools/call`; - no wake while the run is still going; - URL input (link, never answered), and form input (question card, then `tasks/update` with the answer); - cancellation by the run, by closing the task, and no cancellation when only the caller leaves; - failure, an unknown task, and TTL expiry (ends in under 3 s, no hang); - another agent never attaches; - synchronous calls unchanged and older servers never see the extension. - Red/green: with attach disabled, the timeout, keyed-retry, and restart tests fail (3). With `tasks/cancel` disabled, both cancellation tests fail (2). Before `tools/call` declared the extension, 13 end-to-end tests failed. All pass with the change. - Existing suites pass: `mcp-protocol-versions`, `mcp-http`, `mcp-apps`, `mcp-skills`, `server-startup-feedback-export`, `tool-gateway`, `tool-gateway-discovery-http`, `remote-mcp-connectors` (342 tests). - `tsc --noEmit -p server` is clean. `pnpm --filter @paperclipai/db check:migrations` passes (the migration is classified online-compatible). Snapshots pruned to five. - Agent boot and time-to-first-token: no change in the boot or first-turn path. The only new per-call cost is one indexed lookup on stateless tool calls. - Not run: a live provider that returns tasks. No public MCP server that returns tasks was available without new credentials. ## Risks - Shipped off by default. Review findings that only affect the setting-on path after this merge are tracked as follow-ups. - Migration: a new table with indexes and foreign keys to `companies`, `tool_invocations`, and `tool_connections`. Online-compatible. - Behaviour change only for servers that return tasks, which they may do only to clients that declare the extension. Older servers and stdio servers are unchanged. - A task that settles while nobody is waiting stays attachable for 1 hour, so a deliberate repeat of the same call within that hour collects the earlier result instead of starting new work. - The wake after a background task settles uses the generic task wake; the agent must call the tool again to collect the result. - Follow-ups: `notifications/tasks` via `subscriptions/listen`; sampling and roots input requests; showing a long action's progress in the task chat. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use (shell, file edits, local test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/connections/MCP-TASKS.md | 133 +++ doc/connections/README.md | 7 +- .../2026-11-02-sleep-blocker-inventory.md | 1 + .../db/src/migrations/0478_jazzy_vertigo.sql | 49 + ...{0473_snapshot.json => 0478_snapshot.json} | 759 +++++++++++- packages/db/src/migrations/meta/_journal.json | 7 + packages/db/src/schema/index.ts | 1 + packages/db/src/schema/tool_access.ts | 76 ++ packages/shared/src/feature-catalog.ts | 8 + packages/shared/src/types/instance.ts | 6 + packages/shared/src/validators/instance.ts | 3 + .../idle-sleep-diagnostics-postgres.test.ts | 2 +- .../__tests__/idle-sleep-diagnostics.test.ts | 2 +- .../instance-settings-service.test.ts | 1 + server/src/__tests__/mcp-task-work.test.ts | 26 + server/src/__tests__/mcp-tasks.test.ts | 819 +++++++++++++ server/src/index.ts | 8 + .../services/delivery-work-notifications.ts | 1 + server/src/services/idle-sleep-safety.ts | 5 + server/src/services/instance-settings.ts | 2 + server/src/services/mcp-http.ts | 22 +- server/src/services/mcp-task-work.ts | 53 + server/src/services/mcp-tasks.ts | 294 +++++ server/src/services/tool-gateway.ts | 1018 ++++++++++++++++- server/src/startup-recovery-timing.ts | 2 +- .../runner-e2e/source-sdk-public-inputs.json | 6 +- .../InstanceExperimentalSettings.test.tsx | 1 + ui/src/pages/InstanceExperimentalSettings.tsx | 12 + 28 files changed, 3264 insertions(+), 60 deletions(-) create mode 100644 doc/connections/MCP-TASKS.md create mode 100644 packages/db/src/migrations/0478_jazzy_vertigo.sql rename packages/db/src/migrations/meta/{0473_snapshot.json => 0478_snapshot.json} (98%) create mode 100644 server/src/__tests__/mcp-task-work.test.ts create mode 100644 server/src/__tests__/mcp-tasks.test.ts create mode 100644 server/src/services/mcp-task-work.ts create mode 100644 server/src/services/mcp-tasks.ts diff --git a/doc/connections/MCP-TASKS.md b/doc/connections/MCP-TASKS.md new file mode 100644 index 00000000000..9d99072e02d --- /dev/null +++ b/doc/connections/MCP-TASKS.md @@ -0,0 +1,133 @@ +# MCP Tasks: long provider calls that survive timeouts, restarts, and deploys + +Some provider actions take minutes: a CI run, a deploy, a batch job. An MCP +server that supports **Tasks** answers such a `tools/call` with a durable task +handle instead of the result. Paperclip stores that handle, waits on it, and +hands the agent the final result exactly as a quick call would return it. If +the call outlives its timeout, or Paperclip restarts or deploys mid-call, the +work is not lost and is never started a second time. + +## Turning it on + +MCP Tasks are behind the experimental setting **Durable app actions (MCP +Tasks)** (`enableMcpTasks`), off by default. Find it under Instance settings → +Experimental. + +- **Off:** Paperclip never declares `io.modelcontextprotocol/tasks`, so servers + never return a task and every call behaves as before. Nothing polls, attaches + to, or wakes for stored tasks, and they do not keep an idle host awake. +- **On:** everything below applies. Turning it off later stops new tasks; + stored ones resume if it is turned on again before they expire. + +## The standard + +- Specification: [MCP Tasks extension, 2026-07-28](https://github.com/modelcontextprotocol/ext-tasks) + ([overview](https://modelcontextprotocol.io/extensions/tasks/overview)). +- Extension id: `io.modelcontextprotocol/tasks`. It is defined for stateless MCP + (2026-07-28), so Paperclip uses it only with servers on that version. See + [MCP-PROTOCOL-VERSIONS.md](./MCP-PROTOCOL-VERSIONS.md). +- Input requests use the multi round-trip shape + ([MRTR](https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/mrtr)). + +The protocol works like this: + +1. **The client declares the extension per request** in + `_meta["io.modelcontextprotocol/clientCapabilities"].extensions`. A server + must never return a task to a request that did not declare it. +2. **`tools/call` may return a task** (`resultType: "task"`, with `taskId`, + `status`, `ttlMs`, `pollIntervalMs`). The server decides per call. +3. **`tasks/get {taskId}`** returns the task: `working`, `input_required` (with + `inputRequests`), `completed` (with `result`, the normal tool result), + `failed` (with a JSON-RPC `error`), or `cancelled`. +4. **`tasks/update {taskId, inputResponses}`** answers input requests. +5. **`tasks/cancel {taskId}`** asks the server to stop. Cancellation is cooperative. +6. Over HTTP, `Mcp-Name` carries the task ID on every `tasks/*` request so load + balancers route it to the instance holding the task. + +Optional `notifications/tasks` over `subscriptions/listen` are not used; +Paperclip polls, which the specification makes the default. + +## How Paperclip implements it + +| Step | What happens | Code | +| --- | --- | --- | +| Declare | Only the HTTP `tools/call` and `tasks/*` requests declare the extension. Discovery, listings, and local (stdio) servers do not, so no other path can receive a task it cannot handle. | `mcpHttpRequestInit(..., { declareTasks })` in `server/src/services/mcp-http.ts` | +| Record | A returned task is stored before Paperclip waits on it: a `tool_mcp_tasks` row linked to the call, run, task, connection, and grant. | `createMcpTaskRecord` in `server/src/services/tool-gateway.ts` | +| Wait | The live call polls `tasks/get` at the server's `pollIntervalMs` (kept between 0.2 s and 5 s) until the normal tool timeout. A completed task's `result` then goes through the same validation, redaction, and recording as a direct result. | `waitForMcpTask` | +| Hand off | If the timeout passes or the caller disconnects, the agent is told the app is still working and to call the tool again with the same arguments. The row keeps the task and background polling takes over. | `provider_task_pending` | +| Attach | A call with the same endpoint, tool, full arguments, grant, agent, task, and actor attaches to the undelivered task instead of sending `tools/call` again. So does a retry with the same idempotency key, including after a crash mid-wait; the same key with other arguments is refused and leaves the original retry intact. One holder at a time (a lease): a second simultaneous caller is told to call again. | `findAttachableMcpTask`, `mcpTaskForKeyedRetry`, `claimMcpTask` | +| Deliver | A completed task counts as delivered only once its result is recorded on the call. A crash in between leaves it collectable again. | `markMcpTaskDelivered` | +| Restart | Background work reads pending rows at startup and polls each at its next deadline, with each request bounded to 30 s. It rechecks the same access a live call needs (grant, audience, delegation). When a task settles, or asks a new question, after its run has ended, the assignee is woken once; the agent's repeated call collects the result or shows the question. | `pollDueMcpTasks`, `server/src/services/mcp-task-work.ts` | +| Input | URL requests show the provider link, as for a direct request; Paperclip never answers them for the person. Form requests become a question card on the task; only the person's answer is sent with `tasks/update`. Other requests (sampling, roots) stop with a clear "needs input" error. | `planMcpTaskInput` | +| Cancel | Stopping the run sends `tasks/cancel` and marks the row cancelled. Closing the task or stopping its run does the same for a task in the background; a later call reports the cancellation and never revives it. A caller that only disconnects keeps the task. | `cancelMcpTaskRecord`, `mcpTaskStopReason` | +| Finish | `failed` becomes a tool error with the provider's message. An unknown task (`-32602`) or a passed TTL becomes a clear error telling the agent to run the action again. Nothing waits forever: every task stops being tracked after its TTL, and seven days after Paperclip first saw it at most. | `provider_task_failed`, `provider_task_expired` | + +### What is stored + +- The provider's task ID is sealed at rest (AES-256-GCM, a key derived from the + instance's tool-action secret, bound to the company and connection). The + specification lets servers treat task IDs as bearer tokens. Uniqueness uses a + keyed hash, never the ID. +- No provider result is stored in the task row. The result stays with the + provider until it is delivered, and the delivered result is recorded on the + call exactly as a direct result is. +- A task is read only with the grant that created it, after the same access + check a live call makes. If that access is removed, the connection is + disabled, or its endpoint changes, background polling stops and the task is + reported as no longer available. +- A provider's error body is read only up to 64 KiB. + +### Agent-facing errors + +| Reason code | When | What the agent should do | +| --- | --- | --- | +| `provider_task_pending` | Still working at the timeout, or the caller left | Call the same tool again with the same arguments | +| `provider_interaction_required` | The app needs the person to open a link | Wait for the person, then call again | +| `elicitation_required` | The app asked a question; a card is on the task | Wait for the answer, then call again | +| `provider_input_required` | The app needs input Paperclip cannot collect | Ask the person to finish in the app | +| `provider_task_failed` | The app reported a failure | Treat as a tool error | +| `provider_task_cancelled` | The app cancelled, or the run was stopped | Run again if still needed | +| `provider_task_expired` | The app no longer has the task | Run the action again | + +## Background work + +`registerMcpTaskWork` uses the shared deadline scheduler +(`registerDeadlineWork`). It is quiet when nothing is pending: + +- **Trigger:** writing or releasing a task row notifies the `mcp-tasks` queue; + startup runs once and rebuilds from the rows. +- **Deadline:** the earliest `next_poll_at`, never earlier than a live call's lease. +- **Cadence:** the server's `pollIntervalMs`, kept between 5 s and 5 min, with + backoff after failures. A task waiting for a person is checked every 5 min: + the person's answer wakes the agent, whose call checks immediately. +- **Quiet:** once every task is delivered, settled and woken, cancelled, or + expired, no row has a next poll and no query or provider request runs. + +This is the narrow exception in `rules/sleep-aware-background-work.mdc`: the +provider offers no wake Paperclip can receive, so an active task is polled. +Polling stops with the task. A pending task is an idle-sleep blocker +(`tool_mcp_tasks` in `idle-sleep-safety.ts`), so a host that sleeps when idle +stays awake until every task is settled. Recovery runs even when heartbeat +scheduling is off; only the agent wake needs the scheduler. + +An approved action whose task outlives the wait keeps its approval: the action +returns to approved, and its next execution attaches to the same task. + +## Follow-ups + +- `notifications/tasks` over `subscriptions/listen`, to replace polling where + servers support it. +- Sampling and roots input requests. +- Showing a long-running provider action's progress (`statusMessage`) in the + task chat. +- Validating question-card answers against the provider's form schema (types, + required fields) and letting the person correct them before `tasks/update`. + +## Tests + +`server/src/__tests__/mcp-tasks.test.ts` runs a fake 2026-07-28 server that +returns tasks. It covers polling to completion, a timeout followed by an +attaching call, a keyed retry, a restart mid-task (fresh gateway, no second +`tools/call`, one wake, one delivery), URL and form input, cancellation by the +run and by closing the task, failure, an unknown task, TTL expiry, another +agent never attaching, and synchronous calls left unchanged. diff --git a/doc/connections/README.md b/doc/connections/README.md index 4ebdfd2b9ae..f2d7edca5d9 100644 --- a/doc/connections/README.md +++ b/doc/connections/README.md @@ -17,9 +17,10 @@ Runtime authentication: [AI Connections](./AI-CONNECTIONS.md). MCP protocol versions (2026-07-28 stateless MCP and older handshake servers): [MCP-PROTOCOL-VERSIONS.md](./MCP-PROTOCOL-VERSIONS.md). -MCP extensions: [MCP Apps](./MCP-APPS.md) (interactive views in the task chat) -and [MCP Skills](./MCP-SKILLS.md) (skills that connected apps publish, reviewed -by the board and delivered to agents). +MCP extensions: [MCP Apps](./MCP-APPS.md) (interactive views in the task chat), +[MCP Skills](./MCP-SKILLS.md) (skills that connected apps publish, reviewed +by the board and delivered to agents), and [MCP Tasks](./MCP-TASKS.md) (long +provider calls that survive timeouts, restarts, and deploys). Long-term memory: [Experimental memory connectors](./MEMORY.md). diff --git a/doc/plans/2026-11-02-sleep-blocker-inventory.md b/doc/plans/2026-11-02-sleep-blocker-inventory.md index 8918e1b997f..9832b900fc4 100644 --- a/doc/plans/2026-11-02-sleep-blocker-inventory.md +++ b/doc/plans/2026-11-02-sleep-blocker-inventory.md @@ -40,6 +40,7 @@ Remedies below mean completing the owning protocol or supplying a separately tes | `agents.lifecycle` | [agents](../../packages/db/src/schema/agents.ts); [../modules/agent-lifecycle/index.ts](../../server/src/modules/agent-lifecycle/index.ts). active / recovery. | Preparing/verifying/pausing/resuming/terminating/cleaning-up phases. Fixture: Pausing agent versus stable paused state. | Domain settlement; preserve the owning evidence and records. | | `decision_invocations` | [decision_invocations](../../packages/db/src/schema/decision_models.ts); [decision-models.ts](../../server/src/services/decision-models.ts). active. | Running decision invocation. This existing predicate is narrower than a universal unknown-state guard. Fixture: Running invocation versus completed invocation. | Domain completion; preserve the owning evidence and records. | | `prompt_injection_invocations` | [prompt_injection_invocations](../../packages/db/src/schema/prompt_injection_prevention.ts); [prompt-injection-prevention.ts](../../server/src/services/prompt-injection-prevention.ts). active. | Running prompt-injection invocation; current SQL checks running specifically. Fixture: Running invocation versus finished invocation. | Domain completion; preserve the owning evidence and records. | +| `tool_mcp_tasks` | [tool_mcp_tasks](../../packages/db/src/schema/tool_access.ts); [mcp-task-work.ts](../../server/src/services/mcp-task-work.ts). active. | Provider task with a next poll (MCP Tasks); the provider cannot wake Paperclip. Fixture: pending task versus delivered task. | Domain completion: delivery, expiry, cancellation, or the 7-day cap. | | `agent_api_keys` | [agent_api_keys](../../packages/db/src/schema/agent_api_keys.ts); [agents.ts](../../server/src/services/agents.ts). ingress configuration. | Unrevoked machine credential can accept autonomous inbound work. Fixture: Saved live key versus revoked key. | Incoming-work proof; preserve the owning evidence and records. | | `board_api_keys` | [board_api_keys](../../packages/db/src/schema/board_api_keys.ts); [board-auth.ts](../../server/src/services/board-auth.ts). ingress configuration. | Unrevoked key whose expiry is absent or future. Fixture: Live key versus revoked/expired key. | Incoming-work proof; preserve the owning evidence and records. | | `agent_wakeup_requests` | [agent_wakeup_requests](../../packages/db/src/schema/agent_wakeup_requests.ts); [heartbeat/queue.ts](../../server/src/services/heartbeat/queue.ts). active / handoff. | Unsettled wake; coalesced wake additionally requires finished receipt and exact company/agent finished run. Fixture: Deferred wake versus exact completed/coalesced receipt. | Domain handoff; preserve the owning evidence and records. | diff --git a/packages/db/src/migrations/0478_jazzy_vertigo.sql b/packages/db/src/migrations/0478_jazzy_vertigo.sql new file mode 100644 index 00000000000..8759ef2dfd4 --- /dev/null +++ b/packages/db/src/migrations/0478_jazzy_vertigo.sql @@ -0,0 +1,49 @@ +CREATE TABLE "tool_mcp_tasks" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "company_id" uuid NOT NULL, + "invocation_id" uuid NOT NULL, + "connection_id" uuid NOT NULL, + "grant_id" uuid NOT NULL, + "agent_id" uuid, + "issue_id" uuid, + "run_id" uuid, + "actor_type" text NOT NULL, + "actor_id" text, + "responsible_user_id" text, + "identity_context_id" uuid, + "catalog_tool_name" text NOT NULL, + "request_hash" text NOT NULL, + "endpoint_hash" text NOT NULL, + "sealed_caller_headers" text, + "protocol_version" text NOT NULL, + "sealed_provider_task_id" text NOT NULL, + "provider_task_id_hash" text NOT NULL, + "status" text NOT NULL, + "poll_interval_ms" integer, + "ttl_ms" integer, + "expires_at" timestamp with time zone NOT NULL, + "next_poll_at" timestamp with time zone, + "last_polled_at" timestamp with time zone, + "poll_failures" integer DEFAULT 0 NOT NULL, + "lease_expires_at" timestamp with time zone, + "lease_owner" text, + "arguments_identity" text NOT NULL, + "answered_input_keys" jsonb DEFAULT '[]'::jsonb NOT NULL, + "surfaced_input_keys" jsonb DEFAULT '[]'::jsonb NOT NULL, + "input_wake_count" integer DEFAULT 0 NOT NULL, + "input_wake_at" timestamp with time zone, + "error_code" text, + "wake_requested_at" timestamp with time zone, + "delivered_at" timestamp with time zone, + "last_invocation_id" uuid, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "tool_mcp_tasks" ADD CONSTRAINT "tool_mcp_tasks_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "tool_mcp_tasks" ADD CONSTRAINT "tool_mcp_tasks_invocation_id_tool_invocations_id_fk" FOREIGN KEY ("invocation_id") REFERENCES "public"."tool_invocations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "tool_mcp_tasks" ADD CONSTRAINT "tool_mcp_tasks_connection_id_tool_connections_id_fk" FOREIGN KEY ("connection_id") REFERENCES "public"."tool_connections"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE UNIQUE INDEX "tool_mcp_tasks_provider_task_uq" ON "tool_mcp_tasks" USING btree ("company_id","connection_id","provider_task_id_hash");--> statement-breakpoint +CREATE INDEX "tool_mcp_tasks_attach_idx" ON "tool_mcp_tasks" USING btree ("company_id","connection_id","request_hash");--> statement-breakpoint +CREATE INDEX "tool_mcp_tasks_invocation_idx" ON "tool_mcp_tasks" USING btree ("company_id","invocation_id");--> statement-breakpoint +CREATE INDEX "tool_mcp_tasks_next_poll_idx" ON "tool_mcp_tasks" USING btree ("next_poll_at") WHERE "tool_mcp_tasks"."next_poll_at" is not null; \ No newline at end of file diff --git a/packages/db/src/migrations/meta/0473_snapshot.json b/packages/db/src/migrations/meta/0478_snapshot.json similarity index 98% rename from packages/db/src/migrations/meta/0473_snapshot.json rename to packages/db/src/migrations/meta/0478_snapshot.json index 45d0244b9e7..d7f274a6422 100644 --- a/packages/db/src/migrations/meta/0473_snapshot.json +++ b/packages/db/src/migrations/meta/0478_snapshot.json @@ -1,6 +1,6 @@ { - "id": "f14430e8-1ebf-414a-8c89-93c32740c4e6", - "prevId": "77704cfc-2cbe-41de-9d2c-5225b8466646", + "id": "349cdd89-db04-4340-a5d3-3b877bf7227d", + "prevId": "d5d69127-12de-4281-9816-c20e013bfeb7", "version": "7", "dialect": "postgresql", "tables": { @@ -3954,6 +3954,28 @@ "method": "btree", "with": {} }, + "agent_wakeup_requests_company_run_idx": { + "name": "agent_wakeup_requests_company_run_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"agent_wakeup_requests\".\"run_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, "agent_wakeup_requests_review_path_recovery_idempotency_uq": { "name": "agent_wakeup_requests_review_path_recovery_idempotency_uq", "columns": [ @@ -53942,6 +53964,7 @@ } ], "isUnique": true, + "where": "\"sandbox_creation_operations\".\"state\" <> 'resolved'", "concurrently": false, "method": "btree", "with": {} @@ -57541,6 +57564,12 @@ "primaryKey": false, "notNull": false }, + "icons": { + "name": "icons", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, "risk_level": { "name": "risk_level", "type": "text", @@ -59762,6 +59791,18 @@ "primaryKey": false, "notNull": true }, + "model_context": { + "name": "model_context", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "model_context_updated_at": { + "name": "model_context_updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, "created_at": { "name": "created_at", "type": "timestamp with time zone", @@ -60627,6 +60668,720 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.tool_mcp_skill_files": { + "name": "tool_mcp_skill_files", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "file_uri": { + "name": "file_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "digest": { + "name": "digest", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "content_base64": { + "name": "content_base64", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tool_mcp_skill_files_digest_idx": { + "name": "tool_mcp_skill_files_digest_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "file_uri", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "digest", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tool_mcp_skill_files_company_id_companies_id_fk": { + "name": "tool_mcp_skill_files_company_id_companies_id_fk", + "tableFrom": "tool_mcp_skill_files", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tool_mcp_skill_files_connection_id_tool_connections_id_fk": { + "name": "tool_mcp_skill_files_connection_id_tool_connections_id_fk", + "tableFrom": "tool_mcp_skill_files", + "tableTo": "tool_connections", + "columnsFrom": [ + "connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tool_mcp_skills": { + "name": "tool_mcp_skills", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "skill_uri": { + "name": "skill_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "frontmatter": { + "name": "frontmatter", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "manifest": { + "name": "manifest", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "manifest_digest": { + "name": "manifest_digest", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending_review'" + }, + "status_reason": { + "name": "status_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_manifest_digest": { + "name": "approved_manifest_digest", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "allowed_tools_approved": { + "name": "allowed_tools_approved", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "reviewed_at": { + "name": "reviewed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "reviewed_by_user_id": { + "name": "reviewed_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tool_mcp_skills_connection_uri_idx": { + "name": "tool_mcp_skills_connection_uri_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "skill_uri", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_mcp_skills_company_status_idx": { + "name": "tool_mcp_skills_company_status_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tool_mcp_skills_company_id_companies_id_fk": { + "name": "tool_mcp_skills_company_id_companies_id_fk", + "tableFrom": "tool_mcp_skills", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tool_mcp_skills_connection_id_tool_connections_id_fk": { + "name": "tool_mcp_skills_connection_id_tool_connections_id_fk", + "tableFrom": "tool_mcp_skills", + "tableTo": "tool_connections", + "columnsFrom": [ + "connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tool_mcp_tasks": { + "name": "tool_mcp_tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "invocation_id": { + "name": "invocation_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "grant_id": { + "name": "grant_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "agent_id": { + "name": "agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "run_id": { + "name": "run_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "responsible_user_id": { + "name": "responsible_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "identity_context_id": { + "name": "identity_context_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "catalog_tool_name": { + "name": "catalog_tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_hash": { + "name": "request_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "endpoint_hash": { + "name": "endpoint_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sealed_caller_headers": { + "name": "sealed_caller_headers", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "protocol_version": { + "name": "protocol_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sealed_provider_task_id": { + "name": "sealed_provider_task_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_task_id_hash": { + "name": "provider_task_id_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "poll_interval_ms": { + "name": "poll_interval_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "ttl_ms": { + "name": "ttl_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "next_poll_at": { + "name": "next_poll_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_polled_at": { + "name": "last_polled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "poll_failures": { + "name": "poll_failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "lease_owner": { + "name": "lease_owner", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "arguments_identity": { + "name": "arguments_identity", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "answered_input_keys": { + "name": "answered_input_keys", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "surfaced_input_keys": { + "name": "surfaced_input_keys", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "input_wake_count": { + "name": "input_wake_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "input_wake_at": { + "name": "input_wake_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "wake_requested_at": { + "name": "wake_requested_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "delivered_at": { + "name": "delivered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_invocation_id": { + "name": "last_invocation_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tool_mcp_tasks_provider_task_uq": { + "name": "tool_mcp_tasks_provider_task_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_task_id_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_mcp_tasks_attach_idx": { + "name": "tool_mcp_tasks_attach_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "request_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_mcp_tasks_invocation_idx": { + "name": "tool_mcp_tasks_invocation_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "invocation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_mcp_tasks_next_poll_idx": { + "name": "tool_mcp_tasks_next_poll_idx", + "columns": [ + { + "expression": "next_poll_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_mcp_tasks\".\"next_poll_at\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tool_mcp_tasks_company_id_companies_id_fk": { + "name": "tool_mcp_tasks_company_id_companies_id_fk", + "tableFrom": "tool_mcp_tasks", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tool_mcp_tasks_invocation_id_tool_invocations_id_fk": { + "name": "tool_mcp_tasks_invocation_id_tool_invocations_id_fk", + "tableFrom": "tool_mcp_tasks", + "tableTo": "tool_invocations", + "columnsFrom": [ + "invocation_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tool_mcp_tasks_connection_id_tool_connections_id_fk": { + "name": "tool_mcp_tasks_connection_id_tool_connections_id_fk", + "tableFrom": "tool_mcp_tasks", + "tableTo": "tool_connections", + "columnsFrom": [ + "connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.tool_oauth_states": { "name": "tool_oauth_states", "schema": "", diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 5b3649aba28..11496828cb9 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3333,6 +3333,13 @@ "when": 1794554569782, "tag": "0477_friendly_toro", "breakpoints": true + }, + { + "idx": 478, + "version": "7", + "when": 1794577652781, + "tag": "0478_jazzy_vertigo", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts index 0ab8fe7af0b..d22f870e6f8 100644 --- a/packages/db/src/schema/index.ts +++ b/packages/db/src/schema/index.ts @@ -193,6 +193,7 @@ export { toolMcpAppViews, toolMcpSkills, toolMcpSkillFiles, + toolMcpTasks, toolActionRequests, toolCallEvents, toolRateLimitCounters, diff --git a/packages/db/src/schema/tool_access.ts b/packages/db/src/schema/tool_access.ts index 8f37c7c1bf8..88474beeceb 100644 --- a/packages/db/src/schema/tool_access.ts +++ b/packages/db/src/schema/tool_access.ts @@ -890,6 +890,82 @@ export const toolMcpSkills = pgTable( ], ); +/** + * A provider task (MCP Tasks extension) that a `tools/call` returned in place + * of its result. The row is the durable handle: polling resumes from it after + * a restart, and a repeated call with the same request identity, grant, and + * agent attaches to it instead of starting the work again. No provider result + * is stored here; the result is read from the provider when it is delivered. + */ +export const toolMcpTasks = pgTable( + "tool_mcp_tasks", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + /** The call that created the task. */ + invocationId: uuid("invocation_id").notNull().references(() => toolInvocations.id, { onDelete: "cascade" }), + connectionId: uuid("connection_id").notNull().references(() => toolConnections.id, { onDelete: "cascade" }), + /** The grant whose credentials created the task; only that grant may read it. */ + grantId: uuid("grant_id").notNull(), + agentId: uuid("agent_id"), + issueId: uuid("issue_id"), + /** The latest run that waited on the task. */ + runId: uuid("run_id"), + actorType: text("actor_type").notNull(), + actorId: text("actor_id"), + /** The person whose grant applied, and the run identity, so background checks see the same caller. */ + responsibleUserId: text("responsible_user_id"), + identityContextId: uuid("identity_context_id"), + catalogToolName: text("catalog_tool_name").notNull(), + /** Endpoint, tool, and full arguments; a call attaches only on an exact match. */ + requestHash: text("request_hash").notNull(), + endpointHash: text("endpoint_hash").notNull(), + /** Forwarded caller headers the connection allows (such as a tenant), sealed; background polls send them too. */ + sealedCallerHeaders: text("sealed_caller_headers"), + protocolVersion: text("protocol_version").notNull(), + /** The provider's task ID, sealed: it may act as a bearer token. */ + sealedProviderTaskId: text("sealed_provider_task_id").notNull(), + /** Keyed hash of the provider's task ID, for uniqueness without the ID. */ + providerTaskIdHash: text("provider_task_id_hash").notNull(), + /** working | input_required | completed | failed | cancelled | expired */ + status: text("status").notNull(), + pollIntervalMs: integer("poll_interval_ms"), + ttlMs: integer("ttl_ms"), + /** When Paperclip stops tracking the task (the provider's TTL, capped). */ + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), + /** Next background check; null when nothing is left to do. */ + nextPollAt: timestamp("next_poll_at", { withTimezone: true }), + lastPolledAt: timestamp("last_polled_at", { withTimezone: true }), + pollFailures: integer("poll_failures").notNull().default(0), + /** A live call or the background worker holds the task until then. */ + leaseExpiresAt: timestamp("lease_expires_at", { withTimezone: true }), + /** Who holds the lease; writes under a lease require it. */ + leaseOwner: text("lease_owner"), + /** The gateway's keyed identity of the full arguments, for keyed retries. */ + argumentsIdentity: text("arguments_identity").notNull(), + /** Input request keys already answered with `tasks/update`. */ + answeredInputKeys: jsonb("answered_input_keys").$type().notNull().default([]), + /** Input request keys already shown to the agent (a link or a question card). */ + surfacedInputKeys: jsonb("surfaced_input_keys").$type().notNull().default([]), + /** Wakes requested for new input requests; capped, so a provider cannot wake an agent without end. */ + inputWakeCount: integer("input_wake_count").notNull().default(0), + inputWakeAt: timestamp("input_wake_at", { withTimezone: true }), + errorCode: text("error_code"), + wakeRequestedAt: timestamp("wake_requested_at", { withTimezone: true }), + deliveredAt: timestamp("delivered_at", { withTimezone: true }), + /** The latest call that waited on the task (a retry with its key attaches again). */ + lastInvocationId: uuid("last_invocation_id"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), + }, + (table) => [ + uniqueIndex("tool_mcp_tasks_provider_task_uq").on(table.companyId, table.connectionId, table.providerTaskIdHash), + index("tool_mcp_tasks_attach_idx").on(table.companyId, table.connectionId, table.requestHash), + index("tool_mcp_tasks_invocation_idx").on(table.companyId, table.invocationId), + index("tool_mcp_tasks_next_poll_idx").on(table.nextPollAt).where(sql`${table.nextPollAt} is not null`), + ], +); + /** * Verified skill files, written only by the server after a size and SHA-256 * check and never changed in place. Rows are keyed by connection and digest, diff --git a/packages/shared/src/feature-catalog.ts b/packages/shared/src/feature-catalog.ts index cf667a58319..293f19e7958 100644 --- a/packages/shared/src/feature-catalog.ts +++ b/packages/shared/src/feature-catalog.ts @@ -385,6 +385,14 @@ export const INSTANCE_FEATURE_CATALOG: Record !check.reason.includes(".") || ["agents.execution_or_timer", "agents.lifecycle", "agents.company_hold", "heartbeat_runs.budget_cancellation"].includes(check.reason))) - .toHaveLength(75); + .toHaveLength(76); expect(report.diagnostics?.checks).toEqual(expect.arrayContaining([ { reason: "mcp_file_tickets", state: "none" }, { reason: "mcp_authorization_handoffs", state: "none" }, diff --git a/server/src/__tests__/idle-sleep-diagnostics.test.ts b/server/src/__tests__/idle-sleep-diagnostics.test.ts index a9eb0f82be3..995e95eaa75 100644 --- a/server/src/__tests__/idle-sleep-diagnostics.test.ts +++ b/server/src/__tests__/idle-sleep-diagnostics.test.ts @@ -40,7 +40,7 @@ describe("owned idle sleep diagnostics", () => { expect(result.diagnostics?.complete).toBe(true); expect(result.diagnostics?.checks.filter(check => check.state === "present").map(check => check.reason)) .toEqual(["agent_api_keys", "budget_evaluation_work", "chat_deliveries", "heartbeat_runs", "muse_mailbox_items"]); - expect(f.keys()).toHaveLength(75); + expect(f.keys()).toHaveLength(76); expect(f.keys()).toEqual(expect.arrayContaining(["mcp_file_tickets", "mcp_authorization_handoffs"])); expect(new Set(f.keys()).size).toBe(f.keys().length); const inventory = readFileSync(new URL("../../../doc/plans/2026-11-02-sleep-blocker-inventory.md", import.meta.url), "utf8"); diff --git a/server/src/__tests__/instance-settings-service.test.ts b/server/src/__tests__/instance-settings-service.test.ts index 4ced4dcc4c1..779fed4a977 100644 --- a/server/src/__tests__/instance-settings-service.test.ts +++ b/server/src/__tests__/instance-settings-service.test.ts @@ -164,6 +164,7 @@ describe("instance settings service", () => { enableWorkspaceDirtyQuarantineRepair: false, enableOwnerInstanceAdmin: false, enableSandboxDuplexBridge: false, + enableMcpTasks: false, enableRunnerPreviewIngress: false, enableWorktreeRunExecution: false, worktreeRunExecutionActivatedAt: null, diff --git a/server/src/__tests__/mcp-task-work.test.ts b/server/src/__tests__/mcp-task-work.test.ts new file mode 100644 index 00000000000..3ede78f664c --- /dev/null +++ b/server/src/__tests__/mcp-task-work.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it, vi } from "vitest"; +import { registerMcpTaskWork } from "../services/mcp-task-work.js"; + +describe("provider task background work", () => { + it("files each wake under its own key, so a question wake never hides the completion wake", async () => { + let registered: { run: (signal: AbortSignal) => Promise } | undefined; + const coordinator = { register: (_queue: string, task: { run: (signal: AbortSignal) => Promise }) => { + registered = task; + return { ready: Promise.resolve(), wake: () => undefined, stop: async () => undefined }; + } }; + const wakeup = vi.fn(async (_agentId: string, _options: { idempotencyKey: string }) => null); + const gateway = { + pollDueMcpTasks: vi.fn(async (input: { wake?: (task: never) => Promise }) => { + for (const wakeKey of ["mcp-task:t1:input:1", "mcp-task:t1:settled"]) { + await input.wake!({ companyId: "c", agentId: "a", issueId: "i", taskRecordId: "t1", toolName: "build", status: "completed", wakeKey } as never); + } + return { processed: 1 }; + }), + nextMcpTaskPollAt: vi.fn(async () => null), + }; + registerMcpTaskWork(coordinator as never, gateway as never, { wakeup } as never, () => true); + await registered!.run(new AbortController().signal); + expect(wakeup.mock.calls.map(([, options]) => options.idempotencyKey)) + .toEqual(["mcp-task:t1:input:1", "mcp-task:t1:settled"]); + }); +}); diff --git a/server/src/__tests__/mcp-tasks.test.ts b/server/src/__tests__/mcp-tasks.test.ts new file mode 100644 index 00000000000..1c93f1f3712 --- /dev/null +++ b/server/src/__tests__/mcp-tasks.test.ts @@ -0,0 +1,819 @@ +import { randomUUID } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { + agentWakeupRequests, + approvals, + toolActionRequests, + agents, + connectionGrants, + toolConnections, + companies, + companyMemberships, + createDb, + heartbeatRuns, + issues, + issueThreadInteractions, + projects, + toolInvocations, + toolMcpTasks, +} from "@paperclipai/db"; +import { and, eq, lte, ne } from "drizzle-orm"; +import { MCP_MODERN_PROTOCOL_VERSION, forgetMcpHttpSessions, mcpHttpRequestInit } from "../services/mcp-http.js"; +import { + MCP_TASKS_EXTENSION_ID, + backgroundPollDelayMs, + mcpCreatedTask, + mcpTaskExpiresAt, + mcpTaskIdIndex, + openMcpTaskId, + parseMcpTask, + sealMcpTaskId, + sendMcpTaskRequest, +} from "../services/mcp-tasks.js"; +import { createToolGatewayService } from "../services/tool-gateway.js"; +import { toolAccessService } from "../services/tool-access.js"; +import { instanceSettingsService } from "../services/instance-settings.js"; +import { adapterExecutionControls, createAdapterExecutionControl } from "../services/adapter-execution-control.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const META_VERSION = "io.modelcontextprotocol/protocolVersion"; +const META_CAPABILITIES = "io.modelcontextprotocol/clientCapabilities"; + +describe("MCP Tasks protocol", () => { + it("declares the tasks extension only where Paperclip can wait on a task", () => { + const headers = { "MCP-Protocol-Version": MCP_MODERN_PROTOCOL_VERSION }; + const call = JSON.parse(mcpHttpRequestInit(headers, { id: 1, method: "tools/call", params: { name: "x" } }, { declareTasks: true }).body); + expect(call.params._meta[META_CAPABILITIES].extensions[MCP_TASKS_EXTENSION_ID]).toEqual({}); + const list = JSON.parse(mcpHttpRequestInit(headers, { id: 2, method: "tools/list" }).body); + expect(list.params._meta[META_CAPABILITIES].extensions).not.toHaveProperty(MCP_TASKS_EXTENSION_ID); + // Older servers never see it: they get no per-request metadata at all. + const legacy = JSON.parse(mcpHttpRequestInit({ "MCP-Protocol-Version": "2025-11-25" }, { id: 3, method: "tools/call", params: { name: "x" } }, { declareTasks: true }).body); + expect(legacy.params).not.toHaveProperty("_meta"); + }); + + it("routes task requests by task ID in Mcp-Name", () => { + const init = mcpHttpRequestInit({ "MCP-Protocol-Version": MCP_MODERN_PROTOCOL_VERSION }, { id: 1, method: "tasks/get", params: { taskId: "task-é" } }, { declareTasks: true }); + const headers = new Headers(init.headers); + expect(headers.get("mcp-method")).toBe("tasks/get"); + expect(headers.get("mcp-name")).toBe(`=?base64?${Buffer.from("task-é").toString("base64")}?=`); + }); + + it("reads task handles and states, and rejects malformed ones", () => { + const created = mcpCreatedTask({ resultType: "task", taskId: "t1", status: "working", ttlMs: 60_000, pollIntervalMs: 500, createdAt: "2026-11-12T00:00:00Z", lastUpdatedAt: "2026-11-12T00:00:00Z" }); + expect(created).toMatchObject({ taskId: "t1", status: "working", ttlMs: 60_000, pollIntervalMs: 500 }); + expect(mcpCreatedTask({ resultType: "complete", taskId: "t1", status: "working" })).toBeNull(); + expect(parseMcpTask({ taskId: "t1", status: "completed" })).toBeNull(); + expect(parseMcpTask({ taskId: "t1", status: "done", result: {} })).toBeNull(); + expect(parseMcpTask({ taskId: "", status: "working" })).toBeNull(); + expect(parseMcpTask({ taskId: "t1", status: "failed", error: { code: -32603, message: "boom" } })).toMatchObject({ error: { code: -32603, message: "boom" } }); + expect(parseMcpTask({ taskId: "t1", status: "input_required", inputRequests: { a: { method: "elicitation/create", params: { mode: "url" } } } })) + .toMatchObject({ inputRequests: { a: { method: "elicitation/create" } } }); + }); + + it("bounds the server's timing hints and caps the task's life", () => { + expect(backgroundPollDelayMs({ pollIntervalMs: 1, status: "working" })).toBe(5_000); + expect(backgroundPollDelayMs({ pollIntervalMs: 99_999_999, status: "working" })).toBe(5 * 60_000); + expect(backgroundPollDelayMs({ pollIntervalMs: 5_000, status: "input_required" })).toBe(5 * 60_000); + expect(backgroundPollDelayMs({ pollIntervalMs: 5_000, status: "working", failures: 2 })).toBe(20_000); + const now = Date.parse("2026-11-12T00:00:00Z"); + expect(mcpTaskExpiresAt({ createdAt: new Date(now - 1_000), ttlMs: 10_000 }, now).getTime()).toBe(now + 9_000); + expect(mcpTaskExpiresAt({ createdAt: null, ttlMs: null }, now).getTime()).toBe(now + 7 * 24 * 60 * 60_000); + // A TTL extended days later never moves the cap past seven days from when Paperclip first saw the task. + const firstSeen = new Date(now - 6 * 24 * 60 * 60_000); + expect(mcpTaskExpiresAt({ createdAt: firstSeen, ttlMs: 30 * 24 * 60 * 60_000 }, now, firstSeen).getTime()).toBe(firstSeen.getTime() + 7 * 24 * 60 * 60_000); + }); + + it("reads at most 64 KiB of a provider's error body", async () => { + let pulled = 0; + const body = new ReadableStream({ + pull(controller) { pulled += 16 * 1024; controller.enqueue(new Uint8Array(16 * 1024).fill(32)); }, + }); + const transport = { headers: async () => ({ "MCP-Protocol-Version": MCP_MODERN_PROTOCOL_VERSION }), maxBytes: 1_000_000, + send: async () => new Response(body, { status: 500 }) }; + await expect(sendMcpTaskRequest(transport, "tasks/get", { taskId: "t1" })).rejects.toMatchObject({ kind: "http", httpStatus: 500 }); + expect(pulled).toBeLessThanOrEqual(128 * 1024); + }); + + it("seals task IDs at rest and binds them to their company and connection", () => { + const scope = { companyId: "c1", connectionId: "k1" }; + const sealed = sealMcpTaskId("secret", scope, "task-123"); + expect(sealed).not.toContain("task-123"); + expect(openMcpTaskId("secret", scope, sealed)).toBe("task-123"); + expect(openMcpTaskId("secret", { ...scope, companyId: "c2" }, sealed)).toBeNull(); + expect(openMcpTaskId("other", scope, sealed)).toBeNull(); + expect(mcpTaskIdIndex("secret", scope, "task-123")).toBe(mcpTaskIdIndex("secret", scope, "task-123")); + expect(mcpTaskIdIndex("secret", { ...scope, connectionId: "k2" }, "task-123")).not.toBe(mcpTaskIdIndex("secret", scope, "task-123")); + }); +}); + +type Recorded = { method: string; headers: Headers; body: Record }; +type FakeTask = { + status: "working" | "input_required" | "completed" | "failed" | "cancelled"; + gets: number; + /** Complete on its own after this many polls. */ + completeAfter?: number; + inputRequests?: Record; + /** Move on once these input keys are answered with tasks/update. */ + awaiting?: string[]; + result?: Record; + error?: Record; + ttlMs: number; + createdAt: string; + failInstead?: boolean; +}; + +/** + * A stateless (2026-07-28) server that answers long tools with a task. Like a + * compliant server it returns a task only to a client that declared the + * extension on that request, and requires `Mcp-Name` to match the task ID. + */ +function taskServer() { + const requests: Recorded[] = []; + const tasks = new Map(); + let forgetAll = false; + /** The next N task polls fail as if the app were briefly unreachable. */ + let failingGets = 0; + const tool = (name: string) => ({ name, description: name, inputSchema: { type: "object", properties: {} }, annotations: { readOnlyHint: true } }); + const ok = (id: unknown, result: Record) => Response.json({ jsonrpc: "2.0", id, result: { resultType: "complete", ...result } }); + const fail = (status: number, id: unknown, code: number, message: string) => Response.json({ jsonrpc: "2.0", id, error: { code, message } }, { status }); + const view = (taskId: string, task: FakeTask) => ({ + taskId, status: task.status, createdAt: task.createdAt, lastUpdatedAt: new Date().toISOString(), ttlMs: task.ttlMs, pollIntervalMs: 20, + ...(task.status === "completed" ? { result: task.result } : {}), + ...(task.status === "failed" ? { error: task.error } : {}), + ...(task.status === "input_required" ? { inputRequests: task.inputRequests } : {}), + }); + const handle = async (_url: string, init: RequestInit): Promise => { + const body = JSON.parse(String(init.body)); + const headers = new Headers(init.headers); + requests.push({ method: body.method, headers, body }); + const meta = body.params?._meta ?? {}; + if (meta[META_VERSION] !== MCP_MODERN_PROTOCOL_VERSION || headers.get("mcp-protocol-version") !== MCP_MODERN_PROTOCOL_VERSION) return fail(400, body.id, -32020, "Header mismatch"); + const declared = Boolean(meta[META_CAPABILITIES]?.extensions?.[MCP_TASKS_EXTENSION_ID]); + switch (body.method) { + case "server/discover": + return ok(body.id, { supportedVersions: [MCP_MODERN_PROTOCOL_VERSION], capabilities: { tools: {}, extensions: { [MCP_TASKS_EXTENSION_ID]: {} } } }); + case "tools/list": + return ok(body.id, { tools: ["build", "quick", "authorize", "ask_name", "explode", "short_lived", "garbled"].map(tool) }); + case "tools/call": { + const name = body.params.name; + if (name === "quick" || !declared) return ok(body.id, { content: [{ type: "text", text: `${name} done synchronously` }] }); + const taskId = `task-${randomUUID()}`; + const task: FakeTask = { status: "working", gets: 0, ttlMs: name === "short_lived" ? 300 : 3_600_000, createdAt: new Date().toISOString(), + result: { content: [{ type: "text", text: `${name} finished` }], structuredContent: { name }, isError: false } }; + if (name === "authorize") Object.assign(task, { status: "input_required", awaiting: [], inputRequests: { consent: { method: "elicitation/create", params: { mode: "url", message: "Approve access", url: "https://auth.example.com/consent?flow=7" } } } }); + if (name === "ask_name") Object.assign(task, { status: "input_required", awaiting: ["who"], inputRequests: { who: { method: "elicitation/create", params: { mode: "form", message: "Who is deploying?", requestedSchema: { type: "object", required: ["name"], properties: { name: { type: "string", title: "Your name" } } } } } } }); + if (name === "explode") Object.assign(task, { completeAfter: 1, failInstead: true }); + // A result Paperclip cannot record, standing in for a crash before the result is saved. + if (name === "garbled") Object.assign(task, { completeAfter: 1, result: { content: "not a content list" } }); + tasks.set(taskId, task); + return ok(body.id, { resultType: "task", ...view(taskId, task), status: task.status === "input_required" ? "working" : task.status }); + } + case "tasks/get": + case "tasks/update": + case "tasks/cancel": { + if (!declared) return fail(400, body.id, -32021, "Missing required client capability"); + if (headers.get("mcp-name") !== body.params.taskId) return fail(400, body.id, -32020, "Mcp-Name does not match"); + const task = tasks.get(body.params.taskId); + if (!task || forgetAll) return fail(200, body.id, -32602, "Failed to retrieve task: Task not found"); + if (body.method === "tasks/get" && failingGets > 0) { failingGets -= 1; return new Response(null, { status: 503 }); } + if (body.method === "tasks/cancel") { task.status = "cancelled"; return ok(body.id, {}); } + if (body.method === "tasks/update") { + const answered = Object.keys(body.params.inputResponses ?? {}); + task.awaiting = (task.awaiting ?? []).filter((key) => !answered.includes(key)); + if (task.status === "input_required" && !task.awaiting.length && answered.length) { + const response = body.params.inputResponses.who; + task.status = "completed"; + task.result = { content: [{ type: "text", text: `deployed by ${response?.content?.name ?? "nobody"}` }], isError: false }; + } + return ok(body.id, {}); + } + task.gets += 1; + if (task.status === "working" && task.completeAfter !== undefined && task.gets >= task.completeAfter) { + if (task.failInstead) Object.assign(task, { status: "failed", error: { code: -32603, message: "Build runner crashed" } }); + else task.status = "completed"; + } + return ok(body.id, view(body.params.taskId, task)); + } + default: + return fail(404, body.id, -32601, "Method not found"); + } + }; + const only = () => { + const ids = [...tasks.keys()]; + return { id: ids.at(-1)!, task: tasks.get(ids.at(-1)!)! }; + }; + return { + requests, tasks, handle, only, + count: (method: string) => requests.filter((request) => request.method === method).length, + finish: () => { only().task.status = "completed"; }, + /** The running task now needs a person's answer. */ + ask: () => Object.assign(only().task, { status: "input_required", awaiting: ["who"], inputRequests: { who: { method: "elicitation/create", params: { mode: "form", message: "Who is deploying?", requestedSchema: { type: "object", properties: { name: { type: "string" } } } } } } }), + forget: () => { forgetAll = true; }, + failGets: (count: number) => { failingGets = count; }, + }; +} + +const support = await getEmbeddedPostgresTestSupport(); +(support.supported ? describe : describe.skip)("MCP Tasks end to end", () => { + const actor = { actorType: "user" as const, actorId: "mcp-tasks-user", actorSource: "local_implicit" as const }; + let fixture: Awaited>; + let db: ReturnType; + let keyDir: string; + beforeAll(async () => { + keyDir = await mkdtemp(join(tmpdir(), "mcp-tasks-secrets-")); + vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY_FILE", join(keyDir, "key")); + fixture = await startEmbeddedPostgresTestDatabase("mcp-tasks-"); + db = createDb(fixture.connectionString); + // MCP Tasks are an experimental setting, off by default. + await instanceSettingsService(db).updateExperimental({ enableMcpTasks: true }); + }, 30_000); + afterAll(async () => { + await fixture?.cleanup(); + vi.unstubAllEnvs(); + if (keyDir) await rm(keyDir, { recursive: true, force: true }); + }); + + async function setup(server: ReturnType, input: { askFirst?: string[] } = {}) { + const [org] = await db.insert(companies).values({ name: `Tasks ${randomUUID()}`, issuePrefix: `T${randomUUID().slice(0, 5)}` }).returning(); + await db.insert(companyMemberships).values({ companyId: org.id, principalType: "user", principalId: actor.actorId, status: "active", membershipRole: "admin" }); + const [agent] = await db.insert(agents).values({ companyId: org.id, name: "Task agent", role: "engineer", adapterType: "process", adapterConfig: {}, runtimeConfig: {} }).returning(); + const [project] = await db.insert(projects).values({ companyId: org.id, name: "Tasks project" }).returning(); + const [issue] = await db.insert(issues).values({ companyId: org.id, projectId: project.id, title: "Ship it", status: "in_progress", assigneeAgentId: agent.id }).returning(); + const [run] = await db.insert(heartbeatRuns).values({ companyId: org.id, agentId: agent.id, invocationSource: "assignment", status: "running", contextSnapshot: { issueId: issue.id, projectId: project.id } }).returning(); + const options = { deploymentMode: "local_trusted" as const, deploymentExposure: "private" as const, + remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 as const }], remoteHttpRequest: server.handle }; + const service = toolAccessService(db, options); + const connected = await service.connectGalleryApp(org.id, { link: `https://tasks-${randomUUID().slice(0, 8)}.example.com/mcp`, name: "Builds" }, actor); + await service.finishGalleryAppConnection(org.id, connected.connectionId, { + enabledCatalogEntryIds: connected.catalog.map((entry) => entry.id), + askFirstCatalogEntryIds: connected.catalog.filter((entry) => input.askFirst?.includes(entry.toolName)).map((entry) => entry.id), access: "all_agents", + }, actor); + const gatewayOptions = { ...options, toolActionSigningSecret: "tasks-signing-key" }; + let gateway = createToolGatewayService(db, gatewayOptions); + const session = await gateway.createSession({ companyId: org.id, agentId: agent.id, runId: run.id }); + const names = (await gateway.listToolsForSession(session.token)).map((tool) => tool.name); + const toolName = (name: string) => names.find((candidate) => candidate.endsWith(`:${name.replace(/_/g, "-")}`))!; + const call = (name: string, extra: { timeoutMs?: number; idempotencyKey?: string; parameters?: Record } = {}) => + gateway.executeTool({ sessionToken: session.token, tool: toolName(name), parameters: extra.parameters ?? { ref: "main" }, + timeoutMs: extra.timeoutMs ?? 5_000, idempotencyKey: extra.idempotencyKey }); + const rows = () => db.select().from(toolMcpTasks).where(eq(toolMcpTasks.companyId, org.id)); + /** Background poll for this company only: other tests' tasks would go through this fake server too. */ + const poll = async (input: Parameters["pollDueMcpTasks"]>[0] = {}) => { + await db.update(toolMcpTasks).set({ nextPollAt: new Date(Date.now() + 60 * 60_000) }) + .where(and(ne(toolMcpTasks.companyId, org.id), lte(toolMcpTasks.nextPollAt, new Date()))); + return gateway.pollDueMcpTasks(input); + }; + return { + org, agent, issue, run, session, connected, call, rows, poll, + gateway: () => gateway, + /** A new process: no in-memory state survives, only the database. */ + restart: () => { forgetMcpHttpSessions(connected.connectionId); gateway = createToolGatewayService(db, gatewayOptions); return gateway; }, + }; + } + + it("does nothing about tasks while the experimental setting is off", async () => { + const server = taskServer(); + const { call, rows, gateway } = await setup(server); + await expect(call("build", { timeoutMs: 400 })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + await instanceSettingsService(db).updateExperimental({ enableMcpTasks: false }); + try { + expect((await instanceSettingsService(db).getExperimental()).enableMcpTasks).toBe(false); + const before = server.requests.length; + // Without the declaration the server answers synchronously, as for any client. + expect(await call("build", { parameters: { ref: "flag-off" } })).toMatchObject({ status: "completed", result: { content: "build done synchronously" } }); + const toolCall = server.requests.slice(before).find((request) => request.method === "tools/call")!; + expect(toolCall.body.params._meta[META_CAPABILITIES].extensions).not.toHaveProperty(MCP_TASKS_EXTENSION_ID); + // A stored task is neither attached to nor polled. + await db.update(toolMcpTasks).set({ nextPollAt: new Date(Date.now() - 1_000), leaseExpiresAt: null, leaseOwner: null }).where(eq(toolMcpTasks.companyId, (await rows())[0]!.companyId)); + expect(await gateway().pollDueMcpTasks()).toEqual({ processed: 0 }); + expect(await gateway().nextMcpTaskPollAt()).toBeNull(); + expect(server.requests.slice(before).filter((request) => request.method.startsWith("tasks/"))).toEqual([]); + } finally { + await instanceSettingsService(db).updateExperimental({ enableMcpTasks: true }); + } + }); + + it("waits on a task and returns the result exactly as a synchronous call would", async () => { + const server = taskServer(); + const { call, rows } = await setup(server); + const before = server.requests.length; + const pending = call("build"); + // The server completes the task while the call waits. + await vi.waitFor(() => expect(server.count("tasks/get")).toBeGreaterThan(0)); + server.finish(); + const result = await pending; + expect(result).toMatchObject({ status: "completed", result: { content: "build finished", data: { structuredContent: { name: "build" }, isError: false } } }); + const sent = server.requests.slice(before); + expect(sent.filter((request) => request.method === "tools/call")).toHaveLength(1); + const toolCall = sent.find((request) => request.method === "tools/call")!; + expect(toolCall.body.params._meta[META_CAPABILITIES].extensions[MCP_TASKS_EXTENSION_ID]).toEqual({}); + const [row] = await rows(); + expect(row).toMatchObject({ status: "completed", nextPollAt: null, leaseExpiresAt: null }); + expect(row!.deliveredAt).toBeInstanceOf(Date); + // The provider's task ID is never stored in the clear. + expect(JSON.stringify(row)).not.toContain(server.only().id); + }); + + it("leaves synchronous calls and older servers unchanged", async () => { + const server = taskServer(); + const { call, rows } = await setup(server); + expect(await call("quick")).toMatchObject({ status: "completed", result: { content: "quick done synchronously" } }); + expect(server.count("tasks/get")).toBe(0); + expect(await rows()).toEqual([]); + }); + + it("keeps a task past the tool timeout, and the repeated call attaches instead of starting the work again", async () => { + const server = taskServer(); + const { call, rows, gateway } = await setup(server); + await expect(call("build", { timeoutMs: 400 })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + const [held] = await rows(); + expect(held).toMatchObject({ status: "working", leaseExpiresAt: null }); + expect(held!.nextPollAt).toBeInstanceOf(Date); + expect(await gateway().nextMcpTaskPollAt()).toBeLessThanOrEqual(held!.nextPollAt!.getTime()); + server.finish(); + expect(await call("build", { timeoutMs: 2_000 })).toMatchObject({ status: "completed", result: { content: "build finished" } }); + expect(server.count("tools/call")).toBe(1); + // Different arguments are different work. + expect(await call("build", { parameters: { ref: "other" }, timeoutMs: 300 }).catch((error) => error)).toMatchObject({ reasonCode: "provider_task_pending" }); + expect(server.count("tools/call")).toBe(2); + }); + + it("attaches a retry with the same idempotency key to its task", async () => { + const server = taskServer(); + const { call, rows } = await setup(server); + await expect(call("build", { timeoutMs: 400, idempotencyKey: "deploy-42" })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + server.finish(); + expect(await call("build", { timeoutMs: 2_000, idempotencyKey: "deploy-42" })).toMatchObject({ status: "completed", result: { content: "build finished" } }); + expect(server.count("tools/call")).toBe(1); + const [row] = await rows(); + expect(row!.lastInvocationId).toBe(row!.invocationId); + }); + + it("never starts different work under a key whose task is still open", async () => { + const server = taskServer(); + const { call } = await setup(server); + await expect(call("build", { timeoutMs: 400, idempotencyKey: "deploy-43" })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + await expect(call("build", { timeoutMs: 400, idempotencyKey: "deploy-43", parameters: { ref: "other" } })) + .rejects.toMatchObject({ reasonCode: "idempotency_key_conflict" }); + expect(server.count("tools/call")).toBe(1); + }); + + it("resumes after a restart and delivers the result once, with no second tools/call", async () => { + const server = taskServer(); + const ctx = await setup(server); + await expect(ctx.call("build", { timeoutMs: 400 })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + // The process dies; the run that started the task was interrupted. + const fresh = ctx.restart(); + await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, ctx.run.id)); + const [row] = await ctx.rows(); + await db.update(toolMcpTasks).set({ nextPollAt: new Date(Date.now() - 1_000), leaseExpiresAt: new Date(Date.now() - 1_000) }).where(eq(toolMcpTasks.id, row!.id)); + server.finish(); + const wake = vi.fn(async () => undefined); + expect((await ctx.poll({ wake })).processed).toBeGreaterThanOrEqual(1); + expect(wake).toHaveBeenCalledTimes(1); + expect(wake).toHaveBeenCalledWith(expect.objectContaining({ agentId: ctx.agent.id, issueId: ctx.issue.id, status: "completed" })); + // Nothing is left to poll for this task. + expect((await ctx.rows())[0]).toMatchObject({ status: "completed", nextPollAt: null, leaseExpiresAt: null }); + // Nothing is left to do: another pass is quiet and wakes nobody. + await ctx.poll({ wake }); + expect(wake).toHaveBeenCalledTimes(1); + + // The recovered run repeats the call and collects the stored task's result. + const [recovered] = await db.insert(heartbeatRuns).values({ companyId: ctx.org.id, agentId: ctx.agent.id, invocationSource: "assignment", status: "running", contextSnapshot: { issueId: ctx.issue.id } }).returning(); + const session = await fresh.createSession({ companyId: ctx.org.id, agentId: ctx.agent.id, runId: recovered!.id }); + const tool = (await fresh.listToolsForSession(session.token)).find((candidate) => candidate.name.endsWith(":build"))!; + const result = await fresh.executeTool({ sessionToken: session.token, tool: tool.name, parameters: { ref: "main" }, timeoutMs: 2_000 }); + expect(result).toMatchObject({ status: "completed", result: { content: "build finished" } }); + expect(server.count("tools/call")).toBe(1); + const [delivered] = await ctx.rows(); + expect(delivered!.deliveredAt).toBeInstanceOf(Date); + expect(delivered!.runId).toBe(recovered!.id); + }); + + it("does not wake an agent whose run is still going; it re-checks after the run ends", async () => { + const server = taskServer(); + const ctx = await setup(server); + await expect(ctx.call("build", { timeoutMs: 400 })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + const [row] = await ctx.rows(); + await db.update(toolMcpTasks).set({ nextPollAt: new Date(Date.now() - 1_000) }).where(eq(toolMcpTasks.id, row!.id)); + server.finish(); + const wake = vi.fn(async () => undefined); + await ctx.poll({ wake }); + expect(wake).not.toHaveBeenCalled(); + const [deferred] = await ctx.rows(); + expect(deferred).toMatchObject({ status: "completed", wakeRequestedAt: null }); + expect(deferred!.nextPollAt!.getTime()).toBeGreaterThan(Date.now() + 60_000); + }); + + it("shows a URL input request as the provider link, never answers it, and continues once the app moves on", async () => { + const server = taskServer(); + const { call } = await setup(server); + const first = await call("authorize").catch((error) => error); + expect(first).toMatchObject({ reasonCode: "provider_interaction_required", details: { upstreamPending: { links: [{ url: "https://auth.example.com/consent?flow=7" }] } } }); + expect(server.count("tasks/update")).toBe(0); + // The person completes the step in the app; the app finishes on its own. + server.finish(); + expect(await call("authorize")).toMatchObject({ status: "completed", result: { content: "authorize finished" } }); + expect(server.count("tools/call")).toBe(1); + expect(server.count("tasks/update")).toBe(0); + }); + + it("asks a form input request on a question card and sends the person's answer with tasks/update", async () => { + const server = taskServer(); + const { call, issue, org } = await setup(server); + const first = await call("ask_name").catch((error) => error); + expect(first).toMatchObject({ reasonCode: "elicitation_required" }); + const [card] = await db.select().from(issueThreadInteractions).where(and(eq(issueThreadInteractions.companyId, org.id), eq(issueThreadInteractions.issueId, issue.id))); + expect(card).toMatchObject({ kind: "ask_user_questions", status: "pending" }); + // Asking again before anyone answers reuses the same card and sends nothing. + expect(await call("ask_name").catch((error) => error)).toMatchObject({ reasonCode: "elicitation_required" }); + expect(await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, issue.id))).toHaveLength(1); + expect(server.count("tasks/update")).toBe(0); + await db.update(issueThreadInteractions).set({ status: "answered", result: { version: 1, answers: [{ questionId: "name", optionIds: [], otherText: "Ada" }] } }) + .where(eq(issueThreadInteractions.id, card!.id)); + expect(await call("ask_name")).toMatchObject({ status: "completed", result: { content: "deployed by Ada" } }); + const update = server.requests.find((request) => request.method === "tasks/update")!; + expect(update.body.params.inputResponses).toEqual({ who: { action: "accept", content: { name: "Ada" } } }); + expect(server.count("tools/call")).toBe(1); + }); + + it("cancels the task when the run is stopped", async () => { + const server = taskServer(); + const { call, run, rows } = await setup(server); + const control = createAdapterExecutionControl(); + adapterExecutionControls.set(run.id, control); + try { + const pending = call("build", { timeoutMs: 10_000 }).catch((error) => error); + await vi.waitFor(() => expect(server.count("tasks/get")).toBeGreaterThan(0)); + control.controller.abort(); + expect(await pending).toMatchObject({ reasonCode: "provider_task_cancelled" }); + } finally { + adapterExecutionControls.delete(run.id); + } + expect(server.count("tasks/cancel")).toBe(1); + expect(server.only().task.status).toBe("cancelled"); + expect((await rows())[0]).toMatchObject({ status: "cancelled", errorCode: "run_cancelled" }); + }); + + it("keeps the task when only the caller goes away", async () => { + const server = taskServer(); + const { session, gateway, rows } = await setup(server); + const tool = (await gateway().listToolsForSession(session.token)).find((candidate) => candidate.name.endsWith(":build"))!; + const caller = new AbortController(); + const pending = gateway().executeTool({ sessionToken: session.token, tool: tool.name, parameters: { ref: "main" }, timeoutMs: 10_000, signal: caller.signal }).catch((error) => error); + await vi.waitFor(() => expect(server.count("tasks/get")).toBeGreaterThan(0)); + caller.abort(); + expect(await pending).toMatchObject({ reasonCode: "provider_task_pending" }); + expect(server.count("tasks/cancel")).toBe(0); + expect((await rows())[0]).toMatchObject({ status: "working" }); + }); + + it("cancels a background task once its issue is closed", async () => { + const server = taskServer(); + const { call, issue, rows, gateway, poll } = await setup(server); + await expect(call("build", { timeoutMs: 400 })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + await db.update(issues).set({ status: "cancelled" }).where(eq(issues.id, issue.id)); + await db.update(toolMcpTasks).set({ nextPollAt: new Date(Date.now() - 1_000) }).where(eq(toolMcpTasks.companyId, issue.companyId)); + await poll(); + expect(server.count("tasks/cancel")).toBe(1); + expect((await rows())[0]).toMatchObject({ status: "cancelled", errorCode: "issue_closed", nextPollAt: null }); + }); + + it("reports a failed task as a tool error", async () => { + const server = taskServer(); + const { call, org } = await setup(server); + const failure = await call("explode").catch((error) => error); + expect(failure).toMatchObject({ reasonCode: "provider_task_failed" }); + expect(failure.message).toContain("Build runner crashed"); + const [invocation] = await db.select().from(toolInvocations).where(eq(toolInvocations.companyId, org.id)); + expect(invocation).toMatchObject({ status: "failed", errorCode: "provider_task_failed" }); + }); + + it("ends with a clear error when the app forgets the task or its TTL passes, never a hang", async () => { + const forgetting = taskServer(); + const one = await setup(forgetting); + await expect(one.call("build", { timeoutMs: 400 })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + forgetting.forget(); + await expect(one.call("build")).rejects.toMatchObject({ reasonCode: "provider_task_expired" }); + expect((await one.rows())[0]).toMatchObject({ status: "expired", errorCode: "provider_task_unknown" }); + // The next call is new work. + await expect(one.call("build", { timeoutMs: 300 })).rejects.toBeTruthy(); + expect(forgetting.count("tools/call")).toBe(2); + + const shortLived = taskServer(); + const two = await setup(shortLived); + const started = Date.now(); + await expect(two.call("short_lived", { timeoutMs: 5_000 })).rejects.toMatchObject({ reasonCode: "provider_task_expired" }); + expect(Date.now() - started).toBeLessThan(3_000); + expect((await two.rows())[0]).toMatchObject({ status: "expired", errorCode: "ttl_expired" }); + }); + + it("lets a keyed retry collect its task after a crash mid-wait", async () => { + const server = taskServer(); + const { call, org } = await setup(server); + await expect(call("build", { timeoutMs: 400, idempotencyKey: "deploy-crash" })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + // A crash mid-wait leaves the call executing, with no error recorded. + await db.update(toolInvocations).set({ status: "executing", errorCode: null, errorMessage: null, completedAt: null }) + .where(eq(toolInvocations.companyId, org.id)); + await db.update(toolMcpTasks).set({ leaseExpiresAt: new Date(Date.now() - 1_000) }).where(eq(toolMcpTasks.companyId, org.id)); + server.finish(); + expect(await call("build", { timeoutMs: 2_000, idempotencyKey: "deploy-crash" })).toMatchObject({ status: "completed", result: { content: "build finished" } }); + expect(server.count("tools/call")).toBe(1); + }); + + it("keeps a keyed retry intact when the same key is reused with other arguments", async () => { + const server = taskServer(); + const { call, org } = await setup(server); + await expect(call("build", { timeoutMs: 400, idempotencyKey: "deploy-a" })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + // Separate pending work for the other arguments must not be collected under key A. + await expect(call("build", { timeoutMs: 400, parameters: { ref: "other" } })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + await expect(call("build", { timeoutMs: 400, idempotencyKey: "deploy-a", parameters: { ref: "other" } })) + .rejects.toMatchObject({ reasonCode: "idempotency_key_conflict" }); + const keyed = (await db.select().from(toolInvocations).where(eq(toolInvocations.companyId, org.id))) + .find((invocation) => invocation.idempotencyKey === "deploy-a"); + expect(keyed).toMatchObject({ errorCode: "provider_task_pending" }); + for (const id of [...server.tasks.keys()]) server.tasks.get(id)!.status = "completed"; + expect(await call("build", { timeoutMs: 2_000, idempotencyKey: "deploy-a" })).toMatchObject({ status: "completed" }); + expect(server.count("tools/call")).toBe(2); + }); + + it("hands a task to only one of two simultaneous callers", async () => { + const server = taskServer(); + const { call } = await setup(server); + await expect(call("build", { timeoutMs: 400 })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + const gets = server.count("tasks/get"); + const both = Promise.all([call("build", { timeoutMs: 3_000 }).catch((error) => error), call("build", { timeoutMs: 3_000 }).catch((error) => error)]); + // Both calls have looked for the task before it finishes. + await vi.waitFor(() => expect(server.count("tasks/get")).toBeGreaterThan(gets)); + server.finish(); + const outcomes = await both; + expect(outcomes.filter((outcome) => outcome?.status === "completed")).toHaveLength(1); + expect(outcomes.filter((outcome) => outcome?.reasonCode === "provider_task_pending")).toHaveLength(1); + expect(server.count("tools/call")).toBe(1); + }); + + it("never revives a task it cancelled in the background", async () => { + const server = taskServer(); + const { call, issue, gateway, poll } = await setup(server); + await expect(call("build", { timeoutMs: 400 })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + await db.update(issues).set({ status: "cancelled" }).where(eq(issues.id, issue.id)); + await db.update(toolMcpTasks).set({ nextPollAt: new Date(Date.now() - 1_000) }).where(eq(toolMcpTasks.companyId, issue.companyId)); + await poll(); + // The app had not stopped yet, and the task is reopened. + server.only().task.status = "working"; + await db.update(issues).set({ status: "in_progress" }).where(eq(issues.id, issue.id)); + const gets = server.count("tasks/get"); + await expect(call("build", { timeoutMs: 1_000 })).rejects.toMatchObject({ reasonCode: "provider_task_cancelled" }); + expect(server.count("tasks/get")).toBe(gets); + }); + + it("wakes the agent when a background task needs a link opened, and its next call shows the link", async () => { + const server = taskServer(); + const ctx = await setup(server); + await expect(ctx.call("build", { timeoutMs: 400 })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, ctx.run.id)); + Object.assign(server.only().task, { status: "input_required", inputRequests: { consent: { method: "elicitation/create", params: { mode: "url", message: "Approve access", url: "https://auth.example.com/consent?flow=9" } } } }); + await db.update(toolMcpTasks).set({ nextPollAt: new Date(Date.now() - 1_000) }).where(eq(toolMcpTasks.companyId, ctx.org.id)); + const wake = vi.fn(async () => undefined); + await ctx.poll({ wake }); + expect(wake).toHaveBeenCalledWith(expect.objectContaining({ status: "input_required", wakeKey: expect.stringContaining(":input:") })); + // Asked once: the next background pass does not wake again. + await db.update(toolMcpTasks).set({ nextPollAt: new Date(Date.now() - 1_000) }).where(eq(toolMcpTasks.companyId, ctx.org.id)); + await ctx.poll({ wake }); + expect(wake).toHaveBeenCalledTimes(1); + const [woken] = await db.insert(heartbeatRuns).values({ companyId: ctx.org.id, agentId: ctx.agent.id, invocationSource: "assignment", status: "running", contextSnapshot: { issueId: ctx.issue.id } }).returning(); + const session = await ctx.gateway().createSession({ companyId: ctx.org.id, agentId: ctx.agent.id, runId: woken!.id }); + const tool = (await ctx.gateway().listToolsForSession(session.token)).find((candidate) => candidate.name.endsWith(":build"))!; + expect(await ctx.gateway().executeTool({ sessionToken: session.token, tool: tool.name, parameters: { ref: "main" }, timeoutMs: 2_000 }).catch((error) => error)) + .toMatchObject({ reasonCode: "provider_interaction_required", details: { upstreamPending: { links: [{ url: "https://auth.example.com/consent?flow=9" }] } } }); + }); + + it("shows rotating form questions on cards without spending wakes", async () => { + const server = taskServer(); + const ctx = await setup(server); + await expect(ctx.call("build", { timeoutMs: 400 })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, ctx.run.id)); + const wake = vi.fn(async () => undefined); + for (let round = 0; round < 6; round += 1) { + // The provider rotates its input keys on every poll. + Object.assign(server.only().task, { status: "input_required", inputRequests: { [`k${round}`]: { method: "elicitation/create", params: { mode: "form", message: "Again?", requestedSchema: { type: "object", properties: {} } } } } }); + await db.update(toolMcpTasks).set({ nextPollAt: new Date(Date.now() - 1_000), inputWakeAt: null }).where(eq(toolMcpTasks.companyId, ctx.org.id)); + await ctx.poll({ wake }); + } + // Form questions go straight onto cards, so no wake is spent on them. + expect(wake).toHaveBeenCalledTimes(0); + const cards = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, ctx.issue.id)); + expect(cards).toHaveLength(6); + const [row] = await ctx.rows(); + expect(row!.surfacedInputKeys.length).toBeLessThanOrEqual(64); + }); + + it("caps wakes and cards when a provider keeps rotating its questions", async () => { + const server = taskServer(); + const ctx = await setup(server); + await expect(ctx.call("build", { timeoutMs: 400 })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, ctx.run.id)); + const wake = vi.fn(async () => undefined); + for (let round = 0; round < 14; round += 1) { + Object.assign(server.only().task, { status: "input_required", inputRequests: { + [`f${round}`]: { method: "elicitation/create", params: { mode: "form", message: "Again?", requestedSchema: { type: "object", properties: {} } } }, + [`u${round}`]: { method: "elicitation/create", params: { mode: "url", message: "Open", url: `https://auth.example.com/step?n=${round}` } }, + } }); + await db.update(toolMcpTasks).set({ nextPollAt: new Date(Date.now() - 1_000), inputWakeAt: null }).where(eq(toolMcpTasks.companyId, ctx.org.id)); + await ctx.poll({ wake }); + } + expect(wake).toHaveBeenCalledTimes(3); + expect(await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, ctx.issue.id))).toHaveLength(10); + expect((await ctx.rows())[0]!.inputWakeCount).toBe(3); + }); + + it("keeps two provider questions on the same task answerable side by side", async () => { + const server = taskServer(); + const ctx = await setup(server); + expect(await ctx.call("ask_name").catch((error) => error)).toMatchObject({ reasonCode: "elicitation_required" }); + await expect(ctx.call("build", { timeoutMs: 400 })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + server.ask(); + await db.update(toolMcpTasks).set({ nextPollAt: new Date(Date.now() - 1_000), leaseExpiresAt: null, leaseOwner: null }) + .where(and(eq(toolMcpTasks.companyId, ctx.org.id), eq(toolMcpTasks.catalogToolName, "build"))); + await ctx.poll(); + const cards = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, ctx.issue.id)); + expect(cards).toHaveLength(2); + expect(cards.every((card) => card.status === "pending")).toBe(true); + expect(server.count("tasks/update")).toBe(0); + }); + + it("puts a follow-up question on a card even when no wake is left", async () => { + const server = taskServer(); + const ctx = await setup(server); + await expect(ctx.call("build", { timeoutMs: 400 })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + await db.update(toolMcpTasks).set({ inputWakeCount: 3, inputWakeAt: new Date(), nextPollAt: new Date(Date.now() - 1_000) }).where(eq(toolMcpTasks.companyId, ctx.org.id)); + server.ask(); + await ctx.poll({ wake: vi.fn(async () => undefined) }); + const [card] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, ctx.issue.id)); + expect(card).toMatchObject({ kind: "ask_user_questions", status: "pending", continuationPolicy: "wake_assignee" }); + }); + + it("stops background work once the grant is revoked", async () => { + const server = taskServer(); + const ctx = await setup(server); + await expect(ctx.call("build", { timeoutMs: 400 })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.connectionId, ctx.connected.connectionId)); + await db.update(toolMcpTasks).set({ nextPollAt: new Date(Date.now() - 1_000), leaseExpiresAt: null, leaseOwner: null }).where(eq(toolMcpTasks.companyId, ctx.org.id)); + // Count only this task's requests: in tests every gateway sends through + // this fake server, so other tests' due tasks may be polled here too. + const taskId = server.only().id; + const ownGets = () => server.requests.filter((request) => request.method === "tasks/get" && request.body.params.taskId === taskId).length; + const gets = ownGets(); + await ctx.poll(); + expect(ownGets()).toBe(gets); + expect((await ctx.rows())[0]).toMatchObject({ status: "expired", errorCode: "access_removed", nextPollAt: null }); + }); + + it("keeps a completed task recoverable until its result is recorded, then wakes the agent", async () => { + const server = taskServer(); + const ctx = await setup(server); + await expect(ctx.call("garbled")).rejects.toMatchObject({ reasonCode: "remote_mcp_malformed_response" }); + const [held] = await ctx.rows(); + expect(held).toMatchObject({ status: "completed", deliveredAt: null }); + // Background work still has a deadline for it: when the hold ends. + expect(held!.nextPollAt).toBeInstanceOf(Date); + expect(held!.nextPollAt!.getTime()).toBe(held!.leaseExpiresAt!.getTime()); + await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, ctx.run.id)); + await db.update(toolMcpTasks).set({ nextPollAt: new Date(Date.now() - 1_000), leaseExpiresAt: new Date(Date.now() - 1_000) }).where(eq(toolMcpTasks.id, held!.id)); + const wake = vi.fn(async () => undefined); + await ctx.poll({ wake }); + expect(wake).toHaveBeenCalledWith(expect.objectContaining({ taskRecordId: held!.id, status: "completed" })); + }); + + it("keeps the caller's identity with the task for background checks", async () => { + const server = taskServer(); + const ctx = await setup(server); + await db.update(heartbeatRuns).set({ responsibleUserId: actor.actorId }).where(eq(heartbeatRuns.id, ctx.run.id)); + const session = await ctx.gateway().createSession({ companyId: ctx.org.id, agentId: ctx.agent.id, runId: ctx.run.id }); + const tool = (await ctx.gateway().listToolsForSession(session.token)).find((candidate) => candidate.name.endsWith(":build"))!; + await expect(ctx.gateway().executeTool({ sessionToken: session.token, tool: tool.name, parameters: { ref: "main" }, timeoutMs: 400 })) + .rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + expect((await ctx.rows())[0]).toMatchObject({ responsibleUserId: actor.actorId }); + }); + + it("records a task from a saved legacy connection that turns out to be stateless", async () => { + const server = taskServer(); + const ctx = await setup(server); + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, ctx.connected.connectionId)); + await db.update(toolConnections).set({ config: { ...connection!.config, mcpProtocolVersion: "2025-11-25" } }).where(eq(toolConnections.id, connection!.id)); + const fresh = ctx.restart(); + const tool = (await fresh.listToolsForSession(ctx.session.token)).find((candidate) => candidate.name.endsWith(":build"))!; + await expect(fresh.executeTool({ sessionToken: ctx.session.token, tool: tool.name, parameters: { ref: "main" }, timeoutMs: 1_500 })) + .rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + expect((await ctx.rows())[0]).toMatchObject({ protocolVersion: MCP_MODERN_PROTOCOL_VERSION, status: "working" }); + expect(server.tasks.size).toBe(1); + }); + + it("never wakes twice when a wake was already requested before a crash", async () => { + const server = taskServer(); + const ctx = await setup(server); + await expect(ctx.call("build", { timeoutMs: 400 })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, ctx.run.id)); + const [row] = await ctx.rows(); + server.finish(); + // A previous pass woke the agent, then crashed before recording it on the task. + await db.insert(agentWakeupRequests).values({ companyId: ctx.org.id, agentId: ctx.agent.id, source: "automation", idempotencyKey: `mcp-task:${row!.id}:settled` }); + await db.update(toolMcpTasks).set({ nextPollAt: new Date(Date.now() - 1_000), leaseExpiresAt: null, leaseOwner: null }).where(eq(toolMcpTasks.id, row!.id)); + const wake = vi.fn(async () => undefined); + await ctx.poll({ wake }); + expect(wake).not.toHaveBeenCalled(); + expect((await ctx.rows())[0]!.wakeRequestedAt).toBeInstanceOf(Date); + }); + + it("keeps an approved action's approval while its provider task is still running", async () => { + const server = taskServer(); + const ctx = await setup(server, { askFirst: ["build"] }); + await expect(ctx.call("build")).rejects.toMatchObject({ reasonCode: "approval_required" }); + const [pending] = await db.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, ctx.org.id)); + if (pending!.approvalId) await db.update(approvals).set({ status: "approved", decidedByUserId: actor.actorId, decidedAt: new Date() }).where(eq(approvals.id, pending!.approvalId)); + // The app becomes briefly unreachable, so the approved execution hands the task off. + server.failGets(3); + await ctx.gateway().approveActionRequest({ companyId: ctx.org.id, actionRequestId: pending!.id, actor: { userId: actor.actorId } }).catch((error) => error); + expect(server.count("tools/call")).toBe(1); + const [request] = await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending!.id)); + expect(request).toMatchObject({ status: "approved" }); + const [invocation] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending!.invocationId)); + expect(invocation).toMatchObject({ status: "awaiting_approval", errorCode: "provider_task_pending", startedAt: null }); + // The next execution of the same approved action collects the task, without a second approval or tools/call. + server.finish(); + expect(await ctx.call("build", { timeoutMs: 3_000 })).toMatchObject({ result: { content: "build finished" } }); + expect(server.count("tools/call")).toBe(1); + }); + + it("keeps tasks for different forwarded tenants apart and forwards the tenant in the background", async () => { + const server = taskServer(); + const ctx = await setup(server); + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, ctx.connected.connectionId)); + await db.update(toolConnections).set({ config: { ...connection!.config, headerPolicy: { passthrough: { allow: ["x-tenant-id"] } } } }) + .where(eq(toolConnections.id, connection!.id)); + const tool = (await ctx.gateway().listToolsForSession(ctx.session.token)).find((candidate) => candidate.name.endsWith(":build"))!; + const callAs = (tenant: string, timeoutMs = 400) => ctx.gateway().executeTool({ sessionToken: ctx.session.token, tool: tool.name, + parameters: { ref: "main" }, timeoutMs, callerHeaders: { "x-tenant-id": tenant } }); + await expect(callAs("acme")).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + await expect(callAs("globex")).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + expect(server.count("tools/call")).toBe(2); + const rows = await ctx.rows(); + expect(rows.every((row) => row.sealedCallerHeaders && !row.sealedCallerHeaders.includes("acme"))).toBe(true); + await db.update(toolMcpTasks).set({ nextPollAt: new Date(Date.now() - 1_000), leaseExpiresAt: null, leaseOwner: null }).where(eq(toolMcpTasks.companyId, ctx.org.id)); + const before = server.requests.length; + await ctx.poll(); + const background = server.requests.slice(before).filter((request) => request.method === "tasks/get"); + expect(background.map((request) => request.headers.get("x-tenant-id")).sort()).toEqual(["acme", "globex"]); + for (const task of server.tasks.values()) task.status = "completed"; + expect(await callAs("acme", 2_000)).toMatchObject({ result: { content: "build finished" } }); + expect(server.count("tools/call")).toBe(2); + }); + + it("refuses a keyed retry from another tenant without disturbing the original retry", async () => { + const server = taskServer(); + const ctx = await setup(server); + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, ctx.connected.connectionId)); + await db.update(toolConnections).set({ config: { ...connection!.config, headerPolicy: { passthrough: { allow: ["x-tenant-id"] } } } }) + .where(eq(toolConnections.id, connection!.id)); + const tool = (await ctx.gateway().listToolsForSession(ctx.session.token)).find((candidate) => candidate.name.endsWith(":build"))!; + const callAs = (tenant: string, timeoutMs = 400) => ctx.gateway().executeTool({ sessionToken: ctx.session.token, tool: tool.name, + parameters: { ref: "main" }, timeoutMs, idempotencyKey: "deploy-tenant", callerHeaders: { "x-tenant-id": tenant } }); + await expect(callAs("acme")).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + await expect(callAs("globex")).rejects.toMatchObject({ reasonCode: "idempotency_key_conflict" }); + const keyed = (await db.select().from(toolInvocations).where(eq(toolInvocations.companyId, ctx.org.id))) + .find((invocation) => invocation.idempotencyKey === "deploy-tenant"); + expect(keyed).toMatchObject({ errorCode: "provider_task_pending" }); + server.finish(); + expect(await callAs("acme", 2_000)).toMatchObject({ result: { content: "build finished" } }); + expect(server.count("tools/call")).toBe(1); + }); + + it("recreates a question card that was marked shown but never created", async () => { + const server = taskServer(); + const ctx = await setup(server); + await expect(ctx.call("build", { timeoutMs: 400 })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + server.ask(); + // A crash between marking the question shown and creating its card. + await db.update(toolMcpTasks).set({ surfacedInputKeys: ["who"], nextPollAt: new Date(Date.now() - 1_000), leaseExpiresAt: null, leaseOwner: null }) + .where(eq(toolMcpTasks.companyId, ctx.org.id)); + await ctx.poll(); + const [card] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, ctx.issue.id)); + expect(card).toMatchObject({ kind: "ask_user_questions", status: "pending" }); + }); + + it("never lets another agent attach to a task", async () => { + const server = taskServer(); + const ctx = await setup(server); + await expect(ctx.call("build", { timeoutMs: 400 })).rejects.toMatchObject({ reasonCode: "provider_task_pending" }); + const [other] = await db.insert(agents).values({ companyId: ctx.org.id, name: "Other agent", role: "engineer", adapterType: "process", adapterConfig: {}, runtimeConfig: {} }).returning(); + await db.update(issues).set({ assigneeAgentId: other!.id }).where(eq(issues.id, ctx.issue.id)); + const [otherRun] = await db.insert(heartbeatRuns).values({ companyId: ctx.org.id, agentId: other!.id, invocationSource: "assignment", status: "running", contextSnapshot: { issueId: ctx.issue.id } }).returning(); + const session = await ctx.gateway().createSession({ companyId: ctx.org.id, agentId: other!.id, runId: otherRun!.id }); + const tool = (await ctx.gateway().listToolsForSession(session.token)).find((candidate) => candidate.name.endsWith(":build"))!; + await ctx.gateway().executeTool({ sessionToken: session.token, tool: tool.name, parameters: { ref: "main" }, timeoutMs: 300 }).catch(() => undefined); + expect(server.count("tools/call")).toBe(2); + }); +}); diff --git a/server/src/index.ts b/server/src/index.ts index c94ed99f2bc..c8c2c71b055 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -34,6 +34,7 @@ import { registerToolReviewInterruptionWork } from "./services/tool-review-inter import { registerToolReviewRecoveryWork } from "./services/tool-review-recovery-work.js"; import { registerToolReviewExpiryWork } from "./services/tool-review-expiry-work.js"; import { registerGatewayCredentialExpiryWork } from "./services/gateway-credential-expiry-work.js"; +import { registerMcpTaskWork } from "./services/mcp-task-work.js"; import { registerSecretProposalExpiryWork } from "./services/secret-proposal-expiry-work.js"; import { registerCustomImageCleanupWork } from "./services/custom-image-cleanup-work.js"; import { registerWorkspaceRecoveryWork } from "./services/workspace-recovery-work.js"; @@ -1600,6 +1601,13 @@ async function startServerWithDatabaseTeardown( ? registerGatewayCredentialExpiryWork(deliveryWork, app.locals.toolGateway, () => !isIdleTaskDrainActive() && !heartbeatSchedulerStopped && !isWarmStandby()).ready : app.locals.toolGateway.cleanupExpiredSessions()).catch((err: unknown) => logger.error({ err }, "startup gateway token cleanup failed")))); + // Provider tasks outlive calls, restarts, and deploys; polling resumes from + // the rows. Tool calls create tasks whether or not heartbeats are scheduled, + // so recovery always runs; only waking an agent needs the scheduler. + trackHeartbeatSchedulerWork(startupTimeline.background("mcp_tasks", () => timeStartupRecovery("mcp_tasks", () => + registerMcpTaskWork(deliveryWork, app.locals.toolGateway, heartbeat, + () => !isIdleTaskDrainActive() && !heartbeatSchedulerStopped && !isWarmStandby()).ready) + .catch((err: unknown) => logger.error({ err }, "startup provider task recovery failed")))); trackHeartbeatSchedulerWork(startupTimeline.background("delivery_workers", () => timeStartupRecovery("delivery_workers", () => Promise.all([budgetEnforcementWorker, accountingWorker, fastResponseWorker, ...deliveryWorkers].map(worker => worker.ready))))); trackHeartbeatSchedulerWork(startupTimeline.background("github_connections", diff --git a/server/src/services/delivery-work-notifications.ts b/server/src/services/delivery-work-notifications.ts index fce4628002e..5260f9a1e46 100644 --- a/server/src/services/delivery-work-notifications.ts +++ b/server/src/services/delivery-work-notifications.ts @@ -133,6 +133,7 @@ export const DELIVERY_QUEUES = { museMaintenance: "muse-maintenance", mergedPullRequestConfirmations: "merged-pull-request-confirmations", mcpEvents: "mcp-events", + mcpTasks: "mcp-tasks", dotEvents: "dot-events", grokDispatch: "grok-dispatch", skillSourceSync: "skill-source-sync", diff --git a/server/src/services/idle-sleep-safety.ts b/server/src/services/idle-sleep-safety.ts index c560331574c..4231ddc9f27 100644 --- a/server/src/services/idle-sleep-safety.ts +++ b/server/src/services/idle-sleep-safety.ts @@ -98,6 +98,11 @@ const WORK_CHECKS = [ ('preparing', 'verifying', 'pausing', 'resuming', 'terminating', 'cleaning_up')`), workCheck("decision_invocations", `SELECT 1 FROM decision_invocations WHERE status = 'running'`), workCheck("prompt_injection_invocations", `SELECT 1 FROM prompt_injection_invocations WHERE status = 'running'`), + // A pending provider task (MCP Tasks) is polled: the provider cannot wake + // Paperclip, so the instance stays awake until the task is settled. + // Only while the MCP Tasks setting is on; off, nothing polls these rows. + workCheck("tool_mcp_tasks", `SELECT 1 FROM tool_mcp_tasks WHERE next_poll_at IS NOT NULL + AND EXISTS (SELECT 1 FROM instance_settings WHERE (experimental->>'enableMcpTasks') = 'true')`), // Persistent machine credentials can receive work without a human opening // the instance. They need an ingress wake contract before we can sleep. workCheck("agent_api_keys", incomingWakeWorkQuery("agent_api_keys")!), diff --git a/server/src/services/instance-settings.ts b/server/src/services/instance-settings.ts index 1719878f28a..abede64c234 100644 --- a/server/src/services/instance-settings.ts +++ b/server/src/services/instance-settings.ts @@ -294,6 +294,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta enableWorkspaceDirtyQuarantineRepair: parsed.data.enableWorkspaceDirtyQuarantineRepair ?? true, enableOwnerInstanceAdmin: parsed.data.enableOwnerInstanceAdmin ?? false, enableSandboxDuplexBridge: parsed.data.enableSandboxDuplexBridge ?? false, + enableMcpTasks: parsed.data.enableMcpTasks ?? false, enableRunnerPreviewIngress: parsed.data.enableRunnerPreviewIngress ?? false, enableWorktreeRunExecution: parsed.data.enableWorktreeRunExecution ?? false, worktreeRunExecutionActivatedAt: parsed.data.worktreeRunExecutionActivatedAt ?? null, @@ -353,6 +354,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta enableWorkspaceDirtyQuarantineRepair: true, enableOwnerInstanceAdmin: false, enableSandboxDuplexBridge: false, + enableMcpTasks: false, enableRunnerPreviewIngress: false, enableWorktreeRunExecution: false, worktreeRunExecutionActivatedAt: null, diff --git a/server/src/services/mcp-http.ts b/server/src/services/mcp-http.ts index b8200d846b4..d5f74e936d8 100644 --- a/server/src/services/mcp-http.ts +++ b/server/src/services/mcp-http.ts @@ -32,6 +32,10 @@ export const MCP_ERROR_MISSING_CLIENT_CAPABILITY = -32021; export const MCP_ERROR_UNSUPPORTED_PROTOCOL_VERSION = -32022; const MODERN_ERROR_CODES = new Set([MCP_ERROR_HEADER_MISMATCH, MCP_ERROR_MISSING_CLIENT_CAPABILITY, MCP_ERROR_UNSUPPORTED_PROTOCOL_VERSION]); +/** MCP Tasks extension; see mcp-tasks.ts. Kept here so request building has no import cycle. */ +export const MCP_TASKS_EXTENSION_ID = "io.modelcontextprotocol/tasks"; +const MCP_TASK_METHODS = new Set(["tasks/get", "tasks/update", "tasks/cancel"]); + const META_PROTOCOL_VERSION = "io.modelcontextprotocol/protocolVersion"; const META_CLIENT_CAPABILITIES = "io.modelcontextprotocol/clientCapabilities"; const META_CLIENT_INFO = "io.modelcontextprotocol/clientInfo"; @@ -50,10 +54,15 @@ export function isModernMcpProtocolVersion(version: unknown): version is string * they may then return URL input requests, which Paperclip shows as a link. * Legacy sessions keep the handshake capabilities they have always received. */ -export function mcpClientCapabilities(protocolVersion: string): Record { - // The skills extension is defined against stateless MCP only. +export function mcpClientCapabilities(protocolVersion: string, options: { declareTasks?: boolean } = {}): Record { + // The skills and tasks extensions are defined against stateless MCP only. + // Tasks are declared only where Paperclip can wait on one: a provider tool + // call over HTTP and the task requests themselves (spec: per request). return isModernMcpProtocolVersion(protocolVersion) - ? { elicitation: { url: {} }, extensions: { ...MCP_APPS_CLIENT_CAPABILITY, ...MCP_SKILLS_CLIENT_CAPABILITY } } + ? { elicitation: { url: {} }, extensions: { + ...MCP_APPS_CLIENT_CAPABILITY, ...MCP_SKILLS_CLIENT_CAPABILITY, + ...(options.declareTasks ? { [MCP_TASKS_EXTENSION_ID]: {} } : {}), + } } : { extensions: MCP_APPS_CLIENT_CAPABILITY }; } @@ -191,7 +200,7 @@ export type McpJsonRpcRequest = { id?: string | number; method: string; params?: export function mcpHttpRequestInit( headers: Record | undefined, message: McpJsonRpcRequest, - options: { toolInputSchema?: unknown } = {}, + options: { toolInputSchema?: unknown; declareTasks?: boolean } = {}, ): { method: "POST"; headers: Record; body: string } { const requestHeaders = mcpHttpRequestHeaders(headers); const protocolVersion = mcpProtocolVersionOf(headers); @@ -202,7 +211,7 @@ export function mcpHttpRequestInit( _meta: { ...record(params._meta), [META_PROTOCOL_VERSION]: protocolVersion, - [META_CLIENT_CAPABILITIES]: mcpClientCapabilities(protocolVersion), + [META_CLIENT_CAPABILITIES]: mcpClientCapabilities(protocolVersion, { declareTasks: options.declareTasks }), [META_CLIENT_INFO]: MCP_CLIENT_INFO, }, }; @@ -210,7 +219,8 @@ export function mcpHttpRequestInit( for (const key of Object.keys(requestHeaders)) if (key.toLowerCase().startsWith("mcp-param-")) delete requestHeaders[key]; setHeader(requestHeaders, "Mcp-Method", message.method); const name = message.method === "resources/read" ? params.uri - : message.method === "tools/call" || message.method === "prompts/get" ? params.name : undefined; + : message.method === "tools/call" || message.method === "prompts/get" ? params.name + : MCP_TASK_METHODS.has(message.method) ? params.taskId : undefined; if (typeof name === "string") setHeader(requestHeaders, "Mcp-Name", encodeMcpHeaderValue(name)); else for (const key of Object.keys(requestHeaders)) if (key.toLowerCase() === "mcp-name") delete requestHeaders[key]; if (message.method === "tools/call" && options.toolInputSchema !== undefined) { diff --git a/server/src/services/mcp-task-work.ts b/server/src/services/mcp-task-work.ts new file mode 100644 index 00000000000..54ea554f0b9 --- /dev/null +++ b/server/src/services/mcp-task-work.ts @@ -0,0 +1,53 @@ +import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; +import { DELIVERY_QUEUES } from "./delivery-work-notifications.js"; +import { registerDeadlineWork } from "./deadline-work.js"; +import type { heartbeatService } from "./heartbeat.js"; +import type { createToolGatewayService } from "./tool-gateway.js"; + +/** + * Background polling for provider tasks (MCP Tasks) that outlived the call + * that started them, including across restarts and deploys. + * + * Trigger: a task row written or released by a live call notifies this queue; + * startup runs once and reconstructs from the rows. Deadline: the earliest + * `next_poll_at` (never earlier than a live call's lease). Quiet: no row has a + * next poll, which is true once every task is delivered, expired, or woken. + */ +export function registerMcpTaskWork( + coordinator: ReturnType, + gateway: Pick, "pollDueMcpTasks" | "nextMcpTaskPollAt">, + heartbeat: Pick, "wakeup"> | null, + canRun: () => boolean, +) { + return registerDeadlineWork(coordinator, DELIVERY_QUEUES.mcpTasks, { + retryMs: 30_000, + continuationMs: 1_000, + canRun, + run: (signal) => gateway.pollDueMcpTasks({ + signal, + wake: heartbeat ? async (task) => { + // The agent's repeated call collects the result; nothing is replayed. + await heartbeat.wakeup(task.agentId, { + source: "automation", + triggerDetail: "system", + reason: "issue_commented", + payload: { issueId: task.issueId, mutation: "tool_task" }, + // Distinct per reason: an input wake must never stand in for the completion wake. + idempotencyKey: task.wakeKey, + requestedByActorType: "system", + requestedByActorId: "tool_gateway", + contextSnapshot: { + issueId: task.issueId, + taskId: task.issueId, + mutation: "tool_task", + wakeReason: "issue_commented", + source: "mcp_task.settled", + toolTask: { tool: task.toolName, status: task.status }, + }, + issueStateGuard: { statuses: ["todo", "in_progress", "in_review", "blocked"], assigneeAgentId: task.agentId }, + }); + } : undefined, + }), + next: () => gateway.nextMcpTaskPollAt(), + }); +} diff --git a/server/src/services/mcp-tasks.ts b/server/src/services/mcp-tasks.ts new file mode 100644 index 00000000000..edbb3080675 --- /dev/null +++ b/server/src/services/mcp-tasks.ts @@ -0,0 +1,294 @@ +import { createCipheriv, createDecipheriv, createHash, createHmac, hkdfSync, randomBytes, randomUUID } from "node:crypto"; +import { MCP_TASKS_EXTENSION_ID, mcpHttpRequestInit, readMcpHttpResponse } from "./mcp-http.js"; + +/** + * MCP Tasks extension (io.modelcontextprotocol/tasks, 2026-07-28). + * + * A server may answer `tools/call` with a durable task handle instead of the + * result. This module owns the protocol: parsing task states, bounding the + * server's timing hints, and sending `tasks/get`, `tasks/update`, and + * `tasks/cancel`. The tool gateway owns credentials, storage, and delivery. + */ +export { MCP_TASKS_EXTENSION_ID }; + +export const MCP_TASK_STATUSES = ["working", "input_required", "completed", "failed", "cancelled"] as const; +export type McpTaskStatus = typeof MCP_TASK_STATUSES[number]; +/** `expired` is Paperclip's own: the provider no longer knows the task, or its TTL passed. */ +export type McpTaskRecordStatus = McpTaskStatus | "expired"; +export const MCP_TASK_ACTIVE_STATUSES: readonly McpTaskRecordStatus[] = ["working", "input_required"]; + +/** Paperclip stops tracking any task after this long, whatever its TTL says. */ +export const MCP_TASK_MAX_LIFETIME_MS = 7 * 24 * 60 * 60_000; +const MAX_TASK_ID_LENGTH = 512; +const INLINE_POLL_MIN_MS = 200; +const INLINE_POLL_MAX_MS = 5_000; +const BACKGROUND_POLL_MIN_MS = 5_000; +const BACKGROUND_POLL_MAX_MS = 5 * 60_000; +/** + * A task waiting for a person is checked slowly: nothing happens until they + * answer, and their answer wakes the agent, whose call checks right away. + */ +const BACKGROUND_INPUT_POLL_MS = 5 * 60_000; + +export type McpTaskInputRequest = { method: string; params: Record }; + +export type McpTaskState = { + taskId: string; + status: McpTaskStatus; + ttlMs: number | null; + pollIntervalMs: number | null; + createdAt: Date | null; + result?: Record; + error?: { code: number | null; message: string }; + inputRequests?: Record; +}; + +function record(value: unknown): Record | null { + return value && typeof value === "object" && !Array.isArray(value) ? value as Record : null; +} + +function nonNegativeInt(value: unknown): number | null { + return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.min(Math.floor(value), 2 ** 31 - 1) : null; +} + +/** + * Read a task from a `CreateTaskResult` (`resultType: "task"`) or a + * `tasks/get` result. Returns null for anything that is not a well-formed task. + */ +export function parseMcpTask(value: unknown): McpTaskState | null { + const task = record(value); + if (!task) return null; + const taskId = task.taskId; + if (typeof taskId !== "string" || !taskId || taskId.length > MAX_TASK_ID_LENGTH || /[\u0000-\u001f\u007f]/.test(taskId)) return null; + const status = task.status; + if (typeof status !== "string" || !(MCP_TASK_STATUSES as readonly string[]).includes(status)) return null; + const created = typeof task.createdAt === "string" ? new Date(task.createdAt) : null; + const state: McpTaskState = { + taskId, + status: status as McpTaskStatus, + ttlMs: nonNegativeInt(task.ttlMs), + pollIntervalMs: nonNegativeInt(task.pollIntervalMs), + createdAt: created && Number.isFinite(created.getTime()) ? created : null, + }; + if (state.status === "completed") { + const result = record(task.result); + if (!result) return null; + state.result = result; + } + if (state.status === "failed") { + const error = record(task.error); + state.error = { + code: typeof error?.code === "number" ? error.code : null, + message: typeof error?.message === "string" ? error.message : "", + }; + } + if (state.status === "input_required") { + const inputRequests: Record = {}; + for (const [key, entry] of Object.entries(record(task.inputRequests) ?? {}).slice(0, 32)) { + const request = record(entry); + if (key.length <= 256 && typeof request?.method === "string") inputRequests[key] = { method: request.method, params: record(request.params) ?? {} }; + } + state.inputRequests = inputRequests; + } + return state; +} + +/** The task a `tools/call` returned in place of its result, if it did. */ +export function mcpCreatedTask(result: unknown): McpTaskState | null { + return record(result)?.resultType === "task" ? parseMcpTask(result) : null; +} + +export function isMcpTaskTerminal(status: McpTaskRecordStatus): boolean { + return status !== "working" && status !== "input_required"; +} + +/** How long a live call waits before its next `tasks/get`. */ +export function inlinePollDelayMs(pollIntervalMs: number | null): number { + return Math.min(INLINE_POLL_MAX_MS, Math.max(INLINE_POLL_MIN_MS, pollIntervalMs ?? 1_000)); +} + +/** + * How long background polling waits. The server's hint is honored within + * bounds, failures back off, and a task waiting for a person is checked slowly. + */ +export function backgroundPollDelayMs(input: { pollIntervalMs: number | null; status: McpTaskRecordStatus; failures?: number }): number { + const base = Math.min(BACKGROUND_POLL_MAX_MS, Math.max(BACKGROUND_POLL_MIN_MS, input.pollIntervalMs ?? BACKGROUND_POLL_MIN_MS)); + const waiting = input.status === "input_required" ? Math.max(base, BACKGROUND_INPUT_POLL_MS) : base; + const failures = Math.min(input.failures ?? 0, 6); + return Math.min(BACKGROUND_POLL_MAX_MS, waiting * 2 ** failures); +} + +/** When Paperclip gives up on a task: the provider's TTL from creation, capped. */ +export function mcpTaskExpiresAt(task: Pick, now = Date.now(), trackedSince?: Date): Date { + const created = task.createdAt && task.createdAt.getTime() <= now ? task.createdAt.getTime() : now; + // The cap counts from when Paperclip first saw the task, so a provider that + // keeps extending its TTL cannot keep it tracked forever. + const limit = (trackedSince?.getTime() ?? now) + MCP_TASK_MAX_LIFETIME_MS; + return new Date(task.ttlMs === null ? limit : Math.min(limit, created + task.ttlMs)); +} + +/** + * The identity of a call: a repeated call attaches only when all of it + * matches. `argumentsIdentity` is the gateway's keyed request identity, so a + * stored hash cannot be used to guess secret arguments. + */ +export function mcpTaskRequestHash(input: { connectionId: string; endpoint: string; toolName: string; argumentsIdentity: string; routingIdentity?: string }): string { + return createHash("sha256").update(JSON.stringify(["paperclip:mcp-task-request:v1", input.connectionId, input.endpoint, input.toolName, input.argumentsIdentity, input.routingIdentity ?? ""])).digest("hex"); +} + +export function mcpTaskEndpointHash(endpoint: string): string { + return createHash("sha256").update(endpoint).digest("hex"); +} + +/* + * A task ID may work as a bearer token for the provider's stored state (spec: + * Security Considerations), so it is sealed at rest and indexed by a keyed hash. + */ +const TASK_ID_CONTEXT = "paperclip:mcp-task-id:v1"; + +function taskIdKey(secret: string, purpose: "seal" | "index") { + return Buffer.from(hkdfSync("sha256", secret, Buffer.alloc(0), `${TASK_ID_CONTEXT}:${purpose}`, 32)); +} + +function taskIdAad(scope: { companyId: string; connectionId: string }) { + return Buffer.from(JSON.stringify([TASK_ID_CONTEXT, scope.companyId, scope.connectionId])); +} + +export function mcpTaskIdIndex(secret: string, scope: { companyId: string; connectionId: string }, taskId: string): string { + return createHmac("sha256", taskIdKey(secret, "index")).update(taskIdAad(scope)).update("\0").update(taskId).digest("hex"); +} + +export function sealMcpTaskId(secret: string, scope: { companyId: string; connectionId: string }, taskId: string): string { + const iv = randomBytes(12); + const cipher = createCipheriv("aes-256-gcm", taskIdKey(secret, "seal"), iv); + cipher.setAAD(taskIdAad(scope)); + const ciphertext = Buffer.concat([cipher.update(taskId, "utf8"), cipher.final()]); + return `v1.${iv.toString("base64url")}.${ciphertext.toString("base64url")}.${cipher.getAuthTag().toString("base64url")}`; +} + +/** The task ID, or null when the sealed value is not one this instance wrote for this scope. */ +export function openMcpTaskId(secret: string, scope: { companyId: string; connectionId: string }, sealed: string): string | null { + const [version, iv, ciphertext, tag] = sealed.split("."); + if (version !== "v1" || !iv || !ciphertext || !tag) return null; + try { + const decipher = createDecipheriv("aes-256-gcm", taskIdKey(secret, "seal"), Buffer.from(iv, "base64url")); + decipher.setAAD(taskIdAad(scope)); + decipher.setAuthTag(Buffer.from(tag, "base64url")); + return Buffer.concat([decipher.update(Buffer.from(ciphertext, "base64url")), decipher.final()]).toString("utf8"); + } catch { + return null; + } +} + +/** JSON-RPC `-32602` from `tasks/*`: the task is unknown, expired, or purged. */ +export const MCP_TASK_NOT_FOUND_CODE = -32602; + +export class McpTaskRequestError extends Error { + constructor( + readonly kind: "http" | "rpc" | "malformed", + message: string, + readonly httpStatus: number | null = null, + readonly rpcCode: number | null = null, + ) { + super(message); + this.name = "McpTaskRequestError"; + } + get taskNotFound() { return this.kind === "rpc" && this.rpcCode === MCP_TASK_NOT_FOUND_CODE; } +} + +export type McpTaskTransport = { + /** Headers with credentials and the stateless protocol version. */ + headers: () => Promise>; + /** Fresh credentials after a 401; tasks/* never change provider state twice. */ + refreshHeaders?: () => Promise>; + send: (init: RequestInit) => Promise; + maxBytes: number; +}; + +/** + * Send one `tasks/*` request. `Mcp-Name` carries the task ID so intermediaries + * route it to the instance that holds the task (spec: Streamable HTTP). + */ +export async function sendMcpTaskRequest( + transport: McpTaskTransport, + method: "tasks/get" | "tasks/update" | "tasks/cancel", + params: { taskId: string } & Record, + signal?: AbortSignal, +): Promise> { + const id = `paperclip-task-${randomUUID()}`; + const attempt = (headers: Record) => transport.send({ + ...mcpHttpRequestInit(headers, { id, method, params }, { declareTasks: true }), + redirect: "manual", + signal, + }); + let response = await attempt(await transport.headers()); + if (response.status === 401 && transport.refreshHeaders) { + await response.body?.cancel().catch(() => undefined); + response = await attempt(await transport.refreshHeaders()); + } + if (!response.ok) { + // A modern server answers an unknown task with a JSON-RPC error, which + // can arrive with an HTTP error status. + // Read at most 64 KiB of a provider-controlled error body, then stop. + const text = await readBoundedText(response, 64 * 1024).catch(() => ""); + let payload: Record | null = null; + try { payload = record(JSON.parse(text)); } catch { /* Not JSON, or cut short. */ } + const error = record(payload?.error); + if (error && typeof error.code === "number") throw new McpTaskRequestError("rpc", "The app rejected the task request.", response.status, error.code); + throw new McpTaskRequestError("http", "The app returned an HTTP error for the task request.", response.status); + } + const payload = record(await readMcpHttpResponse(response, id, { maxBytes: transport.maxBytes })); + if (!payload) throw new McpTaskRequestError("malformed", "The app returned a malformed task response."); + const error = record(payload.error); + if (error) throw new McpTaskRequestError("rpc", "The app rejected the task request.", response.status, typeof error.code === "number" ? error.code : null); + const result = record(payload.result); + if (!result) throw new McpTaskRequestError("malformed", "The app returned a malformed task response."); + return result; +} + +async function readBoundedText(response: Response, maxBytes: number): Promise { + const reader = response.body?.getReader(); + if (!reader) return ""; + const decoder = new TextDecoder(); + let text = ""; + let bytes = 0; + try { + while (bytes < maxBytes) { + const { value, done } = await reader.read(); + if (done) break; + const chunk = value.byteLength + bytes > maxBytes ? value.subarray(0, maxBytes - bytes) : value; + bytes += chunk.byteLength; + text += decoder.decode(chunk, { stream: true }); + } + } finally { + void reader.cancel().catch(() => undefined); + reader.releaseLock(); + } + return text; +} + +export async function getMcpTask(transport: McpTaskTransport, taskId: string, signal?: AbortSignal): Promise { + const task = parseMcpTask(await sendMcpTaskRequest(transport, "tasks/get", { taskId }, signal)); + if (!task || task.taskId !== taskId) throw new McpTaskRequestError("malformed", "The app returned a malformed task response."); + return task; +} + +/** Best effort: cancellation is cooperative and its failure changes nothing here. */ +export async function cancelMcpTask(transport: McpTaskTransport, taskId: string, timeoutMs = 5_000): Promise { + try { + await sendMcpTaskRequest(transport, "tasks/cancel", { taskId }, AbortSignal.timeout(timeoutMs)); + return true; + } catch { + return false; + } +} + +/** Sleep until `ms` passes or `signal` aborts; resolves false when aborted. */ +export function waitForPoll(ms: number, signal: AbortSignal): Promise { + if (signal.aborted) return Promise.resolve(false); + return new Promise((resolve) => { + const timer = setTimeout(() => { signal.removeEventListener("abort", onAbort); resolve(true); }, ms); + const onAbort = () => { clearTimeout(timer); resolve(false); }; + signal.addEventListener("abort", onAbort, { once: true }); + }); +} diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index d575c35eff5..e43ab1da975 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -52,6 +52,26 @@ import { captureRunIdentity } from "./run-identity.js"; import { emitConnectionInvoked } from "./connector-telemetry.js"; import { resolveManagedGitHubIdentitySelection } from "./git-credentials.js"; import { extractRemoteMcpPending } from "./remote-mcp-pending.js"; +import { + backgroundPollDelayMs, + cancelMcpTask, + getMcpTask, + inlinePollDelayMs, + isMcpTaskTerminal, + mcpCreatedTask, + mcpTaskEndpointHash, + mcpTaskExpiresAt, + mcpTaskIdIndex, + mcpTaskRequestHash, + McpTaskRequestError, + openMcpTaskId, + sealMcpTaskId, + sendMcpTaskRequest, + waitForPoll, + type McpTaskRecordStatus, + type McpTaskState, + type McpTaskTransport, +} from "./mcp-tasks.js"; import { logger } from "../middleware/logger.js"; import { getAppDefinitionForApplicationKey, isConnectorFeatureEnabled } from "@paperclipai/shared"; import { instanceSettingsService } from "./instance-settings.js"; @@ -75,6 +95,7 @@ import { import type { Db } from "@paperclipai/db"; import { agents, + agentWakeupRequests, approvals, companies, companyMemberships, @@ -103,6 +124,7 @@ import { toolMcpGateways, toolMcpGatewayTokens, toolMcpSkills, + toolMcpTasks, toolPolicies, toolProfileBindings, toolProfileEntries, @@ -232,6 +254,7 @@ import { import { canonicalToolArguments, readSignedToolArgumentsPayload, + resolveToolActionSigningSecret, signToolArguments, summarizeToolValue, toolRequestIdentityHash, @@ -542,6 +565,8 @@ type RemoteHttpExecutionAudit = { error?: RemoteHttpErrorEvidence; deadline?: { timeoutMs: number; aborted: boolean }; stream?: McpHttpResponseProgress; + /** The provider answered with a task (MCP Tasks); no provider task ID is kept here. */ + task?: { recordId: string; attached: boolean; polls: number; status: string }; }; type RemoteHttpErrorEvidence = { @@ -561,6 +586,10 @@ const REMOTE_TOOL_CALL_WORKFLOW_REASON_CODES = new Set([ "provider_retry_requested", "oauth_insufficient_scope", "oauth_refreshed_retry_required", + "provider_task_pending", + "provider_task_cancelled", + "provider_task_expired", + "provider_task_failed", ]); const REMOTE_TOOL_CALL_PROTOCOL_REASON_CODES = new Set([ @@ -6570,11 +6599,42 @@ export function createToolGatewayService( ]; } + /** The question card a provider's input request becomes; answering it wakes the assignee. */ + function createElicitationCard(input: { + companyId: string; issueId: string; agentId: string | null; toolName: string; + request: McpElicitationRequest; idempotencyKey: string; + }) { + return interactions.create( + { id: input.issueId, companyId: input.companyId }, + { + kind: "ask_user_questions", + idempotencyKey: input.idempotencyKey, + title: "Tool needs input", + summary: `${input.toolName} asked for more information before it can continue.`, + continuationPolicy: "wake_assignee", + payload: { + version: 1, + title: input.request.message.slice(0, 240), + submitLabel: "Send response", + questions: elicitationQuestions(input.request), + }, + }, + { agentId: input.agentId }, + // Each provider question is independent: a new one must never expire + // another that is still waiting, which would read as a decline. + { supersedePendingSiblingInteractions: false }, + ); + } + async function requestElicitationForRecordedToolCall(input: { session: ToolGatewaySession; tool: ToolGatewayDescriptor; invocationId: string; request: McpElicitationRequest; + /** One card per provider input request; defaults to one per call. */ + idempotencyKey?: string; + /** The name the card shows; a task's cards use one name on every path. */ + cardToolName?: string; }): Promise { if (!input.session.issueId) { throw new ToolGatewayHttpError( @@ -6584,23 +6644,11 @@ export function createToolGatewayService( { invocationId: input.invocationId, tool: input.tool.name }, ); } - const interaction = await interactions.create( - { id: input.session.issueId, companyId: input.session.companyId }, - { - kind: "ask_user_questions", - idempotencyKey: `mcp-elicitation:${input.invocationId}`, - title: "Tool needs input", - summary: `${input.tool.name} asked for more information before it can continue.`, - continuationPolicy: "wake_assignee", - payload: { - version: 1, - title: input.request.message.slice(0, 240), - submitLabel: "Send response", - questions: elicitationQuestions(input.request), - }, - }, - { agentId: input.session.agentId }, - ); + const interaction = await createElicitationCard({ + companyId: input.session.companyId, issueId: input.session.issueId, agentId: input.session.agentId, + toolName: input.cardToolName ?? input.tool.name, request: input.request, + idempotencyKey: input.idempotencyKey ?? `mcp-elicitation:${input.invocationId}`, + }); const now = new Date(); await db .update(toolInvocations) @@ -6728,6 +6776,715 @@ export function createToolGatewayService( return failureInstructions ? `${message}\n\n${failureInstructions}` : message; } + // ── MCP Tasks (io.modelcontextprotocol/tasks) ───────────────────────────── + // A provider may answer tools/call with a durable task. The live call waits + // on it up to the normal tool timeout; past that the row keeps it, background + // work keeps polling, and the same call (same request, grant, and agent) + // attaches to it instead of starting the work again. One owner at a time + // holds a task (a lease): a live call or the background worker. + type McpTaskRow = typeof toolMcpTasks.$inferSelect; + type McpTaskWake = (task: { + companyId: string; agentId: string; issueId: string; taskRecordId: string; toolName: string; status: string; + /** Distinct per reason, so one wake is requested per settlement or new question. */ + wakeKey: string; + }) => Promise; + /** A call that ended with one of these may attach to its task on a retry with the same key. */ + const MCP_TASK_RETRY_CODES = new Set(["provider_task_pending", "provider_interaction_required", "provider_input_required", "elicitation_required"]); + /** How long a settled task waits for the agent's run to end before a wake is reconsidered. */ + const MCP_TASK_WAKE_RECHECK_MS = 2 * 60_000; + /** How long a settled, undelivered task can still be collected by the same call. */ + const MCP_TASK_SETTLED_ATTACH_MS = 60 * 60_000; + /** A completed result is held for the call recording it; if that call dies, the task is collectable again after this. */ + const MCP_TASK_DELIVERY_LEASE_MS = 2 * 60_000; + /** The background worker's hold on a task, and its bound on one provider request. */ + const MCP_TASK_WORKER_LEASE_MS = 60_000; + const MCP_TASK_WORKER_REQUEST_MS = 30_000; + /** At most this many wakes per task for new input requests, this far apart. */ + const MCP_TASK_MAX_INPUT_WAKES = 3; + const MCP_TASK_INPUT_WAKE_SPACING_MS = 30 * 60_000; + /** At most this many question cards per task, whatever keys the provider sends. */ + const MCP_TASK_MAX_CARDS = 10; + /** Provider-chosen keys kept per task; older ones drop off first. */ + const boundedMcpTaskKeys = (keys: Iterable) => [...new Set(keys)].slice(-64); + const mcpTaskSecret = () => options.toolActionSigningSecret?.trim() || resolveToolActionSigningSecret(); + /** The experimental setting (default off). Off: the extension is never declared and nothing about tasks runs. */ + const mcpTasksEnabled = async () => (await instanceSettingsService(db).getExperimental().catch(() => null))?.enableMcpTasks === true; + const mcpTaskScope = (row: Pick) => ({ companyId: row.companyId, connectionId: row.connectionId }); + const mcpTaskInputKey = (row: McpTaskRow, key: string) => + `mcp-task-input:${row.id}:${createHash("sha256").update(key).digest("hex").slice(0, 32)}`; + const mcpTaskArgumentsIdentity = (parameters: unknown) => toolRequestIdentityHash(parameters ?? {}, options.toolActionSigningSecret); + + function mcpTaskPendingError() { + return new ToolGatewayHttpError(504, + "The app is still working on this. Paperclip keeps track of it: call this tool again with the same arguments to get the result. Changing the arguments starts the work over.", + "provider_task_pending"); + } + function mcpTaskExpiredError() { + return new ToolGatewayHttpError(410, + "The app no longer has this action's result: it expired or was removed. Run the action again to start it over.", + "provider_task_expired"); + } + function mcpTaskCancelledError(byRun = false) { + return new ToolGatewayHttpError(409, byRun + ? "The run was stopped, so Paperclip asked the app to cancel this action." + : "This action was cancelled before it finished. Run it again if it is still needed.", + "provider_task_cancelled"); + } + function mcpTaskFailedError(error: McpTaskState["error"]) { + const detail = error?.message ? redactSensitiveText(error.message).replace(/\s+/g, " ").trim().slice(0, 500) : ""; + return new ToolGatewayHttpError(502, detail ? `The app reported that this action failed: ${detail}` : "The app reported that this action failed.", + "provider_task_failed", { code: error?.code ?? null }); + } + function mcpTaskNeedsInputError() { + return new ToolGatewayHttpError(409, + "This app needs information Paperclip can't collect yet. Complete the step in the app, then call this tool again with the same arguments.", + "provider_input_required"); + } + + function mcpTaskTransport(input: { + protocolVersion: string; + headers: (forceRefresh: boolean) => Promise>; + refreshable: boolean; + send: (init: RequestInit) => Promise; + }): McpTaskTransport { + const withVersion = async (forceRefresh: boolean) => ({ ...(await input.headers(forceRefresh)), "MCP-Protocol-Version": input.protocolVersion }); + return { + headers: () => withVersion(false), + ...(input.refreshable ? { refreshHeaders: () => withVersion(true) } : {}), + send: input.send, + maxBytes: MAX_REMOTE_MCP_RESPONSE_BYTES, + }; + } + + /** + * Update a task row. With `owner`, the write applies only while that owner + * still holds the task; the result says whether it did. + */ + async function updateMcpTask(row: McpTaskRow, patch: Partial, opts: { notify?: boolean; owner?: string } = {}) { + const write = async (tx: Db) => { + if (opts.notify) await notifyDeliveryWork(tx, DELIVERY_QUEUES.mcpTasks); + const [updated] = await tx.update(toolMcpTasks).set({ ...patch, updatedAt: new Date() }) + .where(and( + eq(toolMcpTasks.id, row.id), eq(toolMcpTasks.companyId, row.companyId), + ...(opts.owner ? [eq(toolMcpTasks.leaseOwner, opts.owner)] : []), + )).returning(); + if (updated) Object.assign(row, updated); + return Boolean(updated); + }; + return opts.notify ? db.transaction(async (tx) => write(tx as unknown as Db)) : write(db); + } + + /** Take an undelivered task for `owner` unless someone else holds it. */ + async function claimMcpTask(row: McpTaskRow, owner: string, leaseMs: number, patch: Partial = {}) { + const now = new Date(); + const [claimed] = await db.update(toolMcpTasks).set({ ...patch, leaseOwner: owner, leaseExpiresAt: new Date(now.getTime() + leaseMs), updatedAt: now }) + .where(and( + eq(toolMcpTasks.id, row.id), eq(toolMcpTasks.companyId, row.companyId), isNull(toolMcpTasks.deliveredAt), + or(isNull(toolMcpTasks.leaseExpiresAt), lte(toolMcpTasks.leaseExpiresAt, now), eq(toolMcpTasks.leaseOwner, owner)), + )).returning(); + return claimed ?? null; + } + + function mcpTaskStatePatch(row: McpTaskRow, state: McpTaskState): Partial { + return { + status: state.status, + lastPolledAt: new Date(), + pollFailures: 0, + ...(state.pollIntervalMs !== null ? { pollIntervalMs: state.pollIntervalMs } : {}), + // The TTL may change over a task's life; it counts from creation, and + // the seven-day cap counts from when Paperclip first saw the task. + ...(state.ttlMs !== null && state.ttlMs !== row.ttlMs + ? { ttlMs: state.ttlMs, expiresAt: mcpTaskExpiresAt({ createdAt: state.createdAt ?? row.createdAt, ttlMs: state.ttlMs }, Date.now(), row.createdAt) } + : {}), + }; + } + + /** Mark a task finished and release it. `delivered` when this call reported the outcome. */ + function settleMcpTask(row: McpTaskRow, status: McpTaskRecordStatus, input: { errorCode?: string | null; delivered?: boolean; invocationId?: string; owner?: string } = {}) { + return updateMcpTask(row, { + status, nextPollAt: null, leaseExpiresAt: null, leaseOwner: null, errorCode: input.errorCode ?? null, + ...(input.delivered ? { deliveredAt: new Date() } : {}), + ...(input.invocationId ? { lastInvocationId: input.invocationId } : {}), + }, { owner: input.owner }); + } + + /** Hand a task the live call stopped waiting on to background polling. */ + function releaseMcpTask(row: McpTaskRow, owner: string) { + return updateMcpTask(row, { + leaseExpiresAt: null, leaseOwner: null, + nextPollAt: new Date(Date.now() + backgroundPollDelayMs({ pollIntervalMs: row.pollIntervalMs, status: row.status as McpTaskRecordStatus })), + }, { notify: true, owner }); + } + + /** + * Record that the call `invocationId` has recorded a task's result. Until + * then a completed task stays collectable, so a crash between reading the + * result and recording it loses nothing. + */ + async function markMcpTaskDelivered(companyId: string, invocationId: string) { + await db.update(toolMcpTasks).set({ deliveredAt: new Date(), nextPollAt: null, leaseExpiresAt: null, leaseOwner: null, updatedAt: new Date() }) + .where(and(eq(toolMcpTasks.companyId, companyId), eq(toolMcpTasks.lastInvocationId, invocationId), isNull(toolMcpTasks.deliveredAt))); + } + + async function createMcpTaskRecord(input: { + session: ToolGatewaySession; + connection: typeof toolConnections.$inferSelect; + grant: typeof connectionGrants.$inferSelect; + catalogToolName: string; + invocationId: string; + requestHash: string; + argumentsIdentity: string; + endpointHash: string; + callerHeaders: Record; + protocolVersion: string; + state: McpTaskState; + owner: string; + leaseMs: number; + }): Promise { + const secret = mcpTaskSecret(); + const scope = mcpTaskScope({ companyId: input.connection.companyId, connectionId: input.connection.id }); + const providerTaskIdHash = mcpTaskIdIndex(secret, scope, input.state.taskId); + // The person whose grant applied: carried by the session, or by its run. + const [run] = !input.session.responsibleUserId && input.session.runId + ? await db.select({ responsibleUserId: heartbeatRuns.responsibleUserId }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.id, input.session.runId), eq(heartbeatRuns.companyId, input.session.companyId))).limit(1) + : []; + const responsibleUserId = input.session.responsibleUserId ?? run?.responsibleUserId ?? null; + const now = Date.now(); + const inserted = await db.transaction(async (tx) => { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.mcpTasks); + const [row] = await tx.insert(toolMcpTasks).values({ + companyId: input.connection.companyId, + invocationId: input.invocationId, + lastInvocationId: input.invocationId, + connectionId: input.connection.id, + grantId: input.grant.id, + agentId: input.session.agentId, + issueId: input.session.issueId, + runId: input.session.runId, + actorType: input.session.actorType ?? "agent", + actorId: input.session.actorId ?? null, + responsibleUserId, + identityContextId: input.session.identityContextId ?? null, + catalogToolName: input.catalogToolName, + requestHash: input.requestHash, + argumentsIdentity: input.argumentsIdentity, + endpointHash: input.endpointHash, + sealedCallerHeaders: Object.keys(input.callerHeaders).length ? sealMcpTaskId(secret, scope, JSON.stringify(input.callerHeaders)) : null, + protocolVersion: input.protocolVersion, + sealedProviderTaskId: sealMcpTaskId(secret, scope, input.state.taskId), + providerTaskIdHash, + status: input.state.status, + pollIntervalMs: input.state.pollIntervalMs, + ttlMs: input.state.ttlMs, + expiresAt: mcpTaskExpiresAt(input.state, now), + nextPollAt: new Date(now + backgroundPollDelayMs({ pollIntervalMs: input.state.pollIntervalMs, status: input.state.status })), + leaseOwner: input.owner, + leaseExpiresAt: new Date(now + input.leaseMs), + }).onConflictDoNothing().returning(); + return row; + }); + if (inserted) { + await writeAudit({ + session: input.session, companyId: input.session.companyId, agentId: input.session.agentId, + runId: input.session.runId, issueId: input.session.issueId, action: "tool_gateway.task_started", + details: { invocationId: input.invocationId, taskRecordId: inserted.id, connectionId: input.connection.id, tool: input.catalogToolName }, + }); + return inserted; + } + // A server that hands out a task it already gave Paperclip must have given + // it for the same request and credentials; anything else is refused. + const [existing] = await db.select().from(toolMcpTasks).where(and( + eq(toolMcpTasks.companyId, input.connection.companyId), eq(toolMcpTasks.connectionId, input.connection.id), + eq(toolMcpTasks.providerTaskIdHash, providerTaskIdHash))); + if (!existing || existing.grantId !== input.grant.id || existing.requestHash !== input.requestHash) throw malformedRemoteMcpResponse(); + const claimed = await claimMcpTask(existing, input.owner, input.leaseMs, { lastInvocationId: input.invocationId, runId: input.session.runId }); + if (!claimed) throw mcpTaskPendingError(); + return claimed; + } + + /** The forwarded caller headers a connection allows, normalized: they route a call, so they are part of a task's identity. */ + function mcpTaskCallerHeaders(connection: typeof toolConnections.$inferSelect, callerHeaders: ExecuteGatewayToolInput["callerHeaders"]) { + const allowed = new Set(readHeaderPolicy(connection).passthroughAllowlist.map((name) => name.toLowerCase())); + return Object.fromEntries(Object.entries(normalizeCallerHeaders(callerHeaders)) + .filter(([name]) => allowed.has(name.toLowerCase())) + .map(([name, value]) => [name.toLowerCase(), value] as const) + .sort(([a], [b]) => a.localeCompare(b))); + } + + /** Undelivered, and still worth collecting: active, or settled recently. */ + const mcpTaskCollectable = () => and( + isNull(toolMcpTasks.deliveredAt), + // A settled task is collected soon after it settles; an old one is not + // silently handed to what may be a deliberate new run of the same call. + or(inArray(toolMcpTasks.status, ["working", "input_required"]), gt(toolMcpTasks.updatedAt, new Date(Date.now() - MCP_TASK_SETTLED_ATTACH_MS))), + ); + + /** An undelivered task this exact call already started, for this grant, agent, and task. */ + async function findAttachableMcpTask(input: { + session: ToolGatewaySession; connectionId: string; grantId: string; requestHash: string; rowId?: string; + }): Promise { + const [row] = await db.select().from(toolMcpTasks).where(and( + eq(toolMcpTasks.companyId, input.session.companyId), + ...(input.rowId ? [eq(toolMcpTasks.id, input.rowId)] : []), + eq(toolMcpTasks.connectionId, input.connectionId), + eq(toolMcpTasks.requestHash, input.requestHash), + eq(toolMcpTasks.grantId, input.grantId), + input.session.agentId ? eq(toolMcpTasks.agentId, input.session.agentId) : isNull(toolMcpTasks.agentId), + input.session.issueId ? eq(toolMcpTasks.issueId, input.session.issueId) : isNull(toolMcpTasks.issueId), + eq(toolMcpTasks.actorType, input.session.actorType ?? "agent"), + input.session.actorId ? eq(toolMcpTasks.actorId, input.session.actorId) : isNull(toolMcpTasks.actorId), + mcpTaskCollectable(), + )).orderBy(desc(toolMcpTasks.createdAt)).limit(1); + return row ?? null; + } + + /** + * The task a keyed retry should collect, checked before the call changes + * anything. A call interrupted mid-wait (a crash) left its invocation + * executing with no error; that counts too. A different request under the + * same key is a conflict and leaves the original retry intact. + */ + async function mcpTaskForKeyedRetry(companyId: string, invocation: typeof toolInvocations.$inferSelect, current: { + connectionId: string | null; argumentsIdentity: string; callerHeaders: ExecuteGatewayToolInput["callerHeaders"]; + }) { + const interrupted = invocation.status === "executing" && !invocation.errorCode; + if (!interrupted && (!invocation.errorCode || !MCP_TASK_RETRY_CODES.has(invocation.errorCode))) return null; + const [row] = await db.select({ id: toolMcpTasks.id, companyId: toolMcpTasks.companyId, connectionId: toolMcpTasks.connectionId, + argumentsIdentity: toolMcpTasks.argumentsIdentity, sealedCallerHeaders: toolMcpTasks.sealedCallerHeaders }) + .from(toolMcpTasks).where(and( + eq(toolMcpTasks.companyId, companyId), + or(eq(toolMcpTasks.invocationId, invocation.id), eq(toolMcpTasks.lastInvocationId, invocation.id)), + mcpTaskCollectable(), + )).orderBy(desc(toolMcpTasks.createdAt)).limit(1); + if (!row) return null; + // The forwarded routing headers (such as a tenant) must match too, checked + // before anything changes so a mismatch leaves the original retry intact. + const [connection] = await db.select().from(toolConnections) + .where(and(eq(toolConnections.id, row.connectionId), eq(toolConnections.companyId, companyId))).limit(1); + const stored = row.sealedCallerHeaders ? openMcpTaskId(mcpTaskSecret(), mcpTaskScope(row), row.sealedCallerHeaders) : "{}"; + const sameRouting = Boolean(connection) && stored !== null + && JSON.stringify(mcpTaskCallerHeaders(connection!, current.callerHeaders)) === JSON.stringify(JSON.parse(stored)); + if (row.connectionId !== current.connectionId || row.argumentsIdentity !== current.argumentsIdentity || !sameRouting) { + throw new ToolGatewayHttpError(409, "This idempotency key belongs to an earlier call with different arguments. Use a new key to start new work.", "idempotency_key_conflict"); + } + return row.id; + } + + /** Map a person's question-card answers back onto the provider's form schema. */ + function elicitationContent(request: McpElicitationRequest, result: unknown): Record { + const answers = (Array.isArray(asRecord(result)?.answers) ? asRecord(result)!.answers as unknown[] : []) + .map((answer) => asRecord(answer)).filter((answer): answer is Record => Boolean(answer)); + const textOf = (answer: Record | undefined) => typeof answer?.otherText === "string" ? answer.otherText.trim() : ""; + const properties = asRecord(request.requestedSchema?.properties); + if (!properties || Object.keys(properties).length === 0) { + const text = textOf(answers.find((answer) => answer.questionId === "response")); + return text ? { response: text } : {}; + } + const content: Record = {}; + for (const [key, raw] of Object.entries(properties).slice(0, 10)) { + const property = asRecord(raw) ?? {}; + const answer = answers.find((candidate) => candidate.questionId === key.slice(0, 120)); + if (!answer) continue; + const enumValues = Array.isArray(property.enum) ? property.enum : []; + const optionIds = Array.isArray(answer.optionIds) ? answer.optionIds : []; + const index = enumOptions(enumValues).findIndex((option) => optionIds.includes(option.id)); + if (index >= 0) { content[key] = enumValues[index]; continue; } + const text = textOf(answer); + if (!text) continue; + if (property.type === "number" || property.type === "integer") { + const value = Number(text); + if (Number.isFinite(value) && (property.type === "number" || Number.isInteger(value))) content[key] = value; + } else if (property.type === "boolean") { + if (/^(true|yes|y|1)$/i.test(text)) content[key] = true; + else if (/^(false|no|n|0)$/i.test(text)) content[key] = false; + } else { + content[key] = text; + } + } + return content; + } + + type McpTaskInputPlan = { + /** Responses ready to send with tasks/update. */ + responses: Record; + links: ToolUpstreamPending["links"]; + linkKeys: string[]; + linkMessage?: string; + /** The first form still waiting for a person. */ + waitingForm?: { key: string; request: McpElicitationRequest; hasCard: boolean }; + unsupported: boolean; + }; + + /** + * Decide what Paperclip can do with a task's input requests. URL requests + * become the provider link a person opens; Paperclip never answers them, as + * for a direct request. Form requests become a question card, and only a + * person's answer on that card is sent back. Anything else needs the app. + */ + async function planMcpTaskInput(row: McpTaskRow, state: McpTaskState, answered: ReadonlySet): Promise { + const plan: McpTaskInputPlan = { responses: {}, links: [], linkKeys: [], unsupported: false }; + for (const [key, request] of Object.entries(state.inputRequests ?? {})) { + if (answered.has(key)) continue; + const mode = request.params.mode; + if (request.method === "elicitation/create" && mode === "url") { + const checked = checkOAuthEndpointUrl(request.params.url); + if (!checked.ok) return { ...plan, unsupported: true }; + if (!plan.links.some((link) => link.url === checked.url)) plan.links.push({ url: checked.url, host: checked.host }); + plan.linkKeys.push(key); + if (!plan.linkMessage && typeof request.params.message === "string") plan.linkMessage = redactSensitiveText(request.params.message).slice(0, 4000); + continue; + } + if (request.method !== "elicitation/create" || (mode !== undefined && mode !== "form") || !row.issueId) return { ...plan, unsupported: true }; + const form = { + key, + request: { + message: stringValue(request.params.message) ?? "The app needs more information before it can continue.", + requestedSchema: asRecord(request.params.requestedSchema), + raw: request.params, + }, + }; + const [card] = await db.select({ status: issueThreadInteractions.status, result: issueThreadInteractions.result }) + .from(issueThreadInteractions).where(and( + eq(issueThreadInteractions.companyId, row.companyId), + eq(issueThreadInteractions.issueId, row.issueId), + eq(issueThreadInteractions.idempotencyKey, mcpTaskInputKey(row, key)), + )).limit(1); + if (!card || card.status === "pending") { plan.waitingForm ??= { ...form, hasCard: Boolean(card) }; continue; } + const outcome = asRecord(card.result)?.outcome; + plan.responses[key] = card.status === "answered" && outcome === undefined + ? { action: "accept", content: elicitationContent(form.request, card.result) } + : { action: "decline" }; + } + if (plan.links.length > MCP_MAX_INPUT_LINKS) plan.unsupported = true; + return plan; + } + + async function sendMcpTaskResponses(row: McpTaskRow, owner: string, session: ToolGatewaySession, transport: McpTaskTransport, taskId: string, plan: McpTaskInputPlan, answered: Set, signal?: AbortSignal) { + const keys = Object.keys(plan.responses); + if (!keys.length) return; + await sendMcpTaskRequest(transport, "tasks/update", { taskId, inputResponses: plan.responses }, signal); + for (const key of keys) answered.add(key); + await updateMcpTask(row, { answeredInputKeys: boundedMcpTaskKeys(answered) }, { owner }); + await writeAudit({ + session, companyId: row.companyId, agentId: row.agentId, runId: row.runId, issueId: row.issueId, + action: "tool_gateway.task_input_sent", + details: { + invocationId: row.invocationId, taskRecordId: row.id, connectionId: row.connectionId, tool: row.catalogToolName, + // Which kind of answer went back, never what the person wrote. + responses: keys.map((key) => asRecord(plan.responses[key])?.action ?? null), + }, + }); + } + + async function cancelMcpTaskRecord(row: McpTaskRow, owner: string, transport: McpTaskTransport | null, taskId: string | null, reason: "run_cancelled" | "issue_closed", session: ToolGatewaySession, delivered: boolean) { + const acknowledged = transport && taskId ? await cancelMcpTask(transport, taskId) : false; + await settleMcpTask(row, "cancelled", { errorCode: reason, delivered, owner }); + await writeAudit({ + session, companyId: row.companyId, agentId: row.agentId, runId: row.runId, issueId: row.issueId, + action: "tool_gateway.task_cancelled", + details: { invocationId: row.invocationId, taskRecordId: row.id, connectionId: row.connectionId, tool: row.catalogToolName, reason, acknowledged }, + }); + } + + /** + * Wait on a task inside a live call that holds it (`owner`). Returns the + * provider's final tool result, exactly what a synchronous call would have + * returned, or throws the error the caller should see. The task stays + * durable when the wait ends; a completed one stays collectable until the + * caller records its result (markMcpTaskDelivered). + */ + async function waitForMcpTask(wait: { + row: McpTaskRow; + owner: string; + taskId: string; + initial?: McpTaskState; + session: ToolGatewaySession; + tool: ToolGatewayDescriptor; + invocationId: string; + transport: McpTaskTransport; + deadline: AbortSignal; + runSignal?: AbortSignal; + callerSignal?: AbortSignal; + execution: RemoteHttpExecutionAudit; + }): Promise> { + const { row, owner } = wait; + const stop = AbortSignal.any([wait.deadline, ...(wait.callerSignal ? [wait.callerSignal] : []), ...(wait.runSignal ? [wait.runSignal] : [])]); + const answered = new Set(row.answeredInputKeys ?? []); + const audit = { recordId: row.id, attached: !wait.initial, polls: 0, status: row.status }; + wait.execution.task = audit; + const own = (patch: Partial) => updateMcpTask(row, patch, { owner }); + const settle = (status: McpTaskRecordStatus, errorCode?: string | null) => + settleMcpTask(row, status, { errorCode, delivered: true, invocationId: wait.invocationId, owner }); + const cancelForRun = async (): Promise => { + await cancelMcpTaskRecord(row, owner, wait.transport, wait.taskId, "run_cancelled", wait.session, true); + throw mcpTaskCancelledError(true); + }; + try { + // Paperclip's own outcomes are reported as they are: an expired task is + // gone, and a task Paperclip cancelled is never revived by a later poll. + if (row.status === "expired") { await settle("expired", row.errorCode ?? "ttl_expired"); throw mcpTaskExpiredError(); } + if (row.status === "cancelled") { await settle("cancelled", row.errorCode); throw mcpTaskCancelledError(row.errorCode === "run_cancelled"); } + let delay = wait.initial?.status === "working" ? inlinePollDelayMs(row.pollIntervalMs) : 0; + let failures = 0; + for (;;) { + if (delay > 0 && !(await waitForPoll(delay, stop))) { + if (wait.runSignal?.aborted) return await cancelForRun(); + throw mcpTaskPendingError(); + } + if (wait.runSignal?.aborted) return await cancelForRun(); + if (row.expiresAt.getTime() <= Date.now()) { await settle("expired", "ttl_expired"); throw mcpTaskExpiredError(); } + let state: McpTaskState; + try { + state = await getMcpTask(wait.transport, wait.taskId, stop); + audit.polls += 1; + failures = 0; + } catch (error) { + if (wait.runSignal?.aborted) return await cancelForRun(); + if (stop.aborted) throw mcpTaskPendingError(); + if (error instanceof McpTaskRequestError && error.taskNotFound) { await settle("expired", "provider_task_unknown"); throw mcpTaskExpiredError(); } + if (error instanceof ToolGatewayHttpError) throw error; + // A transient failure: the task is still durable, so back off and + // leave it to background polling if the app stays unreachable. + failures += 1; + await own({ pollFailures: row.pollFailures + 1 }); + if (failures >= 3) throw mcpTaskPendingError(); + delay = inlinePollDelayMs(row.pollIntervalMs) * 2 ** failures; + continue; + } + // Losing the task to another owner (a long stall past the lease) ends this wait. + if (!(await own(mcpTaskStatePatch(row, state)))) throw mcpTaskPendingError(); + audit.status = state.status; + if (state.status === "completed") { + // Held for this call until its result is recorded; not yet delivered. + // If this process dies first, background work finds it when the hold + // ends and wakes the agent to collect it. + const holdUntil = new Date(Date.now() + MCP_TASK_DELIVERY_LEASE_MS); + await own({ nextPollAt: holdUntil, errorCode: null, lastInvocationId: wait.invocationId, leaseExpiresAt: holdUntil }); + return state.result!; + } + if (state.status === "failed") { await settle("failed"); throw mcpTaskFailedError(state.error); } + if (state.status === "cancelled") { await settle("cancelled"); throw mcpTaskCancelledError(); } + if (state.status === "input_required") { + const plan = await planMcpTaskInput(row, state, answered); + if (plan.unsupported) throw mcpTaskNeedsInputError(); + try { + await sendMcpTaskResponses(row, owner, wait.session, wait.transport, wait.taskId, plan, answered, stop); + } catch (error) { + if (error instanceof McpTaskRequestError && error.taskNotFound) { await settle("expired", "provider_task_unknown"); throw mcpTaskExpiredError(); } + // Unsent answers stay unanswered and are sent on the next poll. + if (stop.aborted) throw mcpTaskPendingError(); + } + // A form counts as shown only once its card exists. + if (plan.waitingForm && !plan.waitingForm.hasCard && row.issueId) { + await createElicitationCard({ + companyId: row.companyId, issueId: row.issueId, agentId: row.agentId, toolName: row.catalogToolName, + request: plan.waitingForm.request, idempotencyKey: mcpTaskInputKey(row, plan.waitingForm.key), + }); + } + const shown = [...plan.linkKeys, ...(plan.waitingForm ? [plan.waitingForm.key] : [])]; + if (shown.length) await own({ surfacedInputKeys: boundedMcpTaskKeys([...(row.surfacedInputKeys ?? []), ...shown]) }); + if (plan.links.length) { + const pending: ToolUpstreamPending = { kind: "authorization", links: plan.links, ...(plan.linkMessage ? { message: plan.linkMessage } : {}) }; + await retainUpstreamHandoff(wait.invocationId, pending); + throw new ToolGatewayHttpError(409, + "Complete the provider's authorization or approval, then call this tool again with the same arguments to continue.", + "provider_interaction_required", { upstreamPending: pending, invocationId: wait.invocationId }); + } + if (plan.waitingForm) { + await requestElicitationForRecordedToolCall({ + session: wait.session, tool: wait.tool, invocationId: wait.invocationId, + request: plan.waitingForm.request, idempotencyKey: mcpTaskInputKey(row, plan.waitingForm.key), + cardToolName: row.catalogToolName, + }); + } + } + delay = inlinePollDelayMs(row.pollIntervalMs); + } + } finally { + if (!isMcpTaskTerminal(row.status as McpTaskRecordStatus)) await releaseMcpTask(row, owner); + } + } + + /** The credentials, endpoint, and identity a stored task was created with, if they all still hold. */ + async function storedMcpTaskContext(row: McpTaskRow): Promise< + { session: ToolGatewaySession; transport: McpTaskTransport; taskId: string } | { closed: string } + > { + const taskId = openMcpTaskId(mcpTaskSecret(), mcpTaskScope(row), row.sealedProviderTaskId); + if (!taskId) return { closed: "task_unreadable" }; + const [connection] = await db.select().from(toolConnections) + .where(and(eq(toolConnections.id, row.connectionId), eq(toolConnections.companyId, row.companyId))).limit(1); + if (!connection || !connection.enabled || connection.status !== "active" || connection.transport !== "mcp_remote") return { closed: "connection_unavailable" }; + const session: ToolGatewaySession = { + id: `mcp-task:${row.id}`, token: "", companyId: row.companyId, agentId: row.agentId, runId: row.runId, + issueId: row.issueId, projectId: null, actorType: row.actorType as ToolGatewaySession["actorType"], actorId: row.actorId, + responsibleUserId: row.responsibleUserId, identityContextId: row.identityContextId, + createdAt: new Date(), expiresAt: new Date(Date.now() + 5 * 60_000), + }; + // The same access check a live call makes, as the same caller: audience, + // delegation, and the grant itself. Removing any of them stops the work; + // any other failure (a database blip) is retried with backoff. + let grant: typeof connectionGrants.$inferSelect; + try { + grant = await resolveConnectionGrant(session, connection, false); + } catch (error) { + if (error instanceof ToolGatewayHttpError) return { closed: "access_removed" }; + throw error; + } + if (grant.id !== row.grantId || grant.status !== "active") return { closed: "access_removed" }; + const workspaceTarget = connection.config.sourceTemplateKey === "google-workspace" ? googleWorkspaceToolTarget(row.catalogToolName) : null; + const endpoint = workspaceTarget?.serverUrl ?? await resolvedRemoteEndpoint(session, connection, grant); + if (mcpTaskEndpointHash(String(endpoint)) !== row.endpointHash) return { closed: "endpoint_changed" }; + // The allowed forwarded headers the call was made with, so background polls route the same way. + const openedCallerHeaders = row.sealedCallerHeaders ? openMcpTaskId(mcpTaskSecret(), mcpTaskScope(row), row.sealedCallerHeaders) : null; + if (row.sealedCallerHeaders && !openedCallerHeaders) return { closed: "task_unreadable" }; + const callerHeaders = openedCallerHeaders ? JSON.parse(openedCallerHeaders) as Record : undefined; + const transport = mcpTaskTransport({ + protocolVersion: row.protocolVersion, + refreshable: connection.authKind === "oauth", + headers: async (forceRefresh) => buildRemoteHeaders({ + session, connection, callerHeaders, + credentialHeaders: { ...projectedConnectionHeaders(connection), ...(await resolveCredentialHeaders(session, connection, grant, { forceRefresh })) }, + }).headers, + send: (init) => options.remoteHttpRequest + ? options.remoteHttpRequest(String(endpoint), init) + : guardedRemoteHttpFetch(String(endpoint), init, remoteHttpFetchOptions()), + }); + return { session, transport, taskId }; + } + + /** Why a task nobody waits on should be cancelled: its task closed or its run was stopped. */ + async function mcpTaskStopReason(row: McpTaskRow): Promise<"issue_closed" | "run_cancelled" | null> { + if (row.issueId) { + const [issue] = await db.select({ status: issues.status }).from(issues) + .where(and(eq(issues.id, row.issueId), eq(issues.companyId, row.companyId))).limit(1); + if (!issue || issue.status === "done" || issue.status === "cancelled") return "issue_closed"; + } + if (row.runId) { + const [run] = await db.select({ status: heartbeatRuns.status }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.id, row.runId), eq(heartbeatRuns.companyId, row.companyId))).limit(1); + if (run?.status === "cancelled") return "run_cancelled"; + } + return null; + } + + /** + * Wake the task's agent once its run has ended, so the agent's repeated call + * collects the outcome or shows a new question. "deferred" while the run is + * still going, "skipped" when nobody should be woken. + */ + async function wakeAgentForMcpTask(row: McpTaskRow, wake: McpTaskWake | undefined, wakeKey: string): Promise<"woken" | "deferred" | "skipped"> { + if (!wake || !row.issueId || !row.agentId || row.expiresAt.getTime() <= Date.now()) return "skipped"; + const [issue] = await db.select({ status: issues.status, assigneeAgentId: issues.assigneeAgentId }).from(issues) + .where(and(eq(issues.id, row.issueId), eq(issues.companyId, row.companyId))).limit(1); + if (!issue || issue.status === "done" || issue.status === "cancelled" || issue.assigneeAgentId !== row.agentId) return "skipped"; + if (row.runId) { + const [run] = await db.select({ status: heartbeatRuns.status }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.id, row.runId), eq(heartbeatRuns.companyId, row.companyId))).limit(1); + if (run && ["queued", "running", "scheduled_retry"].includes(run.status)) return "deferred"; + } + // The wake request row is the durable receipt: a pass that crashed after + // waking (before recording it here) finds it and never wakes twice. + const [receipt] = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, row.companyId), eq(agentWakeupRequests.agentId, row.agentId), + eq(agentWakeupRequests.idempotencyKey, wakeKey))).limit(1); + if (!receipt) await wake({ companyId: row.companyId, agentId: row.agentId, issueId: row.issueId, taskRecordId: row.id, toolName: row.catalogToolName, status: row.status, wakeKey }); + return "woken"; + } + + /** A task settled while nobody was waiting: wake its agent once. */ + async function wakeForSettledMcpTask(row: McpTaskRow, owner: string, wake?: McpTaskWake) { + const done = () => updateMcpTask(row, { nextPollAt: null, leaseExpiresAt: null, leaseOwner: null }, { owner }); + if (row.deliveredAt || row.wakeRequestedAt || row.status === "expired" || row.status === "cancelled" + || row.updatedAt.getTime() < Date.now() - MCP_TASK_SETTLED_ATTACH_MS) return done(); + const outcome = await wakeAgentForMcpTask(row, wake, `mcp-task:${row.id}:settled`); + if (outcome === "deferred") { + return updateMcpTask(row, { leaseExpiresAt: null, leaseOwner: null, nextPollAt: new Date(Date.now() + MCP_TASK_WAKE_RECHECK_MS) }, { owner }); + } + return updateMcpTask(row, { ...(outcome === "woken" ? { wakeRequestedAt: new Date() } : {}), nextPollAt: null, leaseExpiresAt: null, leaseOwner: null }, { owner }); + } + + /** One background step for a task the worker holds (`owner`). */ + async function pollStoredMcpTask(row: McpTaskRow, owner: string, wake: McpTaskWake | undefined, signal?: AbortSignal) { + const settle = (status: McpTaskRecordStatus, errorCode: string) => settleMcpTask(row, status, { errorCode, owner }); + if (row.deliveredAt) return updateMcpTask(row, { nextPollAt: null, leaseExpiresAt: null, leaseOwner: null }, { owner }); + if (isMcpTaskTerminal(row.status as McpTaskRecordStatus)) return wakeForSettledMcpTask(row, owner, wake); + if (row.expiresAt.getTime() <= Date.now()) return settle("expired", "ttl_expired"); + const context = await storedMcpTaskContext(row); + if ("closed" in context) return settle("expired", context.closed); + const stopReason = await mcpTaskStopReason(row); + if (stopReason) return cancelMcpTaskRecord(row, owner, context.transport, context.taskId, stopReason, context.session, false); + // One slow or endless response must not hold the worker past its lease or the task past its TTL. + const bound = Math.max(1_000, Math.min(MCP_TASK_WORKER_REQUEST_MS, row.expiresAt.getTime() - Date.now())); + const requestSignal = AbortSignal.any([AbortSignal.timeout(bound), ...(signal ? [signal] : [])]); + let state: McpTaskState; + try { + state = await getMcpTask(context.transport, context.taskId, requestSignal); + } catch (error) { + if (error instanceof McpTaskRequestError && error.taskNotFound) return settle("expired", "provider_task_unknown"); + return updateMcpTask(row, { + leaseExpiresAt: null, leaseOwner: null, pollFailures: row.pollFailures + 1, + nextPollAt: new Date(Date.now() + backgroundPollDelayMs({ pollIntervalMs: row.pollIntervalMs, status: row.status as McpTaskRecordStatus, failures: row.pollFailures + 1 })), + }, { owner }); + } + if (!(await updateMcpTask(row, { ...mcpTaskStatePatch(row, state), errorCode: null }, { owner }))) return; + // The result stays with the provider; the agent's repeated call reads it. + if (isMcpTaskTerminal(state.status)) return wakeForSettledMcpTask(row, owner, wake); + if (state.status === "input_required") { + const answered = new Set(row.answeredInputKeys ?? []); + const plan = await planMcpTaskInput(row, state, answered); + // A person may have answered the question card since the call ended. + if (!plan.unsupported) { + await sendMcpTaskResponses(row, owner, context.session, context.transport, context.taskId, plan, answered, requestSignal).catch(() => undefined); + } + // A new question or link nobody has seen: wake the agent, whose call + // shows it. Keys come from the provider, so wakes per task are capped + // and spaced; a provider rotating keys cannot keep waking the agent. + const surfaced = new Set(row.surfacedInputKeys ?? []); + // A form question is put on a card right away, so a person sees it even + // when no wake is left for this task; answering the card wakes the agent. + // A missing card is (re)created even if the question was marked shown: a + // crash between marking and creating must not hide it. + const cardCount = plan.waitingForm && row.issueId && !plan.waitingForm.hasCard + ? (await db.select({ count: sql`count(*)::int` }).from(issueThreadInteractions).where(and( + eq(issueThreadInteractions.companyId, row.companyId), eq(issueThreadInteractions.issueId, row.issueId), + sql`${issueThreadInteractions.idempotencyKey} like ${`mcp-task-input:${row.id}:%`}`)))[0]?.count ?? 0 + : Infinity; + if (!plan.unsupported && plan.waitingForm && row.issueId && cardCount < MCP_TASK_MAX_CARDS) { + const card = await createElicitationCard({ + companyId: row.companyId, issueId: row.issueId, agentId: row.agentId, toolName: row.catalogToolName, + request: plan.waitingForm.request, idempotencyKey: mcpTaskInputKey(row, plan.waitingForm.key), + }); + surfaced.add(plan.waitingForm.key); + await updateMcpTask(row, { surfacedInputKeys: boundedMcpTaskKeys(surfaced) }, { owner }); + await writeAudit({ + session: context.session, companyId: row.companyId, agentId: row.agentId, runId: row.runId, issueId: row.issueId, + action: "tool_gateway.elicitation_requested", + details: { invocationId: row.invocationId, taskRecordId: row.id, interactionId: card.id, tool: row.catalogToolName, reasonCode: "elicitation_required" }, + }); + } + const unseen = Object.keys(state.inputRequests ?? {}).filter((key) => !answered.has(key) && !surfaced.has(key)).sort(); + const wakeAllowed = row.inputWakeCount < MCP_TASK_MAX_INPUT_WAKES + && (!row.inputWakeAt || row.inputWakeAt.getTime() <= Date.now() - MCP_TASK_INPUT_WAKE_SPACING_MS); + if (unseen.length && wakeAllowed) { + const outcome = await wakeAgentForMcpTask(row, wake, `mcp-task:${row.id}:input:${row.inputWakeCount + 1}`); + if (outcome === "woken" || outcome === "skipped") { + await updateMcpTask(row, { + surfacedInputKeys: boundedMcpTaskKeys([...surfaced, ...unseen]), + ...(outcome === "woken" ? { inputWakeCount: row.inputWakeCount + 1, inputWakeAt: new Date() } : {}), + }, { owner }); + } + if (outcome === "deferred") { + return updateMcpTask(row, { leaseExpiresAt: null, leaseOwner: null, nextPollAt: new Date(Date.now() + MCP_TASK_WAKE_RECHECK_MS) }, { owner }); + } + } + } + return updateMcpTask(row, { + leaseExpiresAt: null, leaseOwner: null, + nextPollAt: new Date(Date.now() + backgroundPollDelayMs({ pollIntervalMs: row.pollIntervalMs, status: row.status as McpTaskRecordStatus })), + }, { owner }); + } + async function executeRemoteHttpTool( session: ToolGatewaySession, tool: ToolGatewayDescriptor, @@ -6736,6 +7493,8 @@ export function createToolGatewayService( invocationId: string, callerHeaders?: ExecuteGatewayToolInput["callerHeaders"], useDefaultTimeout = false, + /** `run` aborts when the run is stopped (the task is cancelled); `caller` when the caller leaves (it is kept). */ + taskSignals: { run?: AbortSignal; caller?: AbortSignal; attachToTaskRecordId?: string | null } = {}, ): Promise { const { entry, connection, sourceTemplateKey } = await resolveConnectedRemoteTool( session, @@ -6943,13 +7702,74 @@ export function createToolGatewayService( // address it approved, so an operator-supplied hostname cannot be rebound // onto a loopback or metadata address between validation and dispatch // (PAP-17098). + // MCP Tasks are off unless the experimental setting is on; off, the call is exactly as before. + const tasksOn = await mcpTasksEnabled(); const toolCallInit = (): RequestInit => ({ ...mcpHttpRequestInit(requestHeaders, { id: callRequestId, method: "tools/call", params: callParams }, { toolInputSchema: entry.inputSchema ?? undefined, + // Paperclip can wait on a task here, durably (see waitForMcpTask). + declareTasks: tasksOn, }), redirect: "manual", signal: controller.signal, }); + // A stateless server may answer with a task. The same call (request, + // grant, agent, and task) attaches to an undelivered one instead of + // sending tools/call again, so retries and recovered runs never repeat work. + const taskArgumentsIdentity = mcpTaskArgumentsIdentity(parameters); + // Forwarded caller headers the connection allows (such as a tenant) + // route the call too, so they are part of a task's identity. Per-run + // metadata headers and credentials are not: they change on recovery. + const taskCallerHeaders = mcpTaskCallerHeaders(connection, callerHeaders); + const taskRoutingIdentity = mcpTaskArgumentsIdentity(taskCallerHeaders); + // Built from the version a request actually used: a version retry can + // move a saved legacy connection to stateless MCP mid-call. + const taskIdentityFor = (headersUsed: Record) => { + const version = mcpProtocolVersionOf(headersUsed); + return tasksOn && isModernMcpProtocolVersion(version) ? { + protocolVersion: version, + requestHash: mcpTaskRequestHash({ + connectionId: connection.id, endpoint: String(endpoint), toolName: upstreamToolName, + argumentsIdentity: taskArgumentsIdentity, routingIdentity: taskRoutingIdentity, + }), + endpointHash: mcpTaskEndpointHash(String(endpoint)), + } : null; + }; + const taskIdentity = taskIdentityFor(requestHeaders); + // This call's hold on a task it starts or attaches to. + const taskOwner = `call:${invocationId}:${randomUUID()}`; + const taskTransport = (protocolVersion: string) => mcpTaskTransport({ + protocolVersion, + refreshable: connection.authKind === "oauth", + headers: async (forceRefresh) => forceRefresh ? buildRemoteHeaders({ + session, connection, callerHeaders, + credentialHeaders: { ...projectedConnectionHeaders(connection), ...(await resolveCredentialHeaders(session, connection, grant, { forceRefresh: true })) }, + }).headers : headers, + send: (init) => dispatchRemote(endpoint, { ...init, signal: init.signal ?? controller.signal }), + }); + const waitOnTask = (row: typeof toolMcpTasks.$inferSelect, taskId: string, initial?: McpTaskState) => waitForMcpTask({ + row, owner: taskOwner, taskId, initial, session, tool, invocationId, transport: taskTransport(row.protocolVersion), + deadline: controller.signal, runSignal: taskSignals.run, callerSignal: taskSignals.caller, execution, + }); + if (taskIdentity) { + const attachable = await findAttachableMcpTask({ + session, connectionId: connection.id, grantId: grant.id, requestHash: taskIdentity.requestHash, + rowId: taskSignals.attachToTaskRecordId ?? undefined, + }); + const attachedTaskId = attachable ? openMcpTaskId(mcpTaskSecret(), mcpTaskScope(attachable), attachable.sealedProviderTaskId) : null; + if (attachable && attachedTaskId) { + // Only one caller collects a task at a time; another one waiting on + // it means this call is told to try again, never handed a copy. + const claimed = await claimMcpTask(attachable, taskOwner, ms + 15_000, { lastInvocationId: invocationId, runId: session.runId ?? attachable.runId }); + if (!claimed) throw mcpTaskPendingError(); + return await completeRemoteMcpCall(await waitOnTask(claimed, attachedTaskId)); + } + } + if (taskSignals.attachToTaskRecordId) { + // The keyed retry's task is no longer collectable here (its grant or + // endpoint changed): report it rather than start the work again. + throw mcpTaskExpiredError(); + } let response = await dispatchRemote(endpoint, toolCallInit()); // A stateless server rejects a request it cannot accept before running // anything (wrong version, or legacy request shape), so one retry with a @@ -7204,6 +8024,20 @@ export function createToolGatewayService( if (!Object.prototype.hasOwnProperty.call(payloadRecord, "result")) { throw malformedRemoteMcpResponse(); } + if (asRecord(payloadRecord.result)?.resultType === "task") { + // Only a stateless call declared tasks, and the server must send a + // well-formed task; anything else is not a result Paperclip can use. + const created = mcpCreatedTask(payloadRecord.result); + const usedIdentity = taskIdentityFor(requestHeaders); + if (!created || !usedIdentity) throw malformedRemoteMcpResponse(); + const row = await createMcpTaskRecord({ + session, connection, grant, catalogToolName: entry.toolName, invocationId, + requestHash: usedIdentity.requestHash, argumentsIdentity: taskArgumentsIdentity, endpointHash: usedIdentity.endpointHash, + callerHeaders: taskCallerHeaders, + protocolVersion: usedIdentity.protocolVersion, state: created, owner: taskOwner, leaseMs: ms + 15_000, + }); + return await completeRemoteMcpCall(await waitOnTask(row, created.taskId, created)); + } const inputRequired = mcpInputRequired(payloadRecord.result); if (inputRequired) { // Stateless servers ask for input by returning it as a result. The call @@ -7229,31 +8063,33 @@ export function createToolGatewayService( { connectionId: connection.id, catalogEntryId: entry.id, execution }, ); } - const resultElicitation = extractMcpElicitationRequest( - payloadRecord.result, - ); - if (resultElicitation) { - await requestElicitationForRecordedToolCall({ - session, - tool, - invocationId, - request: resultElicitation, - }); + return await completeRemoteMcpCall(payloadRecord.result); + // A provider's final tool result, whether it came back directly or from a task. + async function completeRemoteMcpCall(callResult: unknown): Promise { + const resultElicitation = extractMcpElicitationRequest(callResult); + if (resultElicitation) { + await requestElicitationForRecordedToolCall({ + session, + tool, + invocationId, + request: resultElicitation, + }); + } + const result = normalizeMcpToolResult( + callResult, + "mcp_http", + false, + sourceTemplateKey, + ); + const failureInstructions = result.errorCode === "github_access_denied" + ? githubAccessDeniedInstructions(entry.toolName, connection.config.connectionMethodKey ?? connection.transportConfig.connectionMethodKey) + : undefined; + await markCallHealth( + "ok", + "Remote MCP server responded to tools/call.", + ); + return { result, failureInstructions, headerSummary, execution }; } - const result = normalizeMcpToolResult( - payloadRecord.result, - "mcp_http", - false, - sourceTemplateKey, - ); - const failureInstructions = result.errorCode === "github_access_denied" - ? githubAccessDeniedInstructions(entry.toolName, connection.config.connectionMethodKey ?? connection.transportConfig.connectionMethodKey) - : undefined; - await markCallHealth( - "ok", - "Remote MCP server responded to tools/call.", - ); - return { result, failureInstructions, headerSummary, execution }; } catch (error) { execution.error = remoteHttpErrorEvidence(error); execution.deadline = { timeoutMs: ms, aborted: controller.signal.aborted }; @@ -8491,6 +9327,8 @@ export function createToolGatewayService( await persistToolTestOutcome(db, args.invocationId, { status: "succeeded", result: resultValidation.summary, }, args.approvedClaim); + // A provider task's result is now recorded; only now is it delivered. + await markMcpTaskDelivered(args.session.companyId, args.invocationId); await writeToolCallEvent({ invocationId: args.invocationId, session: args.session, @@ -8748,6 +9586,26 @@ export function createToolGatewayService( }; } + /** Return a claimed approved action whose provider task is still running to approved, under the same claim. */ + async function resumeApprovedActionForPendingTask(input: { actionRequestId: string; invocationId: string; claimUpdatedAt: Date; message: string }) { + const now = new Date(); + return db.transaction(async (tx) => { + const [invocation] = await tx.select({ status: toolInvocations.status }).from(toolInvocations) + .where(eq(toolInvocations.id, input.invocationId)).for("update").limit(1); + if (invocation?.status !== "executing") return false; + const [actionRequest] = await tx.select({ companyId: toolActionRequests.companyId, status: toolActionRequests.status, updatedAt: toolActionRequests.updatedAt }) + .from(toolActionRequests).where(eq(toolActionRequests.id, input.actionRequestId)).for("update").limit(1); + if (actionRequest?.status !== "executing" || actionRequest.updatedAt.getTime() !== input.claimUpdatedAt.getTime()) return false; + await notifyToolReviewChange(tx, actionRequest.companyId); + await tx.update(toolInvocations).set({ + status: "awaiting_approval", startedAt: null, errorCode: "provider_task_pending", errorMessage: input.message, updatedAt: now, + }).where(and(eq(toolInvocations.id, input.invocationId), eq(toolInvocations.status, "executing"))); + await tx.update(toolActionRequests).set({ status: "approved", updatedAt: now }) + .where(and(eq(toolActionRequests.id, input.actionRequestId), eq(toolActionRequests.status, "executing"), eq(toolActionRequests.updatedAt, input.claimUpdatedAt))); + return true; + }); + } + async function markApprovedActionFailed(input: { actionRequestId: string; invocationId: string; @@ -9277,6 +10135,7 @@ export function createToolGatewayService( updatedAt: now, }) .where(eq(toolInvocations.id, invocation.id)); + await markMcpTaskDelivered(invocation.companyId, invocation.id); void emitConnectionInvoked(db, invocation.id); await writeToolReviewChange(db, claimed.companyId, tx => tx .update(toolActionRequests) @@ -9307,6 +10166,13 @@ export function createToolGatewayService( }); return resultValidation.value; } catch (error) { + // The provider is still working on the approved action. Keep the + // approval: the next execution attaches to the same task instead of + // asking the person again or starting the work twice. + if (error instanceof ToolGatewayHttpError && error.reasonCode === "provider_task_pending" + && await resumeApprovedActionForPendingTask({ actionRequestId: claimed.id, invocationId: invocation.id, claimUpdatedAt: claimed.updatedAt, message: error.message })) { + throw error; + } const { reasonCode } = await markApprovedActionFailed({ actionRequestId: claimed.id, invocationId: invocation.id, @@ -11545,6 +12411,8 @@ export function createToolGatewayService( promptInjectionMode: "ignore", }); let recoveredGitHubPublication: { content: string; data: unknown } | undefined; + /** A keyed retry collecting its provider task (MCP Tasks); it may only attach to that task. */ + let retryingMcpTaskRecordId: string | null = null; let effectiveParameters: unknown = requestedParameters; let effectiveArgumentsSummary = argumentValidation.summary; @@ -12008,6 +12876,16 @@ export function createToolGatewayService( throw new ToolGatewayHttpError(409, "Idempotency key belongs to a different GitHub publication", "github_idempotency_conflict"); const retryingGitHubPublication = gitHubPublicationReplay && accessDecision.allowed && recorded.invocation.approvalState === "not_required" && gitHubReplayBindingMatches; + // A keyed retry of a call whose provider task is still undelivered + // runs again so it attaches to the task; it never sends tools/call twice. + retryingMcpTaskRecordId = recorded.replayed && accessDecision.allowed && !retryingSlackRateLimit && !retryingGitHubPublication + && recorded.invocation.agentId === session.agentId && await mcpTasksEnabled() + ? await mcpTaskForKeyedRetry(session.companyId, recorded.invocation, { + connectionId: tool.connectionId ?? null, argumentsIdentity: mcpTaskArgumentsIdentity(effectiveParameters), + callerHeaders: input.callerHeaders, + }) + : null; + const retryingMcpTask = Boolean(retryingMcpTaskRecordId); if (retryingGitHubPublication) { // Invocation hashes describe shortened audit previews. The durable // publication checks the complete saved request and current authority. @@ -12032,7 +12910,7 @@ export function createToolGatewayService( throw new ToolGatewayHttpError(409, "The saved GitHub publication is not available yet", "github_publication_unavailable"); } } - if (recorded.replayed && !retryingSlackRateLimit && !retryingGitHubPublication) { + if (recorded.replayed && !retryingSlackRateLimit && !retryingGitHubPublication && !retryingMcpTask) { if (gitHubPublicationReplay && !gitHubReplayPolicyAllowed) throw new ToolGatewayHttpError(policyErrorStatus(accessDecision), accessDecision.explanation, accessDecision.reasonCode); await writeAudit({ @@ -12110,7 +12988,7 @@ export function createToolGatewayService( .update(toolInvocations) .set({ status: "executing", - ...(retryingGitHubPublication ? { errorCode: null, errorMessage: null, completedAt: null } : {}), + ...(retryingGitHubPublication || retryingMcpTask ? { errorCode: null, errorMessage: null, completedAt: null } : {}), startedAt: new Date(), updatedAt: new Date(), }) @@ -12161,6 +13039,13 @@ export function createToolGatewayService( invocationId, input.callerHeaders, input.timeoutMs === undefined, + { + // Approved actions keep their run's attribution, not its lifetime. + run: session.runId && !input.approvedActionRequestId + ? adapterExecutionControls.get(session.runId)?.controller.signal : undefined, + caller: input.signal, + attachToTaskRecordId: retryingMcpTaskRecordId, + }, ) : tool.providerType === "mcp_local_stdio" ? await executeLocalStdioTool( @@ -12221,6 +13106,8 @@ export function createToolGatewayService( updatedAt: completedAt, }) .where(eq(toolInvocations.id, invocationId)); + // A provider task's result is now recorded; only now is it delivered. + await markMcpTaskDelivered(session.companyId, invocationId); if (input.approvedActionRequestId) { const actionRequestId = input.approvedActionRequestId; const [executedRequest] = await writeToolReviewChange(db, session.companyId, tx => tx @@ -12807,6 +13694,51 @@ export function createToolGatewayService( return { ...sessionView, revokedAt: session!.revokedAt ?? now }; }, + /** + * Poll provider tasks that no live call is waiting on (MCP Tasks). Each + * row is claimed with a short lease, so replicas never poll one twice. + */ + async pollDueMcpTasks(input: { signal?: AbortSignal; limit?: number; wake?: McpTaskWake } = {}) { + if (!(await mcpTasksEnabled())) return { processed: 0 }; + const now = new Date(); + const due = await db.select().from(toolMcpTasks).where(and( + lte(toolMcpTasks.nextPollAt, now), + or(isNull(toolMcpTasks.leaseExpiresAt), lte(toolMcpTasks.leaseExpiresAt, now)), + )).orderBy(asc(toolMcpTasks.nextPollAt)).limit(input.limit ?? 25); + let processed = 0; + for (const candidate of due) { + if (input.signal?.aborted) break; + const owner = `worker:${randomUUID()}`; + const [claimed] = await db.update(toolMcpTasks).set({ leaseOwner: owner, leaseExpiresAt: new Date(Date.now() + MCP_TASK_WORKER_LEASE_MS), updatedAt: new Date() }) + .where(and( + eq(toolMcpTasks.id, candidate.id), eq(toolMcpTasks.companyId, candidate.companyId), + eq(toolMcpTasks.nextPollAt, candidate.nextPollAt!), + or(isNull(toolMcpTasks.leaseExpiresAt), lte(toolMcpTasks.leaseExpiresAt, now)), + )).returning(); + if (!claimed) continue; + try { + await pollStoredMcpTask(claimed, owner, input.wake, input.signal); + } catch (error) { + logger.warn({ err: error, companyId: claimed.companyId, taskRecordId: claimed.id }, "provider task poll failed"); + await updateMcpTask(claimed, { + leaseExpiresAt: null, leaseOwner: null, pollFailures: claimed.pollFailures + 1, + nextPollAt: new Date(Date.now() + backgroundPollDelayMs({ pollIntervalMs: claimed.pollIntervalMs, status: claimed.status as McpTaskRecordStatus, failures: claimed.pollFailures + 1 })), + }, { owner }).catch(() => undefined); + } + processed += 1; + } + return { processed }; + }, + + /** The next time a stored provider task needs attention, or null when none does. */ + async nextMcpTaskPollAt(): Promise { + if (!(await mcpTasksEnabled())) return null; + const [row] = await db.select({ + at: sql`min(greatest(${toolMcpTasks.nextPollAt}, coalesce(${toolMcpTasks.leaseExpiresAt}, ${toolMcpTasks.nextPollAt})))`, + }).from(toolMcpTasks).where(sql`${toolMcpTasks.nextPollAt} is not null`); + return row?.at ? new Date(row.at).getTime() : null; + }, + async nextCredentialExpiryAt(): Promise { const [row] = await db.execute<{ at: string | Date | null }>(sql` select min(expires_at) as at from ( diff --git a/server/src/startup-recovery-timing.ts b/server/src/startup-recovery-timing.ts index 1c1519e9870..193711d0834 100644 --- a/server/src/startup-recovery-timing.ts +++ b/server/src/startup-recovery-timing.ts @@ -1,6 +1,6 @@ import { ROOT_CONTEXT, SpanStatusCode, trace, type Span } from "@opentelemetry/api"; -type StartupRecoveryPhase = "tool_reviews" | "gateway_sessions" | "delivery_workers" +type StartupRecoveryPhase = "tool_reviews" | "gateway_sessions" | "mcp_tasks" | "delivery_workers" | "accounting" | "plugin_workers" | "native_recovery" | "hot_restart" | "orphan_reaping" | "scheduled_retries" | "queued_runs" | "fresh_queued_runs" | "goal_actions" | "active_goals"; diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 8fe8d048988..52e94651755 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -253,7 +253,7 @@ "packages/shared/src/external-objects.ts": "a9953c4e3f77f2bad03cb7832914ffc0b1a1266a", "packages/shared/src/fast-response.ts": "a81332a2b46b59c1f6953cfc4da659eae2326beb", "packages/shared/src/feature-catalog.test.ts": "d3e000c039492daad1fe0b7302b34e7c3816a8ce", - "packages/shared/src/feature-catalog.ts": "cf667a58319771ee9c87e2148f8bfe6529380192", + "packages/shared/src/feature-catalog.ts": "293f19e7958a144ed75032149d76bbe72b995bbb", "packages/shared/src/frontmatter-runner-contract.test.ts": "cd121330e10aaa9da36c16293bcd9760561b6b41", "packages/shared/src/frontmatter.test.ts": "56635e331c8abca8868da76f23a08e98f20ff07f", "packages/shared/src/frontmatter.ts": "a86e046ce588d2f92d4996122cc2068ec275e89c", @@ -408,7 +408,7 @@ "packages/shared/src/types/inbox-dismissal.ts": "58fb7013847396ac9971eb5799dd0bf0486e0371", "packages/shared/src/types/inbox-mine.ts": "1d302b531d34842189704abd2f75f8743d09490d", "packages/shared/src/types/index.ts": "f63f67250d6d5a0b737478c634244ae3aba0328a", - "packages/shared/src/types/instance.ts": "2c40a18c05010991d93d719937faa4a43e47104f", + "packages/shared/src/types/instance.ts": "ddabd7cc0d885b5fdf45b33a7937b7b704f8fb7d", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", "packages/shared/src/types/issue.ts": "725bd6f677b9d461460697d1ce10dee739a66ebe", "packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec", @@ -485,7 +485,7 @@ "packages/shared/src/validators/inbox-agent-policy.ts": "29cef157f4d9b564fd813868038aa8c813df4a7b", "packages/shared/src/validators/index.ts": "a62024f564b768d87e9b8a2869c0b8b9ce92dc09", "packages/shared/src/validators/instance.test.ts": "3faa9593a9a05f74429d9b1d2251906a03e9a903", - "packages/shared/src/validators/instance.ts": "d94ffda92ccacd3d9410562e2898410db1a100be", + "packages/shared/src/validators/instance.ts": "d801db219659707f0c9a8c1fbad06e862be4892d", "packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645", "packages/shared/src/validators/issue-tree-control.ts": "7144ef86a83e008ac0626e1d62a1d6164c46f438", "packages/shared/src/validators/issue.test.ts": "9a10bf1112d7c85f80cc1fd5db9920dda8974643", diff --git a/ui/src/pages/InstanceExperimentalSettings.test.tsx b/ui/src/pages/InstanceExperimentalSettings.test.tsx index 08def9e8e68..75f8e2296c3 100644 --- a/ui/src/pages/InstanceExperimentalSettings.test.tsx +++ b/ui/src/pages/InstanceExperimentalSettings.test.tsx @@ -125,6 +125,7 @@ function defaultExperimentalSettings(): InstanceExperimentalSettingsPayload { enableWorkspaceDirtyQuarantineRepair: true, enableOwnerInstanceAdmin: false, enableSandboxDuplexBridge: false, + enableMcpTasks: false, enableRunnerPreviewIngress: false, enableWorktreeRunExecution: false, worktreeRunExecutionActivatedAt: null, diff --git a/ui/src/pages/InstanceExperimentalSettings.tsx b/ui/src/pages/InstanceExperimentalSettings.tsx index 737614b6864..5925d8023b6 100644 --- a/ui/src/pages/InstanceExperimentalSettings.tsx +++ b/ui/src/pages/InstanceExperimentalSettings.tsx @@ -414,6 +414,18 @@ export function InstanceExperimentalSettings() { ariaLabel="Toggle decisions experimental setting" /> + toggleMutation.mutate({ enableMcpTasks: checked })} + disabled={toggleMutation.isPending} + settingKey="enableMcpTasks" + managed={managedKeys.enableMcpTasks} + ariaLabel="Toggle durable app actions experimental setting" + /> +