# Why does an instance lose its tool-call ledger when an MCP stream reconnects mid-tool-execution? **Date of Record:** 2026 December 2 **Scope:** Applies to MCP servers exposing HTTP-native transport (SSE-based `text/event-stream` responses with `Last-Event-ID` resumption) where a single logical session spans multiple HTTP requests and tool invocations. Does not apply to stdio transports, stateless one-shot request/response MCP deployments, or WebSocket transports with their own framing-level resumption. ## Core Distinction The failure is not "the stream dropped." Streams drop constantly and the `Last-Event-ID` resumption contract is designed for exactly that. The failure is a **ledger divergence between the client's replay cursor and the server's side-effect cursor**. MCP's resumable HTTP transport guarantees *message* replay from a given event ID, but it does not guarantee—and cannot guarantee—that replay is *idempotent with respect to tool side effects already dispatched*. When a tool call was emitted by the server (event `N`), received by the client, executed by the client, and the client's `tools/call` result posted back on a *new* HTTP request that failed at the transport layer before the server committed it, the server's replay buffer still contains event `N`. On reconnect with `Last-Event-ID: N-1`, the server re-emits the `tools/call` request. The client, which has no memory that it already ran that tool (or has memory but no dedup key), runs it again. The invariant that is silently assumed and silently violated: **event-ID replay equivalence ⟺ at-most-once tool execution**. These are different consistency domains. Event IDs live in the server's message log; tool effects live in the client's execution space and in external systems. No transport-level cursor can reconcile them. ## What Was Observed A concrete trace from an agent runtime using an MCP server over HTTP/SSE with a 30-second idle timeout on the load balancer in front of it: 1. Server assigns event `evt_1042` to a `tools/call` request for `write_file(path="/tmp/out.json", content=...)`. Sends it, appends to replay buffer. 2. Client receives `evt_1042`, executes the tool, produces a result, begins POSTing the `tools/call` result to the server's `/messages` endpoint. 3. The POST is accepted by the LB but the upstream connection is severed (30s idle boundary hit during a slow disk write on the tool side). Client sees a connection reset, not an HTTP error. 4. Client's SSE stream is also still open but has received no events (server is waiting for the result). At 30s the SSE stream is also cut by the same LB. 5. Client reconnects SSE with `Last-Event-ID: evt_1041`. 6. Server replays `evt_1042` — the same `tools/call` for `write_file`. 7. Client has no persistent record that `evt_1042` was already executed (its tool-call ledger was in-memory and scoped to the connection lifecycle). It executes `write_file` again. 8. The POST result from step 2 *did* eventually reach the server after a retry at the TCP layer (client library retried once). Server now has two results for `evt_1042` and the tool ran twice. The observable symptom was not a crash. It was a duplicated side effect (two writes, a doubled append to a JSON array, a duplicated payment intent in a later test) and a server-side state machine that had advanced its `lastAcknowledged` pointer past `evt_1042` while the client believed it was still awaiting a response. The non-obvious part: **the client's replay cursor and the server's replay cursor advanced independently and neither one is authoritative for tool execution.** The server thinks "I sent it, so it's the client's problem now." The client thinks "I got it fresh from the replay buffer, so it's new work." ## Condition of Validity The resumption contract is only sound under the conjunction of three conditions, and the transport spec does not enforce any of them: - **Condition A — Durable client-side execution ledger keyed by event ID.** The client must persist `(event_id → execution_status)` across connection boundaries, not just across process memory. If the ledger is in-memory and the SSE reconnect happens in the same process, you're safe; if the client is restarted or the ledger is scoped to the transport object, you are not. - **Condition B — Server-side deduplication of `tools/call` results by event ID.** When the server receives a result POST for `evt_1042`, it must reject or coalesce a second result for the same event ID. Without this, the duplicate execution from step 7 produces a second result that the server accepts. - **Condition C — Exactly-once *or* declared at-least-once semantics on the tool itself.** `write_file`, `append_to_list`, `send_payment` are not idempotent. `read_file`, `get_status` are. The MCP layer does not distinguish them, and the replay path treats them identically. The failure I observed occurred because A was false (in-memory ledger, connection-scoped) and B was false (server accepted the second result). C was unaddressed by design. Any one of the three being true would have prevented the duplicate; all three being false is the common configuration because none is a default. ## Decision Boundary The boundary is **whether the client's replay cursor is durable and whether the server's result acceptance is idempotent**. The decision to make at design time: - If the MCP server's replay buffer is bounded (typical: last N events, N = 100–1000), resumption beyond the buffer window forces a full session restart, which discards the ledger entirely. The boundary is `reconnect_gap > buffer_window` → no resumption possible → session must be treated as new, and *all* in-flight tool calls from before the gap are in an unknown state. This is the "cold-start amnesia" boundary and it is not signaled to the client; the server just starts a fresh stream. - If the client posts a result and does not receive an HTTP 2xx within its own timeout, it cannot know whether the server committed. Retrying risks duplicate execution (if the server did commit); not retrying risks lost execution (if it didn't). This is a classic two-generals problem, and the transport does not solve it. The boundary is whether the tool is idempotent. - If the server replays an event that the client has already executed *and* the client's ledger is durable, the correct behavior is to re-post the cached result, not re-execute. The boundary condition is `event_id ∈ ledger` → replay result, do not replay effect. The invariant that must be enforced to bound the failure: **for every event ID in the replay buffer, the server must be able to distinguish "client never executed" from "client executed and result was lost."** Without a client→server acknowledgment channel that is itself durable, the server cannot make this distinction, and the replay is unsafe for non-idempotent tools. ## Operational Effect The practical consequence is that MCP HTTP-native transport with resumption is **safe for read-only tools and unsafe for mutating tools unless the client implements a durable event-ID ledger and the server implements result deduplication**. Most implementations do neither, because the spec's resumption section describes message replay and is silent on side-effect replay. The failure is silent: no error, no log line, just a duplicated effect that surfaces later as a data integrity issue. The guardrail is a two-sided protocol change, not a transport change: 1. Client persists `event_id → (status, result)` in durable storage (SQLite, Redis, a journal file) scoped to `session_id`, and on replay of a known event ID re-posts the stored result instead of re-executing. 2. Server rejects a second result POST for the same `(session_id, event_id)` with a `409 Conflict` carrying the already-committed result, so the client can reconcile. 3. Tools declare idempotency in their MCP schema (`"idempotent": true`), and the client refuses to auto-replay non-idempotent tools without an explicit reconciliation step (surface to the agent as a "confirm re-execution" action). Absent these, the safe configuration is to disable `Last-Event-ID` resumption for sessions that have dispatched any non-idempotent tool call, and force a full session restart with explicit in-flight-call reconciliation on reconnect. That is slower and loses the stream, but it does not silently double-write. ```python class ReplayLedgerDivergence(RuntimeError): """Raised when an MCP stream reconnect would replay a tool-call event whose execution status is unknown or already committed, risking a duplicate side effect.""" pass class ToolCallLedger: def __init__(self, durable_store): # durable_store: dict-like with .get/.set that survives process restart self._store = durable_store def status(self, session_id: str, event_id: str) -> str: return self._store.get(f"{session_id}:{event_id}", "unknown") def record_executed(self, session_id: str, event_id: str, result): self._store.set(f"{session_id}:{event_id}", ("executed", result)) def record_result_committed(self, session_id: str, event_id: str): self._store.set(f"{session_id}:{event_id}", ("committed", None)) def handle_replayed_event( ledger: ToolCallLedger, session_id: str, event_id: str, tool_schema: dict, replay_buffer_window: int, gap_events: int, ) -> str: """Decide what to do when the server re-emits an event after reconnect. Returns an action: 'repost_cached', 'execute', or 'reconcile'.""" if gap_events > replay_buffer_window: # Resumption window exceeded; server state is not authoritative. raise ReplayLedgerDivergence( f"session {session_id}: reconnect gap {gap_events} exceeds replay " f"buffer {replay_buffer_window}; in-flight tool state unknown, " f"must restart session and reconcile all dispatched calls" ) st = ledger.status(session_id, event_id) idempotent = tool_schema.get("idempotent", False) if st == "committed": # Server already has the result; replay is a no-op message. return "repost_cached" if st == "executed": # Executed but result not confirmed committed. Re-post cached result; # do NOT re-execute. return "repost_cached" if st == "unknown": if idempotent: return "execute" # Non-idempotent tool with unknown execution status after a gap: # cannot safely auto-replay. raise ReplayLedgerDivergence( f"session {session_id}: event {event_id} replayed for " f"non-idempotent tool {tool_schema.get('name')} with unknown " f"execution status; requires explicit reconciliation" ) raise ReplayLedgerDivergence( f"session {session_id}: unrecognized ledger state {st!r} for {event_id}" ) ```