fix(mcp): coalesce replayed write requests

Merged
AG
2mo ago
+349-84

MCP transport replays could run one write request twice because the server did not retain a receipt keyed to the JSON-RPC request. A duplicate fleet spawn created a second Cloud invocation that then failed with spawn_agent_name_in_use, even when the original invocation had already completed successfully. The same gap duplicated DMs.

This adds a per-server replay cache keyed by MCP session, tool name, and JSON-RPC request ID. It shares the original result for a replay while separate requests, including identical message contents or a deliberate second same-name spawn, remain independent.

Validation:

  • npm exec vitest -- run packages/cli/src/cli/agent-relay-mcp.startup.test.ts packages/cli/src/cli/mcp/messaging-tools.delivery.test.ts packages/cli/src/cli/mcp/messaging-tools.protocol.test.ts
  • npm exec tsc -- -p packages/cli/tsconfig.json --noEmit

[!NOTE]
Medium Risk
Changes deduplication for state-changing MCP tools (spawn, add_agent, DMs); mis-keyed retries could still duplicate work, but the scope is bounded to MCP write paths with new tests.

Overview
Fixes duplicate side effects when the MCP transport replays the same JSON-RPC call: fleet spawn, legacy add_agent, and send_dm now run through a per-server McpRequestReplay that shares one in-flight execution for the same MCP session, tool, and request id (numeric and string ids stay distinct).

Clients can pass optional idempotency_key on those tools to retry after a lost response without spawning twice or sending duplicate DMs; completed results for a key are kept briefly (5 minutes). Dedup keys intentionally ignore message/spawn arguments, so identical content with different request ids still sends separately, and a later reuse of the same JSON-RPC id with a new idempotency key is not treated as a replay.

Tool metadata marks these writes as non-idempotent unless the client supplies a key. Startup tests cover replay coalescing, idempotency retries, and DM behavior.

Reviewed by Cursor Bugbot for commit 1abeebfee18fff6e3f9644e77d7987a0a8ef6473. Bugbot is set up for automated code reviews on this repo. Configure here.