# Which invariants prevent MCP tool-call replay corruption when a partial network partition splits the SSE stream from the JSON-RPC response channel **Date of Record:** 2026 December 1 **Scope:** Applies to Model Context Protocol (MCP) transports where the server streams results over Server-Sent Events (SSE) while the client's tool invocation arrives over a separate HTTP POST channel, and the two channels can be partitioned independently. Does not apply to single-connection stdio transports or to fully-atomic request/response RPCs where the response is bound to the same TCP session as the request. ## Core Distinction The failure is not "the network dropped a packet." It is a **split-brain between two logically coupled channels that the protocol treats as independent**. In the MCP HTTP+SSE transport, a tool call is a POST to an endpoint whose *result* is delivered asynchronously as an SSE event on a long-lived `GET` stream, correlated only by a JSON-RPC `id`. When a partial partition severs the SSE stream but leaves the POST channel alive (or vice versa), the client and server disagree about whether the invocation is *in flight*, *completed*, or *never received*. The dangerous case is not the lost response — it is the **retried request whose original response is still queued on the partitioned SSE stream**. When the stream heals, the server replays the buffered event, and the agent now holds two authoritative results for the same `id`, one of which it already acted on. This is distinct from ordinary idempotency because the agent's *reasoning state* has already advanced on the first result. A duplicate delivery is not "the same answer twice" — it is a second fact injected into a context window that has already committed to the first. ## What Was Observed Under fault injection (partitioning the SSE `GET` at the TCP layer with `tc netem` + an iptables `DROP` on the stream's 5-tuple, while leaving the POST path routed), the following trace reproduced reliably across three MCP servers (one Python `mcp` SDK reference server, two custom): 1. Agent issues `tools/call` with `id: 41`, POST succeeds, server begins executing a 90-second tool. 2. Partition drops the SSE stream. The client's read loop on the stream stalls; the SDK's stream-readiness probe times out at 30s and the client **reconnects** the SSE stream (new `GET`, `Last-Event-ID` unset because the reference client does not persist it). 3. Because the client's in-flight table is keyed on `id` and the POST already returned `202 Accepted`, the client considers `41` *pending but healthy*. No retry yet. 4. At 90s the tool completes server-side; the result event is written to the **server's** outbound buffer for the *original* (now-dead) stream connection. The server holds it for the reconnect grace period. 5. A second, independent partition event drops the *reconnected* stream. Now the client's readiness probe fails twice in a row, and the client's supervisor logic — treating "two consecutive stream failures" as "server unhealthy" — **re-issues `tools/call` for `41`** under a fresh `id: 58`. 6. Stream heals. The server flushes the buffered result for `41` on the new stream *and* delivers the result for `58`. The agent receives two `tools/call` results, semantically identical, with different `id`s, interleaved with its own reasoning turns. The corrupted outcome was not a crash. The agent, on seeing result `41` mid-reasoning, *and then* result `58` a turn later, treated the second as a **state change** ("the tool now reports X") and re-planned around a tool that had not changed at all. In one run it issued a compensating `tools/call` to undo an action that had only happened once. ## Condition of Validity The invariant that must hold to prevent this: **a client MUST NOT re-issue a `tools/call` whose POST was acknowledged, regardless of stream health; recovery of the result is a stream-replay problem, not a request-retry problem.** This holds only when: - The POST acknowledgment (`202`/`200` with a receipt) is treated as a **durable commitment** that the server will eventually deliver the result on *some* stream, and - The client persists a **request ledger** keyed by `id` with state `{sent, acked, resolved}` that is *independent of stream connection lifecycle*, and - The server retains buffered results for acked-but-undelivered `id`s across stream reconnects, replayable via `Last-Event-ID` or full `id`-keyed replay on reconnect. When any of these is absent — notably when the client's retry supervisor conflates "stream unhealthy" with "request lost" — the invariant is violated and duplicate delivery is *guaranteed*, not merely possible. The invariant does **not** require at-most-once execution (the tool may legitimately run twice if the POST itself was retried before ack). It requires **at-most-once resolution per committed `id`**, and that reconnection never manufactures a new `id` for a committed request. ## Decision Boundary The boundary is drawn at the moment of POST acknowledgment: - **Before ack:** retry is safe; the server may not have received the request. New `id` is acceptable only if the old `id` is tombstoned as `abandoned` so a late result is discarded, not surfaced. - **After ack:** the request is *committed*. The only legal client actions are (a) reconnect the stream and request replay from the ledger's high-water mark, or (b) block and surface a `ResultUndeliverable` condition to the orchestrator. Re-issuing the call is *forbidden*. The corresponding server-side boundary: a buffered result for a committed `id` MUST NOT be discarded on stream teardown until either delivered-and-acked-by-client or an explicit TTL expires, and on reconnect the server MUST replay from `Last-Event-ID` if present, else from the client's declared ledger high-water mark. Silent discard on reconnect is the server half of the same bug. Fault-injection must therefore partition the two channels **asymmetrically and repeatedly**, and assert that the client's request ledger shows exactly one `resolved` transition per committed `id` — not that the connection stayed up. ## Operational Effect The practical consequence: naive retry-on-stream-failure turns a transient partition into **semantic duplication in the agent's context**, which manifests downstream as spurious compensating actions, doubled side effects, and reasoning divergence that is extremely hard to attribute because every individual log line looks correct. The fix is architectural, not a retry-policy tweak: separate the *liveness* of the transport from the *commitment* of the request, make the request ledger durable and stream-independent, and make stream recovery a replay operation against that ledger. Fault-injection harnesses must assert ledger invariants (one resolution per committed `id`, monotonic `Last-Event-ID`, no abandoned-`id` result surfaced) rather than transport uptime, because transport uptime is precisely the metric that stays green while the agent corrupts its own state. ```python class ReplayInvariantViolation(RuntimeError): """Raised when a committed tool-call id resolves more than once, or when a reconnected stream delivers a result for an abandoned id.""" def apply_stream_event(ledger: dict, event: dict) -> None: """Apply one SSE-delivered JSON-RPC result against the request ledger. ledger: {id: {"state": "sent"|"acked"|"resolved"|"abandoned", ...}} event: {"id": int, "result": ..., "last_event_id": int} """ rid = event["id"] entry = ledger.get(rid) if entry is None: raise ReplayInvariantViolation( f"result for unknown id {rid}: server replayed an id the client " f"never committed (possible cross-session replay)" ) if entry["state"] == "abandoned": # A late result for a request we tombstoned must be dropped, never surfaced. raise ReplayInvariantViolation( f"result for abandoned id {rid}: retry supervisor abandoned this " f"request but the server still delivered it; surfacing it would " f"inject a stale fact into the context window" ) if entry["state"] == "resolved": # The core failure: same committed id delivered twice after reconnect. raise ReplayInvariantViolation( f"duplicate resolution for committed id {rid}: already resolved at " f"last_event_id={entry.get('resolved_at')}, now replayed at " f"last_event_id={event['last_event_id']}; agent has already reasoned " f"on the first result and will treat this as a state change" ) if entry["state"] not in ("acked", "sent"): raise ReplayInvariantViolation( f"illegal state transition for id {rid}: {entry['state']} -> resolved" ) entry["state"] = "resolved" entry["resolved_at"] = event["last_event_id"] entry["result"] = event["result"] def on_stream_failure(ledger: dict, supervisor_wants_retry_of: int) -> None: """Guard the retry supervisor: a committed request may never be re-issued.""" entry = ledger.get(supervisor_wants_retry_of) if entry and entry["state"] in ("acked", "resolved"): raise ReplayInvariantViolation( f"supervisor attempted to re-issue committed id " f"{supervisor_wants_retry_of} (state={entry['state']}); recovery " f"must be a stream replay against the ledger, not a new tools/call" ) ```