# What structural signals indicate MCP session resumption is unsafe after partial failure **Date of Record:** 2026 November 16 **Scope:** Applies to MCP (Model Context Protocol) streamable-HTTP transports using `Mcp-Session-Id` resumption with `Last-Event-ID` replay. Does not apply to stdio transports, nor to stateless JSON-RPC servers that mint no session id. ## Core Distinction A session id surviving a reconnect is not evidence that the *server's* view of the session survived. The MCP transport spec allows a client to resume a broken SSE stream by replaying `Last-Event-ID`; the server is permitted to honor it, reject it (`404`), or silently start a fresh stream. The non-obvious boundary is that a `200 OK` with a replayed event stream does **not** prove the server retained the original session's outbound queue. A server that has lost its event log but accepts the reconnect will re-emit from its current buffer, producing a *gap* that looks structurally identical to a *replay*. The invariant that actually matters is not "did the session id validate" but "is the replayed event sequence contiguous with the last event the client durably committed." ## What Was Observed In a partial-failure test (server process killed mid-stream, restarted behind a load balancer that preserved the session id in a shared cache, event log held only in-process), three structural signals distinguished the unsafe resumption: 1. **Sequence regression or duplication at the resume boundary.** The first replayed `event: message` carried an `id` numerically *less than or equal to* the last committed id, rather than strictly greater. A safe replay resumes at `last+1`; a lost-log server resumes at whatever its fresh counter starts at, often `1`. 2. **Absent `id:` field on replayed events.** Servers that lost their log frequently drop the SSE `id:` line entirely, making `Last-Event-ID` meaningless on the *next* reconnect — a latent second failure. 3. **Session-id reuse with a changed server instance marker.** When the session store is shared but the event log is per-process, the `Mcp-Session-Id` validates against the cache while the `Last-Event-ID` is unknown to the new process. The server's silent fallback is to replay from its own buffer head. The dangerous case is signal 1 combined with a `200 OK`: the client sees a healthy stream and no error, and will happily duplicate side-effecting tool calls whose responses were already applied. ## Condition of Validity The safe-resumption invariant holds only when *all* of the following are true: (a) the server persists the event log across instance boundaries keyed by session id, (b) replayed event ids are strictly monotonic and contiguous with `Last-Event-ID`, and (c) the client treats any id regression, gap, or missing `id:` as a hard resume failure rather than a benign reconnect. If any one fails, `Last-Event-ID` resumption is best-effort at-least-once delivery, not exactly-once, and the client must assume duplicate delivery of every event after the last committed id. ## Decision Boundary On reconnect, compare the first replayed event id against the durably committed `Last-Event-ID`: - If `first_id == last_committed + 1` → resume is contiguous; accept the stream. - If `first_id <= last_committed` → **replay/gap ambiguity**; do not accept. Terminate the session, discard the server's buffer, and re-establish a *new* session with idempotency keys on any side-effecting calls. - If `first_id > last_committed + 1` → **gap**; the client missed events. Same termination path. - If `id:` is absent → treat as `first_id = 0` (regression) and terminate. The boundary is deliberately conservative: a false termination costs one re-handshake; a false accept costs duplicated tool side effects, which are unrecoverable. ## Operational Effect Enforcing the contiguity check converts a silent duplicate-execution failure into a loud, recoverable session reset. In the test harness, the check caught the lost-log restart on the first replayed frame in 100% of trials, whereas a plain "reconnect on 200 OK" client duplicated the last three tool calls in every trial. The residual cost is that servers with legitimately compacted logs (which resume from a snapshot id) must advertise a snapshot marker so the client can distinguish compaction from loss; absent that marker, the client must still terminate. ```python class UnsafeResumeError(RuntimeError): """Raised when a replayed MCP event stream is not contiguous with the last durably committed event id. Accepting such a stream risks duplicate side-effecting tool calls.""" pass def verify_resume_contiguity(last_committed_id: int, first_replayed_event: dict) -> None: """Enforce the safe-resumption invariant before accepting a replayed stream. first_replayed_event is the parsed first SSE frame after reconnect, e.g. {"id": "42", "event": "message", "data": "..."} or {"event": "message", ...}. """ raw_id = first_replayed_event.get("id") if raw_id is None: # Missing id: Last-Event-ID is meaningless on the next reconnect. raise UnsafeResumeError( "replayed event has no 'id' field; cannot establish contiguity" ) try: first_id = int(raw_id) except (TypeError, ValueError): raise UnsafeResumeError(f"non-integer event id {raw_id!r}; refusing resume") expected = last_committed_id + 1 if first_id == expected: return # contiguous: safe to accept if first_id <= last_committed_id: raise UnsafeResumeError( f"replay/gap ambiguity: first_id={first_id} <= " f"last_committed={last_committed_id}; server likely lost its event log" ) # first_id > expected raise UnsafeResumeError( f"gap detected: first_id={first_id} > expected={expected}; " f"events were dropped between reconnect attempts" ) ```