# Which invariants prevent session resumption from silently forking an MCP agent's tool-call state across SSE replay boundaries **Date of Record:** 2026 November 25 **Scope:** Applies to MCP clients and servers using the HTTP-native transport (streamable HTTP + SSE), specifically when a client resumes a session after a dropped connection via `Last-Event-ID` replay and the server is configured for stateless request handling. Does not apply to stdio transport, nor to stateful servers that pin a session to a single in-memory event log. ## Core Distinction The failure is not "the connection dropped." Connections drop constantly and resumption works. The failure is the **semantic gap between transport-level replay and reasoning-level idempotency**: SSE replay guarantees that the *bytes* of events `id=N+1..M` are re-delivered, but it does not guarantee that the client's *interpretation* of those bytes is unchanged. When an MCP server runs statelessly across shards, the resumed stream may be served by a different process that has no memory of what the client already acknowledged, what tool-call IDs are in flight, or which `initialize`-negotiated capabilities the session actually holds. The client then resumes with a `Last-Event-ID` that the new shard interprets as "start fresh from your cursor," while the client interprets it as "continue exactly where I was." Both are locally correct; the composition forks the agent's tool-call state. ## What Was Observed A tool-orchestrating agent (call it the *executor*) issued `tools/call` for `write_file` against a long-running MCP server. The call was dispatched, the server began streaming progress notifications as SSE events with monotonic IDs, and the executor received events `1..14` before the TCP connection was reset by an intermediate proxy (idle timeout at 30s during a slow filesystem flush). The executor held `Last-Event-ID: 14` and reconnected. The reconnect landed on shard B. Shard B was stateless: it had no record of session `sess_7c2`, no record that `write_file` was mid-flight, and — critically — no record that the executor had already been told `id=14` carried a *partial* progress payload. Shard B's event store was a shared append-only log, so it happily replayed from `id=15`. But shard B's *handler* for the resumed request re-entered the dispatch path and re-issued the `write_file` tool call with a fresh `call_id`. The executor, seeing a new `call_id` in the resumed stream, treated it as a *new* tool invocation and dispatched it a second time. Two `write_file` operations ran against the same path. The second one clobbered the first's partial output. The executor's local transcript recorded a single logical call; the filesystem recorded two physical writes. The tell was subtle: the executor's replay log showed `id=14` (partial) followed by `id=15` (a `call_id` it had never emitted). A naive client would have accepted `id=15` as continuation. The invariant that *should* have held — "a resumed stream contains only events causally downstream of the client's cursor, under the same session identity" — was violated because session identity was transport-scoped, not reasoning-scoped. ## Condition of Validity The replay contract is only sound when **all three** of the following hold simultaneously: 1. **Session identity is durable and shard-independent.** The session token must resolve to the same logical handler state regardless of which process serves the reconnect. If the server is stateless, the session token must carry (or point to) enough state to reconstruct the in-flight tool-call set — at minimum, the set of outstanding `call_id`s and their status. 2. **Event IDs are causally dense per session, not per connection.** A gap in the ID sequence is not "resume from here"; it is "you missed events that may have changed your interpretation of the next event." If the server cannot prove density, it must renegotiate rather than replay. 3. **The `Last-Event-ID` cursor is bound to a capability snapshot.** The `initialize` handshake negotiated a set of capabilities (tools, resources, sampling, experimental features). A resumed stream served by a shard with a different capability snapshot must not silently proceed; it must re-run capability negotiation, because a tool-call event interpreted under a stale capability set is a different event. When any of these fails, the correct behavior is to **refuse the resume and force a fresh `initialize`**, not to replay. The stateless server's instinct — "I have the event bytes, so I can serve them" — is exactly the wrong instinct. ## Decision Boundary The boundary is between **replay as transport** and **replay as state transfer**. Transport replay is safe when the client's only obligation on resume is to append bytes to a transcript. State transfer is required when the client's obligation includes re-deriving in-flight intent. The two are indistinguishable from the wire, which is why the failure is non-obvious. Operationally, the decision is: *does the resumed stream contain any event whose interpretation depends on state the client built before the disconnect?* If yes — any `tools/call` result, any `sampling/createMessage` response, any progress notification tied to an outstanding `call_id` — then replay alone is insufficient and the server must either (a) prove session continuity via a durable session store, or (b) signal `session_invalidated` and require re-initialization. A server that cannot do either must not advertise resumable sessions. The concrete guardrail: on reconnect, the client sends `Last-Event-ID` **and** a `session_epoch` (a hash of its negotiated capability snapshot + outstanding `call_id` set). The server compares epochs. Mismatch → `409 session_epoch_mismatch`, client re-initializes. Match → replay proceeds with the guarantee that the cursor is causally dense. This converts a silent fork into a loud, recoverable renegotiation. ## Operational Effect Without the epoch check, the failure mode is **silent duplicate tool execution with divergent state** — the worst class of agent bug, because the transcript looks clean, the logs look clean, and only the side effects reveal the fork. Agents that write files, send messages, or mutate remote state are the highest-risk class; read-only tool calls degrade to wasted tokens rather than corruption. With the epoch check, the failure degrades to a **bounded re-initialization**: the agent loses the in-flight call, must re-issue it, and pays a round-trip. That is a recoverable cost. The invariant to encode in the client is: *never treat a resumed SSE event as continuation unless the server has confirmed session-epoch continuity; otherwise treat the stream as a fresh session and reconcile outstanding `call_id`s against the server's authoritative state before re-dispatching.* ```python class SessionEpochMismatch(RuntimeError): """Raised when a resumed MCP SSE stream cannot prove causal continuity with the client's pre-disconnect state. The client MUST re-initialize rather than replay, to avoid duplicate tool-call dispatch.""" pass def resume_stream( last_event_id: int, client_epoch: str, server_epoch: str, outstanding_call_ids: set[str], server_known_call_ids: set[str], ) -> int: """Validate that a resumed SSE stream is causally continuous with the client's pre-disconnect state. Returns the cursor to resume from, or raises SessionEpochMismatch to force re-initialization.""" if client_epoch != server_epoch: # Capability snapshot or session identity diverged across shards. raise SessionEpochMismatch( f"epoch mismatch: client={client_epoch!r} server={server_epoch!r}; " f"refusing replay, re-initialize required" ) # Even with matching epochs, the server must know about every in-flight # call the client believes is outstanding. An unknown call_id means the # server has no handler state for it -> replay would fork execution. orphans = outstanding_call_ids - server_known_call_ids if orphans: raise SessionEpochMismatch( f"server has no state for in-flight call_ids {sorted(orphans)}; " f"replay would re-dispatch them, refusing" ) # Cursor is causally dense and session identity is continuous: safe. return last_event_id + 1 ```