# Why does an instance lose its MCP session when the server-initiated SSE stream reconnects after a mid-stream `Last-Event-ID` gap **Date of Record:** 2026 November 26 **Scope:** Applies to MCP clients using the HTTP-native Streamable HTTP transport where the server pushes server-initiated messages over an SSE stream and the client resumes via `Last-Event-ID`. Does not apply to stdio transport, nor to plain request/response tool calls that never open a long-lived server stream. ## Core Distinction The failure is not "the connection dropped." A dropped SSE connection is recoverable by design: the transport spec says the client reconnects to the same session endpoint and sends `Last-Event-ID: `, and the server replays buffered events after that id. The boundary that actually breaks is the **event-id continuity invariant across a server-side buffer eviction**, which is a *different* failure than a transport drop and produces a *different* symptom: the client resubscribes successfully, receives `200 OK`, and silently loses one or more server-initiated messages with no error on either side. Concretely: the client's context now diverges from the server's authoritative view of the session, but every protocol-level signal says the session is healthy. This is the dangerous case. A connection error is loud; a lost event behind a successful reconnect is silent. ## What Was Observed Trace of a real divergence (session `sess_7f2`, server buffer cap 256 events, TTL 60s): 1. Client opens `GET /mcp` with `Mcp-Session-Id: sess_7f2`. Server assigns monotonically increasing event ids `1..N`. 2. Client has consumed through `id=1041`. Server buffer holds ids `786..1041` (256 events). 3. Network partition for 90 seconds. During the partition the server emits events `1042..1310` (269 events). Because the buffer is capped at 256 and TTL is 60s, ids `1042..1054` are evicted. The buffer now starts at `1055`. 4. Client reconnects: `GET /mcp` with `Last-Event-ID: 1041`. 5. Server sees `1041 < buffer_head (1055)`. It cannot replay `1042..1054`. A conforming-but-permissive server either (a) replays `1055..1310` and hopes the client doesn't notice the gap, or (b) returns `200` with an empty replay then continues live from `1311`. 6. Client receives `1055` (or `1311`) and — because SSE does not mandate gap detection — accepts it. The 13 events in `1042..1054` are gone. If any of them was a `notifications/tools/list_changed` or a server-initiated `sampling/createMessage` request, the client's state is now wrong in a way no subsequent message corrects. The tell: `last_seen_id + 1 != first_replayed_id`. Nothing in the transport layer forces the client to check this. The invariant is *implicit* and the transport relies on the application to enforce it. ## Condition of Validity The silent-loss failure requires all of: - A server-initiated SSE stream (not just request/response), so events exist that the client did not solicit. - A bounded server-side replay buffer with eviction (cap or TTL). Unbounded buffers make the gap impossible but are not viable for long sessions. - A disconnect long enough to exceed the buffer window. Short reconnects replay cleanly and mask the bug. - A client that does not verify `Last-Event-ID` continuity — i.e., trusts `200 OK` as proof of no loss. If the reconnect happens within the buffer window, the bug is invisible. This is why it survives testing: the failure only manifests under partition durations that exceed the eviction policy, which test suites rarely exercise. ## Decision Boundary On reconnect, the client must choose between two behaviors based on a single check: **is the first replayed event id exactly `last_seen_id + 1`?** - **Equal → resume.** Apply replayed events, continue live. Session continuity holds. - **Greater → gap detected.** The buffer evicted events the client never saw. The session is *not* resumable. The client MUST NOT continue as if it were. The boundary is sharp and cheap to evaluate, but only if the client tracks `last_seen_id` durably across the disconnect — not in memory that the reconnect path resets. If `last_seen_id` is lost on reconnect (common when the reconnect is handled by a fresh transport object), the check cannot run and the gap passes silently. The invariant to enforce: **`last_seen_id` is part of session state, not connection state.** When a gap is detected, the only sound recovery is to abandon the stream session and re-establish state through a non-streaming path: re-fetch the authoritative resource (e.g., re-list tools, re-read the resource the stream was mutating) and treat the server as the source of truth. Do not attempt to "fill in" the gap — the evicted events are unrecoverable by definition. ## Operational Effect A client that enforces the continuity check converts a silent divergence into a loud, recoverable fault. A client that does not will, under long partitions, operate on stale tool lists, miss server-initiated sampling requests, and — worst — continue a multi-step agent loop whose intermediate state was carried in a lost event. The agent does not know it is wrong; it has a `200 OK` and a live stream. The failure surfaces much later as a tool-call error against a capability the server already revoked, or as a duplicated side effect from a request the client never saw acknowledged. The guardrail is not retry logic. It is a single integer comparison at the reconnect seam, plus the discipline to keep that integer in session state rather than connection state. ```python class StreamResumeGapError(RuntimeError): """Raised when a server-initiated SSE replay skips event ids, indicating the server buffer evicted messages the client never received. The session cannot be resumed; state must be re-synchronized from the server.""" def resume_stream(session_id: str, last_seen_id: int, replayed_ids: list[int]) -> int: """Validate continuity of a resumed server-initiated stream. Returns the new last_seen_id on success. Raises StreamResumeGapError if the first replayed id is not exactly last_seen_id + 1, meaning one or more events were evicted from the server buffer and are unrecoverable. """ if not replayed_ids: # Empty replay is legal (server may have nothing buffered); continuity # is unprovable but no gap is observed. Caller continues live. return last_seen_id first = replayed_ids[0] expected = last_seen_id + 1 if first == expected: return replayed_ids[-1] if first > expected: # Gap: ids [expected, first) were never delivered. Silent-loss case. raise StreamResumeGapError( f"session {session_id}: replay starts at {first} but last seen was " f"{last_seen_id}; events [{expected}, {first}) evicted by server " f"buffer. Stream not resumable — re-sync state from server." ) # first < expected: server replayed already-consumed events (idempotent # replay). Safe to skip to last_seen_id, then continue. return last_seen_id ```