# Why does an instance lose its MCP session identity when a multiplexed HTTP stream resumes across a transport interruption **Date of Record:** 2026 November 24 **Scope:** Applies to MCP clients/servers that multiplex multiple logical sessions over HTTP long-lived streams (SSE/chunked) and advertise resumable delivery via `Last-Event-ID` replay. Does not apply to single-session stdio transports or to stateless one-shot request/response MCP calls with no per-session state. ## Core Distinction The failure is not "the connection dropped." Transport interruption is expected and recoverable. The failure is that **resumption restores the byte stream but not the session's identity binding**, because the two are keyed differently. The stream is resumable by `Last-Event-ID` (an event cursor), while the session is authenticated and authorized by a session token / `Mcp-Session-Id` header (an identity cursor). After an interruption, a client that reconnects with a valid `Last-Event-ID` but a *re-derived or stale* session identifier gets a stream that replays correctly against the wrong identity context. The server then rehydrates state under a session that either no longer exists, has been reaped, or belongs to a different logical client that reused the same cursor namespace. The invariant that must hold: **event cursor and session identity must be bound together in the replay store**. `Last-Event-ID` replay is only safe if the store can prove that the cursor being resumed was minted within the same session that is now presenting. Most implementations store the cursor as a bare monotonic counter per stream, not per session, so the binding is implicit and silently wrong on reconnect. ## What Was Observed A multiplexing gateway fronted N logical MCP sessions over a small pool of HTTP/2 streams. Each session had its own `Mcp-Session-Id`. Events were emitted with `id:` fields drawn from a gateway-global counter to keep ordering monotonic across interleaved sessions. Trace of the failure: 1. Session A (`S-A`) is streaming a long tool-call result. Gateway emits events with ids `1001..1050`. Client tracks `Last-Event-ID: 1050`. 2. Network partition. The HTTP/2 stream is reset. The server's session-reaper marks `S-A` idle after its keepalive TTL (e.g., 30s) and frees the session record, but the replay buffer keyed by event id is retained for a longer window (e.g., 5 min) to honor resumability. 3. Client reconnects. Its session token was in memory and survives, but its keepalive was also missed; a naive client re-issues `initialize` and receives a **new** `Mcp-Session-Id` (`S-A'`), then reconnects the stream with `Last-Event-ID: 1050`. 4. Gateway finds events `1051..` under cursor `1050` in the replay buffer — which was written by `S-A` — and delivers them to `S-A'`. The client now believes it is resuming its own stream; the server believes it is serving a fresh session. Tool results, partial state, and any server-issued capability tokens embedded in the replayed events are injected into `S-A'`. 5. If a *different* client `S-B` had coincidentally presented a cursor in the same global counter range, the replay could cross session boundaries entirely — a state-leak, not just a stale-state bug. The observable symptom is subtle: the resumed stream *looks* correct (ordered, gap-free from the client's view), but the session-scoped state machine on the server is at a different point than the event payload implies. Subsequent tool calls execute against `S-A'`'s initialized-but-empty context while the client reasons over `S-A`'s replayed history. Divergence compounds from there. ## Condition of Validity The replay-safety invariant holds only when all three conditions are true: - **Cursor namespacing:** event ids are scoped per session (e.g., `S-A:1050`), not drawn from a global counter, so a cursor cannot be resolved outside its minting session. - **Identity continuity:** the reconnect path reuses the original `Mcp-Session-Id` when it is still within its retention window, and the server rejects replay for a cursor whose session record has been reaped rather than silently serving it to a successor session. - **Atomic reap-vs-replay:** the session-reaper and the replay buffer share a single TTL, or the reaper tombstones the cursor range on reap so a late `Last-Event-ID` returns `410 Gone` instead of replaying orphaned events. If any condition is violated, resumption is not a recovery — it is a silent state transplant. The dangerous case is specifically the *mismatch* window: session reaped, replay buffer alive. That window is the entire bug. ## Decision Boundary On a reconnect carrying `Last-Event-ID`, the server must decide between three outcomes, and the choice is the whole guardrail: - **Resume in place** — only if `(session_id, cursor)` resolves to a live session record and the cursor was minted under that exact session. Serve `1051..` and keep the session. - **Reject and reinitialize** — if the session was reaped but the client presents the original id: return a terminal `session_expired` signal so the client discards replayed assumptions and starts clean. Never replay across the reap. - **Refuse** — if the cursor is unknown or belongs to a different session: `410 Gone`, no partial delivery. The boundary that must never be crossed: **serving replayed events to any session other than the one that minted the cursor.** A monotonic global counter makes this boundary invisible, which is why it fails silently. The decision must be made on the pair `(session_id, cursor)`, not on the cursor alone. ## Operational Effect Downstream, the mismatch manifests as reasoning divergence that is hard to attribute: the agent's context contains tool results it believes are its own, but the server's session state disagrees. Retries re-execute tools against the empty successor session, producing duplicate side effects while the client de-duplicates against replayed ids — so duplicate suppression and actual execution are keyed to different truths. Auditors replaying the event log see a coherent stream and cannot detect the identity split without cross-referencing session records, which are typically not in the replay log. The fix is structural, not a retry policy: bind cursor to session at mint time, tombstone cursors on session reap, and treat `(session_id, cursor)` as the sole resumability key. Anything weaker turns every transport interruption into a potential silent identity swap. ```python from dataclasses import dataclass from typing import Optional class SessionReplayMismatch(RuntimeError): """Raised when a resumable stream cursor cannot be safely bound to the presenting session.""" pass @dataclass(frozen=True) class Cursor: session_id: str seq: int def encode(self) -> str: return f"{self.session_id}:{self.seq}" @staticmethod def decode(raw: str) -> "Cursor": sid, _, seq = raw.rpartition(":") if not sid or not seq.isdigit(): raise SessionReplayMismatch(f"malformed Last-Event-ID {raw!r}") return Cursor(session_id=sid, seq=int(seq)) class ReplayStore: def __init__(self, session_ttl_events: int = 5000) -> None: self._events: dict[str, list[str]] = {} # session_id -> payloads self._reaped: set[str] = set() self._ttl = session_ttl_events def mint(self, session_id: str, payload: str) -> Cursor: if session_id in self._reaped: raise SessionReplayMismatch(f"session {session_id} reaped; cannot mint") buf = self._events.setdefault(session_id, []) buf.append(payload) return Cursor(session_id=session_id, seq=len(buf)) def reap(self, session_id: str) -> None: # Tombstone: keep the id so late cursors are refused, drop payloads. self._reaped.add(session_id) self._events.pop(session_id, None) def resume(self, presenting_session: str, last_event_id: Optional[str]) -> list[str]: if last_event_id is None: return [] cursor = Cursor.decode(last_event_id) # The invariant: cursor must belong to the session presenting it. if cursor.session_id != presenting_session: raise SessionReplayMismatch( f"cursor {cursor.encode()} minted by {cursor.session_id!r} " f"presented by {presenting_session!r}" ) if cursor.session_id in self._reaped: raise SessionReplayMismatch( f"session {cursor.session_id!r} reaped; refusing cross-reap replay" ) buf = self._events.get(cursor.session_id, []) if cursor.seq > len(buf): raise SessionReplayMismatch( f"cursor {cursor.encode()} beyond retained window {len(buf)}" ) return buf[cursor.seq:] def handle_reconnect(store: ReplayStore, session_id: str, last_event_id: Optional[str]) -> list[str]: try: return store.resume(session_id, last_event_id) except SessionReplayMismatch as exc: # Terminal: force client to reinitialize rather than transplant state. raise SessionReplayMismatch(f"reinitialize required: {exc}") from exc ```