# Which invariants prevent SSE resumption tokens from silently forking an MCP session across reconnects **Date of Record:** 2026 December 3 **Scope:** Applies to MCP servers exposing the HTTP-native transport with Server-Sent Events streaming plus a `Last-Event-ID`-style resumption token (the Streamable HTTP transport). Does not apply to stdio transports, nor to plain request/response HTTP endpoints without a persistent event stream. ## Core Distinction There are two different things a resumption token can mean, and conflating them is the root of the failure. The first is a **replay cursor**: "re-send me buffered events strictly after sequence N." This is what the SSE `Last-Event-ID` spec implies, and it is stateless with respect to the client — the server only needs the event buffer. The second is a **session identity anchor**: "I am the same logical MCP session that was talking to you before the socket dropped, restore my negotiated state." This is what the MCP session model actually requires, because the session carries negotiated capabilities, subscriptions, and in-flight request correlation IDs that are *not* reconstructible from event replay alone. A correct implementation treats the token as *both simultaneously* and enforces that they advance together. The failure mode is an implementation that treats the token as a pure replay cursor while the server keeps session state in a per-connection structure. When the connection dies, the buffer survives but the session state does not, and the resumed stream is a replay of a conversation whose other half has been garbage-collected. ## What Was Observed A client opened a stream, negotiated capabilities, issued a long-running tool call (`tools/call` for a code-search over a large index), and received a partial `notifications/progress` stream. Mid-call the TCP connection reset. The client reconnected with `Last-Event-ID: 4471` and a session header carrying the prior session ID. The server's behavior on reconnect: 1. Looked up the event buffer by session ID — **found it**, because buffers were keyed by session and TTL'd for 5 minutes. 2. Replayed events 4472 onward — the buffered progress notifications, then the *final* `tools/call` result event that had been written to the buffer at completion time. 3. Did **not** reconstruct the in-flight request table, because that table was a per-connection `dict` destroyed on socket close. The client therefore received a well-formed, ordered, replay-consistent stream that terminated in a valid JSON-RPC result for a request the server no longer had any record of. The result was delivered. The client's request-completion callback fired. The client marked the call done and advanced its own state. But the server, having lost the request table, had *also* — through a separate retry path — re-executed the tool call when a second reconnect arrived 40 seconds later with the same `Last-Event-ID` (the client's dedupe window had expired). The second execution produced a *different* result (the index had been re-sharded in between), which was appended to the buffer at a new sequence number. Now the buffer contained two terminal results for the same JSON-RPC `id`. The client's request table, keyed by `id`, was already closed. The second result was dropped as "unknown id" — but the server had now performed the side-effecting tool call twice. For a read-only search this was invisible. For the actual production incident that motivated this record, the tool was a `filesystem.write` and the second execution clobbered a file the first execution had produced, with stale shard data. The trace, in order: - T0: stream open, session `S1`, capabilities negotiated, connection `C1` bound to `S1`. - T1: `tools/call` id=`42` dispatched; request table entry `{42: in_flight}` in `C1`-local dict. - T2: progress events 4470–4471 buffered. - T3: `C1` resets. `C1`-local request table freed. Event buffer for `S1` retained. - T4: reconnect `C2`, `Last-Event-ID: 4471`, session `S1`. Buffer replayed. **No request table reconstruction.** Server has no record that `42` is in flight. - T5: server's completion handler for the *original* execution of `42` fires, writes result to buffer at seq 4472. - T6: client receives 4472, closes `42`, considers call done. - T7: client reconnects again (`C3`) with `Last-Event-ID: 4471` (dedupe window expired). Server sees no in-flight `42`, no completed `42` in *connection* state, and — because the retry logic keyed on "request not present in current connection" — re-dispatches `42`. - T8: second execution completes with divergent result, appended at seq 4473. Duplicate terminal result for id `42`. Two invariants were violated. First: **the resumption token must not advance past a point where the server has lost the state required to honor requests issued before that point.** The token said "you have everything up to 4471," which was true for the event log and false for the request table. Second: **a JSON-RPC `id` must map to at most one terminal outcome per session, for the life of the session** — not for the life of the connection. ## Condition of Validity The replay-cursor interpretation of the resumption token is only valid under a precondition that is almost never stated: **the set of state required to service the stream is a subset of the state reconstructible from the event buffer.** For pure notification streams (log tailing, progress-only feeds) this holds. For any stream that carries request/response correlation — `tools/call`, `sampling/createMessage`, `roots/list` — it does not, because the request table is write-ahead state that is *not* an event and is not in the buffer. The invariant that makes the token safe is therefore: > A resumption token `T` is valid iff, for every request `r` issued at or before `T` that has not yet produced a terminal event in the buffer, the server can reconstruct `r`'s in-flight state from durable storage keyed by session, not by connection. If that cannot be guaranteed, the server must **not** honor the token for resumption of a session that had in-flight requests. It must instead fail the resume with a distinct, non-retryable error that forces the client to re-negotiate a fresh session — accepting the loss of in-flight work rather than silently duplicating it. The choice is between losing a request and executing it twice; for side-effecting tools, exactly-once-or-fail is the only defensible default. ## Decision Boundary The boundary is drawn on two axes: **does the session have in-flight requests at reconnect time**, and **are those requests idempotent**. - No in-flight requests, buffer intact → replay from token. Safe. This is the common case and the one the naive implementation was tuned for. - In-flight requests, all idempotent (read-only tools, pure queries) → replay from token, allow re-dispatch, dedupe by `id` on the client within a bounded window **longer than the server's buffer TTL**. Safe only if the client's dedupe window strictly exceeds the server's replay window; otherwise the T7 re-dispatch is reachable. - In-flight requests, any non-idempotent → **refuse resumption.** Return a session-invalid error. Force fresh negotiation. The token is not a license to resume; it is a hint that resumption *might* be possible, and the server is the authority on whether it is. The subtle part: the server cannot decide this from the token alone. It must consult the durable request table at resume time and compare it against the highest sequence number the token authorizes replaying. If any in-flight request's dispatch sequence is `<= T` and it has no terminal event `<= T` in the buffer, the token is *behind* the request table and resumption is unsafe. ## Operational Effect The guardrail is a single check at the resume entry point, before any replay bytes are written: reconcile the token against the durable request table and refuse if they disagree. Implementations that skip it are indistinguishable from correct ones under all-read-only workloads and under all clean-disconnect workloads — the failure only surfaces when a non-idempotent tool is in flight across a reconnect, which is precisely the case that is hardest to reproduce in test and most expensive in production. The secondary effect is on the client side: the dedupe window must be derived from the server's advertised buffer TTL, not chosen independently. A client that dedupes for 30 seconds against a server that buffers for 5 minutes will re-dispatch at T7 every time. The code below encodes the resume-time reconciliation as an explicit gate, raising on the unsafe boundary rather than degrading to silent replay. ```python from dataclasses import dataclass, field from typing import Optional class UnsafeResumptionError(RuntimeError): """Raised when a resumption token would replay past lost in-flight state.""" @dataclass class InFlightRequest: request_id: str dispatch_seq: int idempotent: bool terminal_seq: Optional[int] = None @dataclass class SessionState: session_id: str buffer_tail_seq: int requests: dict[str, InFlightRequest] = field(default_factory=dict) def reconcile_resumption( session: SessionState, last_event_id: int, client_dedupe_window_s: float, server_buffer_ttl_s: float, ) -> int: """ Validate a resume token against durable session state before replay. Returns the sequence number to replay from. Raises if unsafe. """ if last_event_id > session.buffer_tail_seq: raise UnsafeResumptionError( f"token {last_event_id} ahead of buffer tail {session.buffer_tail_seq}" ) if client_dedupe_window_s < server_buffer_ttl_s: raise UnsafeResumptionError( f"client dedupe {client_dedupe_window_s}s shorter than server " f"buffer TTL {server_buffer_ttl_s}s; re-dispatch reachable" ) for req in session.requests.values(): if req.dispatch_seq > last_event_id: continue # dispatched after the token; not yet replayed if req.terminal_seq is not None and req.terminal_seq <= last_event_id: continue # already delivered before the token; safe # In-flight at or before the token with no terminal event in range. if not req.idempotent: raise UnsafeResumptionError( f"non-idempotent request {req.request_id} in flight since " f"seq {req.dispatch_seq}, no terminal event <= {last_event_id}; " f"refusing resume, require fresh negotiation" ) # Idempotent: replay is safe, but caller must dedupe by id. return last_event_id + 1 def handle_resume(session: SessionState, last_event_id: int, **kw) -> int: try: return reconcile_resumption(session, last_event_id, **kw) except UnsafeResumptionError: # Surface as a non-retryable session-invalid to the client. session.requests.clear() raise ```