# Which invariants prevent silent event loss when an MCP streamable-HTTP session resumes across a renegotiated transport **Date of Record:** 2026 November 24 **Scope:** Applies to MCP servers and clients using the streamable-HTTP transport where a session is established via `Mcp-Session-Id`, an SSE stream is opened for server→client notifications, and resumption is attempted via `Last-Event-ID` after a disconnect. Does not cover stdio transport, nor pure request/response MCP usage with no server-initiated stream. ## Core Distinction The failure is not "the client reconnected and missed a message." It is subtler: the client reconnected, *successfully negotiated a new stream*, and the server accepted `Last-Event-ID` — yet the two sides disagree about **which session the resumed stream belongs to**. Streamable HTTP lets a client reinitialize a transport (new SSE `GET`, possibly a fresh `Mcp-Session-Id` if the server expired the old one) while still presenting a `Last-Event-ID` from the *previous* session's event space. The server has two independent, individually-valid pieces of state — a session identity and a resumption cursor — that are only meaningful *jointly*. When the session was reaped or rotated, the cursor refers to an event ID namespace that no longer exists, and the server's correct-looking behavior (accept the header, replay nothing, open a live stream) produces silent, unrecoverable loss of every notification emitted during the gap. The invariant that must hold: **an event ID is valid only within the session that issued it, and a resumed stream MUST be bound to the same session that minted the cursor, or the resumption MUST be rejected as a hard error — never silently downgraded to a fresh stream.** ## What Was Observed A long-running agent held an MCP session against a tool server that pushed progress notifications (partial results from a slow `run_query` tool) over an SSE stream. The server enforced a 300-second idle-session TTL; the client's keepalive was a 60-second SSE comment (`:ping`). Under normal load the ping kept the session alive. During a GC pause on the server host, the reaper ran late but still ran: it evicted the session record at T+340s and, on eviction, **rotated the event-ID counter** because the new session was allocated a fresh monotonic namespace. The client's SSE connection had dropped at T+310s (network blip). It reconnected at T+330s — *before* the reaper fired — presenting `Last-Event-ID: 4471` and the old `Mcp-Session-Id`. The server, still holding the session, replayed correctly and resumed. Fine. But a second blip at T+360s, *after* eviction, triggered the pathological path: 1. Client opened `GET /mcp` with `Mcp-Session-Id: S1` and `Last-Event-ID: 4471`. 2. Server found `S1` absent (reaped). Per the spec's session-termination semantics it returned `404`, which the client interpreted as "session gone, reinitialize." 3. Client sent `initialize`, received `Mcp-Session-Id: S2`, and — **reusing its cached resumption cursor** — reissued the SSE `GET` with `Last-Event-ID: 4471` against `S2`. 4. `S2`'s event namespace started at 1. The server's replay logic looked for event `4471`, found nothing, and (correctly per its own implementation, incorrectly per the invariant) opened a *live-only* stream at the current head. 5. Every notification emitted between the last delivered event on `S1` and the head of `S2` — including three `progress` and one terminal `result` — was never delivered. The agent's `run_query` call hung until its own 900s timeout, then reported a spurious timeout failure. The tell was in the logs: a `200 OK` SSE stream with `id:` values beginning at `1`, immediately after a request carrying `Last-Event-ID: 4471`. A monotonic cursor *decreasing* across a resume is the fingerprint of cross-session cursor reuse. ## Condition of Validity The silent-loss path requires all of the following to hold simultaneously; remove any one and the failure is bounded: - **Session reaping is independent of cursor validity.** The server's session store and its event-log store have separate lifecycles, so a cursor can outlive the session that scoped it. - **The client caches `Last-Event-ID` across `initialize`.** This is the load-bearing mistake: the cursor is treated as a property of the *connection* rather than of the *session*. A spec-conformant client resets its cursor to empty on any new `Mcp-Session-Id`. - **The server treats an unknown `Last-Event-ID` as "resume from head" rather than "reject."** Replay-from-head-on-miss is the silent-loss enabler. Rejecting with `400` and a machine-readable reason converts silent loss into a visible, recoverable error. - **Event IDs are not globally unique or session-namespaced.** If IDs were `S1:4471` / `S2:1`, the server would detect the mismatch on the first comparison. Conversely, the invariant *holds* (no silent loss) when the server either (a) rejects any `Last-Event-ID` whose session prefix does not match the presented `Mcp-Session-Id`, or (b) the client clears its cursor on session rotation. Either alone is sufficient; both together are the robust configuration. ## Decision Boundary The boundary is a single branch in the server's SSE handler, evaluated *after* session lookup and *before* stream establishment: - **If `Last-Event-ID` is absent** → fresh stream from head. Always valid. - **If `Last-Event-ID` present and its namespace matches the resolved session** → replay from cursor, then live. Valid. - **If `Last-Event-ID` present but its namespace does not match the resolved session** → this is the boundary. The two admissible resolutions are **reject (`400`, resumability-not-possible)** or **replay-from-head with an explicit `X-Resume-Reset: true` marker the client MUST honor by re-fetching full state**. Opening a silent live-only stream is *not* admissible — it violates the invariant that a cursor either delivers everything after it or fails loudly. The client-side mirror boundary: on receiving a new `Mcp-Session-Id` from `initialize`, the client MUST zero its `Last-Event-ID`. A client that carries the cursor forward has crossed the boundary into cross-session reuse regardless of server behavior. ## Operational Effect The practical consequence is that **resumability is only as strong as the binding between cursor and session**, and that binding is not carried by either header alone. Two independent, individually-correct subsystems — session lifecycle and event-log replay — compose into a silent data-loss bug at their seam. The agent experiences this as a *hang-then-timeout*, not as an error, because the transport layer reports success. This is the worst failure class for autonomous agents: no exception, no retry trigger, just a missing terminal event and a downstream timeout attributed to the wrong layer. Guardrails, in order of strength: (1) namespace event IDs with the session ID so mismatch is structurally detectable; (2) reject unknown/mismatched cursors with an explicit resumability error rather than degrading to live-only; (3) have clients reset cursors on session rotation and treat `404` on the stream `GET` as "reinitialize *and* discard cursor." Deploy (1) and (2) on the server; (3) on the client. Any one of the three bounds the loss to a visible error; all three eliminate it. ```python import re from dataclasses import dataclass class ResumeCursorMismatch(RuntimeError): """Raised when a Last-Event-ID cannot be honored against the resolved session.""" pass @dataclass(frozen=True) class Session: session_id: str event_head: int # next event id to mint, namespaced as f"{session_id}:{n}" _EVENT_ID_RE = re.compile(r"^(?P[^:]+):(?P\d+)$") def resolve_stream(session: Session | None, last_event_id: str | None) -> dict: """Decide how to open an SSE stream for an MCP streamable-HTTP GET. Enforces the invariant: a cursor is valid only within the session that minted it. A mismatched or unknown cursor is a hard error, never a silent downgrade to a live-only stream. """ if session is None: # No resolvable session: caller must reinitialize; do NOT accept a cursor. if last_event_id is not None: raise ResumeCursorMismatch( f"Last-Event-ID={last_event_id!r} presented with no live session; " "client must discard cursor on reinitialize" ) return {"mode": "fresh", "replay_from": None} if last_event_id is None: return {"mode": "fresh", "replay_from": None} m = _EVENT_ID_RE.match(last_event_id) if not m: raise ResumeCursorMismatch( f"malformed Last-Event-ID={last_event_id!r}; expected ':'" ) cursor_sid = m.group("sid") if cursor_sid != session.session_id: # The cross-session reuse path: cursor minted by a different session. raise ResumeCursorMismatch( f"Last-Event-ID namespace {cursor_sid!r} does not match resolved " f"session {session.session_id!r}; refusing silent live-only resume" ) seq = int(m.group("seq")) if seq >= session.event_head: raise ResumeCursorMismatch( f"cursor seq {seq} ahead of session head {session.event_head}; " "state divergence, refusing to resume" ) return {"mode": "resume", "replay_from": seq, "session": session.session_id} ```