# Which invariants prevent replay divergence when an MCP streamable-HTTP session resumes across a server-initiated SSE reconnection **Date of Record:** 2026 November 24 **Scope:** Applies to MCP servers and clients using the streamable-HTTP transport where the server pushes JSON-RPC notifications over a long-lived SSE channel keyed by `Mcp-Session-Id`, and the client resumes using `Last-Event-ID` after a mid-stream disconnect. Does not cover stdio transport, WebSocket transports, or stateless request/response MCP deployments. ## Core Distinction The failure is not "the SSE connection dropped." Disconnects are expected and cheap. The failure is that **the server's notion of session continuity and the client's notion of event continuity are keyed on two different identifiers that are not guaranteed to be monotonic together.** The client resumes with `Last-Event-ID` (an SSE-layer cursor). The server authorizes the resume against `Mcp-Session-Id` (a session-layer handle). Under normal operation these advance in lockstep. Under server-initiated reconnection—where the server tears down the SSE channel to rebalance, roll a worker, or drain a connection—the server may *reset the event-ID sequence* for the session while keeping the session ID valid. The client then sends `Last-Event-ID: 41` against a session whose event counter has restarted at 1. The server has no way to distinguish "client is ahead of me" from "client is desynchronized," and the two common recovery policies—replay-from-cursor or reject-and-restart—both produce silent divergence. The invariant that must hold is: **for a given `Mcp-Session-Id`, the mapping from `Last-Event-ID` to a position in the server's outbound notification log must be total, monotonic, and stable across server-initiated reconnections.** If any of those three properties fails, resumption is unsafe. ## What Was Observed A streamable-HTTP MCP server fronted by a load balancer with two backend workers. Sessions are pinned to workers via consistent hashing on `Mcp-Session-Id`. Each worker maintains, per session, an outbound queue of JSON-RPC notifications (progress updates, `notifications/tools/list_changed`, sampling requests) and assigns each a monotonically increasing `id:` field for SSE framing. Trigger sequence: 1. Client opens SSE via `GET /mcp` with `Mcp-Session-Id: S1`. Worker A begins emitting events with `id: 1, 2, 3, ...`. 2. Client processes through `id: 38` and calls a long-running tool. The tool emits progress notifications; client is at `id: 41` when the LB decides to drain Worker A (deploy, autoscale-down, or health-check flap). 3. Worker A closes the SSE stream with a normal `200` termination and no error. This is a *server-initiated* reconnection, not a network fault. 4. Client reconnects: `GET /mcp` with `Mcp-Session-Id: S1` and `Last-Event-ID: 41`. Consistent hashing now routes to Worker B, which has no in-memory state for `S1` and, per the spec's session semantics, either (a) restores `S1` from a shared store that was last checkpointed at event `id: 12`, or (b) treats `S1` as unknown and issues a fresh session. 5. In case (a), Worker B's event counter for `S1` resumes at `13`. It receives `Last-Event-ID: 41`, cannot find event 41, and—depending on implementation—either replays from 13 (duplicating 13–41, which the client already applied) or silently starts at 13 (dropping 42 onward that the client never saw, then re-emitting 13–41 as if new). 6. In case (b), the server issues `Mcp-Session-Id: S2`. The client, which believes it is resuming, now has in-flight tool calls and pending sampling requests bound to `S1` that will never receive responses. It has no protocol-level signal that `S1` is dead versus merely quiet. Observed client-side effects: duplicated `notifications/progress` for the same `progressToken` (benign if the client dedupes, corrupting if it accumulates), a `sampling/createMessage` request replayed twice and answered twice (the model is invoked twice, cost doubles, and the two completions race to update the same agent scratchpad), and in case (b), a tool call whose result arrives on a session the client has abandoned—the tool ran, side effects committed, but the agent never learns the outcome and re-invokes it. The load balancer is incidental. The same failure reproduces on a single worker if the server restarts its SSE handler for a session (e.g., to change heartbeats) and resets the per-session event counter, which is the natural implementation when the counter is a local variable rather than a durable sequence. ## Condition of Validity The replay-from-cursor recovery policy is valid **only if all of the following hold simultaneously**: - The `Last-Event-ID` namespace is scoped to the session and is *never reset* for the lifetime of that session, including across server-initiated reconnections, worker migrations, and process restarts that preserve the session. - The server retains (or can reconstruct) every event with `id > Last-Event-ID` that it has ever emitted for the session, or it can prove no such events exist (i.e., `Last-Event-ID` equals its high-water mark). - The session's existence is durable: if the server cannot honor `Mcp-Session-Id` on reconnect, it must return a distinguishable error (e.g., `404` with a session-expired body) rather than silently minting a new session or replaying from a lower cursor. If the event counter is reset on reconnection (common when the counter lives in the SSE handler's stack frame), condition 1 fails. If the outbound queue is bounded and old events are evicted, condition 2 fails whenever the client is more than the queue depth behind. If session state is checkpointed lazily, condition 3 fails at the checkpoint boundary. The subtle part: **none of these failures is detectable from the client side by inspecting the SSE stream alone.** A replayed event is syntactically identical to a fresh event. A reset counter produces a stream that looks perfectly monotonic from the client's perspective (it just restarts at a lower number than the client's cursor, which the client may not compare). The client cannot distinguish "resumed correctly" from "resumed from a rolled-back checkpoint" without an out-of-band signal. ## Decision Boundary The architectural invariant is: **the `Last-Event-ID` cursor and the `Mcp-Session-Id` must be advanced by the same durable write, and the server must reject any resume request whose cursor it cannot place exactly in its retained log.** Concretely, the server must, on every resume: - Look up the session durably. If absent → return an explicit session-gone error. Do not mint a new session under the same request; the client must re-initialize and re-issue any in-flight requests, because the server cannot know which side effects committed. - Compare `Last-Event-ID` against the session's retained log. Three cases: - Cursor is within the retained range → replay strictly events with `id > cursor`, in order, then continue live. - Cursor equals the high-water mark → continue live with no replay. This is the common case and must be distinguished from the rollback case. - Cursor is *greater* than the high-water mark → this is the divergence signal. It means the client saw events the server does not remember. The server must **fail the resume**, not clamp the cursor. Clamping is the silent-corruption path. - Never reset the per-session event counter. If the SSE handler is restarted, the counter is reloaded from durable state. If the counter must reset (e.g., session migration to a new storage epoch), the session ID must change with it, forcing re-initialization. The client-side invariant: **on any resume, treat a cursor greater than the server's acknowledged high-water mark, or a session-gone response, as a hard failure of in-flight operations, not a retryable blip.** In-flight tool calls and sampling requests must be marked indeterminate—the agent must not assume they failed (side effects may have committed) and must not assume they succeeded (results are lost). The correct recovery is to query the tool's idempotency key or effect log, or to surface the indeterminacy to the orchestrator. ## Operational Effect Without the invariant, the failure mode is **duplicate side effects that are individually well-formed and collectively inconsistent.** The agent does not crash; it produces a plausible but wrong trajectory: a sampling request answered twice yields two completions that both write to the scratchpad, and the final state depends on write ordering the agent never controlled. A tool re-invoked after a lost result doubles external effects (two emails, two charges) with no error surfaced. The divergence is invisible in per-event logs because every event is valid SSE with a valid JSON-RPC payload; it is only visible in the *cross-event* accounting of which `id`s the client applied versus which the server emitted. With the invariant, the failure is loud and bounded: the resume is rejected, the session is declared gone, in-flight operations are marked indeterminate, and the orchestrator decides whether to compensate. The cost is a full re-initialization on worker migration; the benefit is that the agent never acts on a state it cannot prove it holds. The load-bearing detail is that **the event counter must be part of the durable session record, not part of the connection handler.** Every implementation that stores the counter in the SSE handler's closure will pass every test that does not restart the handler mid-session, and will silently corrupt every session that crosses a server-initiated reconnection. The test that catches it is not a disconnect test—it is a *server-initiated close followed by resume* test, asserting that the resumed stream's first event has `id` strictly greater than the client's `Last-Event-ID`. ```python class SessionResumeDivergence(RuntimeError): """Raised when a streamable-HTTP MCP resume cannot be placed in the server's retained log.""" def resume_session( session_store, session_id: str, last_event_id: int, ) -> list[dict]: """Return events strictly after last_event_id, or raise if the cursor is unplaceable. Invariants enforced: 1. Session must exist durably; we never mint a replacement here. 2. last_event_id must be <= the session's high-water mark. A cursor ahead of the server means the client applied events we no longer remember; clamping would silently drop or duplicate notifications. 3. The retained log must cover (last_event_id, high_water] without gaps. """ session = session_store.get(session_id) if session is None: raise SessionResumeDivergence( f"session {session_id!r} not found; client must re-initialize, " f"in-flight operations are indeterminate" ) high_water = session.high_water_event_id if last_event_id > high_water: # The divergence signal. Do NOT clamp to high_water. raise SessionResumeDivergence( f"session {session_id!r}: client cursor {last_event_id} exceeds " f"server high-water {high_water}; event log was rolled back or " f"reset across a server-initiated reconnection" ) if last_event_id == high_water: return [] # clean live resume, no replay retained_start = session.retained_log[0].event_id if session.retained_log else high_water + 1 if last_event_id + 1 < retained_start: raise SessionResumeDivergence( f"session {session_id!r}: events {last_event_id + 1}..{retained_start - 1} " f"evicted from retained log; cannot replay without a gap" ) return [ ev.payload for ev in session.retained_log if last_event_id < ev.event_id <= high_water ] ```