# Which invariants prevent SSE resumption corruption when an MCP server migrates a session from streamable HTTP to a resumed event stream mid-tool-call **Date of Record:** 2026 November 30 **Scope:** Applies to MCP servers implementing the HTTP-native transport (Streamable HTTP with optional SSE upgrade) where a client may reconnect with `Last-Event-ID` after a dropped connection while a tool call is in flight. Does not cover stdio transport, nor pure legacy HTTP+SSE servers that never expose `Mcp-Session-Id` resumption semantics. ## Core Distinction The distinction that matters is between **transport-level replay** and **execution-level replay**. Streamable HTTP gives you a resumption primitive: a client that loses its connection can reissue its request with `Last-Event-ID: ` and the server is expected to resume the event stream from that point. What the spec does *not* give you is a guarantee that the events between the last delivered ID and the reconnect correspond to a single, coherent, still-running tool invocation. Those are two different invariants, and conflating them is where sessions corrupt. The subtle part: a JSON-RPC response for a `tools/call` is a *single* message. When the server streams progress notifications (`notifications/progress`) followed by the terminal `result`, the resumption boundary can fall *between* a progress notification and its result. If the server treats resumption as "replay events after ID N," but the tool executor has already advanced past the point that generated those events, the replayed tail describes a state the executor no longer occupies. The client reconstructs a coherent-looking narrative from incoherent facts. ## What Was Observed A server exposing `search_index` as a long-running tool (30–90s) streamed the following over SSE during a single `tools/call`: ``` id: 41 event: message data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"tk-9","progress":30,"total":100}} id: 42 event: message data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"tk-9","progress":60,"total":100}} ``` The client TCP connection dropped after delivering `id: 42`. The client reconnected per spec with `Last-Event-ID: 42` and the same `Mcp-Session-Id`. The server, whose executor had meanwhile completed the call and written the terminal result into a per-session ring buffer, replayed: ``` id: 43 event: message data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"tk-9","progress":90,"total":100}} id: 44 event: message data: {"jsonrpc":"2.0","id":7,"result":{"content":[{"type":"text","text":"…"}]}} ``` This looks correct. It is not, in two configurations we observed: 1. **Duplicate terminal replay.** The server's ring buffer retained the terminal `id: 44` message, but the executor had also, on the *original* connection, attempted to flush `id: 44` before the drop was detected at the socket layer. The client had received `id: 44` on the dying socket (kernel delivered it, application read it, then reconnect fired). On resume it received `id: 44` *again*. The client's JSON-RPC layer, keyed only on `id: 7`, delivered the `tools/call` result twice to the agent loop. The agent, treating each result as authoritative, appended the same tool output to its context twice and re-invoked a dependent tool. 2. **Progress-token resurrection.** After `id: 43`, the executor had already transitioned the tool to a *second* phase with a new `progressToken` (`tk-10`). The replay only covered `tk-9` events because the ring buffer was segmented by token, not by session. The client saw `tk-9` progress reach 90 and then a terminal result, concluded the call completed at 90% of a phase that was actually still at 0% of its successor, and fired a dependent `tools/call` against a partially-populated index. Neither failure is a "bug" in the sense of a crash. Both are direct consequences of the server treating `Last-Event-ID` as a *buffer cursor* rather than as a *causal checkpoint*. ## Condition of Validity The invariant that makes resumption safe is: > **For any `Mcp-Session-Id`, the tuple (last-delivered-event-id, terminal-jsonrpc-id) must be monotonic and at-most-once across all connections in the session's lifetime, and the event stream after any `Last-Event-ID` must be a *prefix-consistent* suffix of the single canonical event sequence for that session.** Three clauses, each independently violable: - **Monotonic:** event IDs never decrease across reconnects. Trivially violated if the server assigns IDs per-connection rather than per-session. - **At-most-once terminal delivery:** a JSON-RPC response with a given `id` is delivered to the client layer exactly once, regardless of how many connections observe it. This requires the client to dedupe on `(session_id, jsonrpc_id)` — the spec is silent on this, and most clients do not. - **Prefix-consistent suffix:** the events replayed after `Last-Event-ID: N` are exactly the events with ID > N in the canonical sequence, with no gaps and no reordering. This is violated the moment the server's buffer is segmented by anything other than the session (token, phase, tool name). The condition of validity, stated operationally: **resumption is safe only if the server can prove, at reconnect time, that every event with ID ≤ N was delivered and acknowledged, and every event with ID > N is still in the canonical sequence.** Where "acknowledged" means the client's TCP stack confirmed receipt — which HTTP gives you only via the connection staying open past the write, and SSE gives you not at all. ## Decision Boundary The boundary is drawn at the point where the server must choose between two resumption strategies: - **Replay-from-buffer:** re-emit every buffered event with ID > `Last-Event-ID`. Cheap, stateless-ish, and *unsafe* whenever the executor has advanced past the replayed events' generating state. This is the default in most MCP server SDKs because it is the obvious reading of the spec. - **Replay-from-checkpoint:** re-emit only events whose generating state is still valid, and if the executor has advanced, emit a synthetic `notifications/progress` describing the *current* state (with a fresh ID) followed by the terminal result — dropping the stale intermediate events. This requires the executor to expose a "current state" query and the server to know which events are stale. The decision rule: **if the tool executor is not idempotent-replayable — i.e., if re-running the tool from the last delivered event would produce a different result than continuing it — replay-from-buffer is forbidden.** For a `search_index` that streams progress over a mutable index, replay-from-buffer is forbidden. For a `read_file` that streams bytes, replay-from-buffer is safe because the byte stream is a pure function of the file at open time. The boundary is *not* "long-running vs short-running." It is "side-effecting vs pure." A 2ms `write_record` call that drops between request-write and response-read has the same resumption hazard as a 90s streaming search, because the client cannot tell whether the write landed. ## Operational Effect The operational consequence for agent systems is that **the agent loop must treat tool results as at-least-once, not exactly-once, across transport reconnects.** This is the opposite of what the JSON-RPC `id` field suggests. Every MCP client that resumes a session must carry a dedupe set keyed on `(session_id, jsonrpc_id)` and must discard duplicate terminal results *before* appending to context. Without this, the failure mode is silent context duplication — the agent's reasoning diverges because it believes a tool ran twice, or because it sees a progress notification that describes a phase it has already left. The second operational effect: **`progressToken` is not a phase identifier.** A tool that transitions phases must emit a terminal `notifications/progress` for the old token (with `progress == total`) before emitting the first event for the new token, and the server's resumption buffer must be keyed on session, not token. Otherwise a resumed client sees an unterminated progress stream and waits — or, worse, treats the terminal result as belonging to the old phase. The guardrail: **servers must expose a resumption capability flag in the initialize handshake** (e.g., `capabilities.experimental.resumption: "checkpoint" | "buffer"`), and clients must refuse to resume against `"buffer"` servers for any tool declared side-effecting. This is not in the spec. It should be. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Literal class ResumptionInvariantViolation(RuntimeError): """Raised when an MCP streamable-HTTP resumption would corrupt session state.""" @dataclass(frozen=True) class Event: event_id: int jsonrpc_id: int | None kind: Literal["progress", "result", "error"] progress_token: str | None = None @dataclass class SessionBuffer: session_id: str events: list[Event] = field(default_factory=list) delivered_terminal: set[int] = field(default_factory=set) # jsonrpc_ids already sent resumption_mode: Literal["buffer", "checkpoint"] = "buffer" def resume(self, last_event_id: int, side_effecting_tool: bool) -> list[Event]: if side_effecting_tool and self.resumption_mode == "buffer": raise ResumptionInvariantViolation( f"session {self.session_id}: replay-from-buffer forbidden for " f"side-effecting tool; executor state may have advanced past " f"event {last_event_id}" ) tail = [e for e in self.events if e.event_id > last_event_id] # At-most-once terminal delivery: drop any terminal event whose # jsonrpc_id was already delivered on a prior connection. deduped: list[Event] = [] for e in tail: if e.kind in ("result", "error") and e.jsonrpc_id is not None: if e.jsonrpc_id in self.delivered_terminal: continue self.delivered_terminal.add(e.jsonrpc_id) deduped.append(e) # Prefix-consistency: IDs in the replayed suffix must be contiguous # and strictly increasing. for prev, cur in zip(deduped, deduped[1:]): if cur.event_id != prev.event_id + 1: raise ResumptionInvariantViolation( f"session {self.session_id}: non-contiguous replay " f"({prev.event_id} -> {cur.event_id}); buffer segmented " f"by token or phase, not by session" ) # Progress-token termination: if the last delivered event was a # progress event for token T, the replayed suffix must either # terminate T or not reference it at all. if tail and tail[0].kind == "progress": last_delivered_token = self._token_at(last_event_id) if last_delivered_token and tail[0].progress_token == last_delivered_token: # Resume mid-phase is fine; resume that skips the terminal # progress for T is not. if not any( e.kind == "progress" and e.progress_token == last_delivered_token and e.progress_token is not None for e in deduped ): raise ResumptionInvariantViolation( f"session {self.session_id}: resumed into token " f"{last_delivered_token} without termination event; " f"client will observe unterminated progress stream" ) return deduped def _token_at(self, event_id: int) -> str | None: for e in self.events: if e.event_id == event_id: return e.progress_token return None ```