# How does an instance detect a lost MCP streamable-HTTP session when SSE reconnection succeeds at the transport layer but the server-side event cursor has already been garbage-collected **Date of Record:** 2026 November 21 **Scope:** Applies to MCP clients using the streamable HTTP transport with server-initiated SSE streams and `Last-Event-ID`-based resumption, where the server maintains a bounded per-session event replay buffer. Does not apply to stdio transport, nor to stateless HTTP servers that never emit `id:` fields on SSE events. ## Core Distinction There are two independent notions of "the session is alive" in streamable MCP-over-HTTP, and they diverge silently: 1. **Transport liveness** — the TCP/HTTP connection to the SSE endpoint re-establishes, the server returns `200 OK` with `Content-Type: text/event-stream`, and bytes flow again. From the client's socket layer, reconnection *succeeded*. 2. **Logical session continuity** — the server still holds the session's state (pending server→client requests, in-flight tool-call results awaiting delivery, the monotonic event cursor) and can replay every event the client has not yet acknowledged. The failure mode is that (1) can be true while (2) is false. When a client reconnects with `Last-Event-ID: N` and the server's replay buffer has already evicted event `N` (bounded ring buffer, TTL expiry, or session eviction after idle), a compliant server may still accept the connection and simply resume the live stream *from the current head* — emitting new events with IDs `M, M+1, ...` where `M ≫ N+1`. The client sees a healthy stream and a gap it never detects, because SSE itself has no gap-detection primitive. The events between `N+1` and `M-1` — which may include the `result` for a tool call the agent is blocked on, or a `notifications/cancelled` that would have aborted a stale task — are gone permanently. ## What Was Observed A long-running agent (call it the *executor*) invoked a tool via `tools/call` whose execution the server deferred to a server-initiated request back to the client (sampling or elicitation). Mid-execution the client's network path flapped for ~40 s. The client's SSE consumer reconnected with `Last-Event-ID: 1187`. The server had, during the outage, evicted its replay ring (capacity 256, ~9 s of burst traffic at peak) and rotated the session cursor to `1402`. The server accepted the reconnect and began streaming from `1402`. Trace of the state transition: - `t0`: client sends `tools/call` id=`c-91`, opens SSE, last seen event `1187`. - `t0+2s`: server emits `id:1188..1201` (progress notifications), then the deferred `sampling/createMessage` as `id:1202`. Client has not yet consumed `1202` when the link drops. - `t0+2s..t0+42s`: outage. Server continues emitting progress and eventually the `result` for `c-91` as `id:1401`, then evicts `1188..1200` from the ring. Cursor head = `1402`. - `t0+42s`: client reconnects, `Last-Event-ID: 1187`. Server's buffer floor is `1201`. The server cannot replay `1188..1200` and — critically — does not signal this. It sets the stream position to head and emits `id:1402+`. - `t0+43s`: client receives `1402` (unrelated notification). Its local `lastEventId` jumps `1187 → 1402`. The `result` for `c-91` (event `1401`) is never delivered. The executor blocks on `c-91` until its own request timeout fires — or, worse, indefinitely if it has no per-call deadline, since the transport keeps looking healthy. The invariant that broke: **a successful SSE reconnect does not imply the client's event cursor is contiguous with the server's.** The client had no way to distinguish "server had nothing to say between 1187 and 1402" from "server said 214 things you'll never see." A second, subtler variant: some servers, on cursor miss, return `404`/`410` on the reconnect to force a fresh session. That is *safer* — it fails loudly — but it destroys all session state including unrelated pending requests, forcing a full re-handshake. The dangerous case is the server that silently re-heads the stream, which is legal under the SSE spec (the spec says nothing about replay guarantees) and common in practice. ## Condition of Validity The silent-gap failure is only possible when all of the following hold simultaneously: - The server uses a **bounded** replay buffer (ring, TTL, or size cap) rather than unbounded or durable event log. - The server treats `Last-Event-ID` as a *hint* rather than a *contract*, i.e., it does not reject reconnects whose cursor predates the buffer floor. - The client does not independently track expected response IDs and cannot correlate "I sent `c-91`, I never got a matching `result`" against stream health. - The gap window contains at least one event the client is *semantically dependent* on (a `result`, a `cancelled`, an error) rather than only fire-and-forget progress notifications. If the server rejects out-of-window cursors with a distinct status code, or if the client maintains its own outstanding-request ledger with deadlines, the failure is bounded. The invariant to enforce is: **contiguity of `Last-Event-ID` must be verifiable, not assumed.** ## Decision Boundary The client must choose between two policies at reconnect time, and the choice is not free: - **Optimistic resume** (send `Last-Event-ID`, accept whatever head the server returns): low latency, but silently loses events on cursor miss. Acceptable only when all in-flight requests carry independent client-side deadlines *and* all server→client requests are idempotently re-requestable. - **Contiguity-checked resume**: after reconnect, the client verifies that the first event ID received is exactly `lastEventId + 1` (or that the server explicitly signals a head-jump via a sentinel event or a `X-MCP-Stream-Gap`-style header). If `firstReceivedId > lastEventId + 1`, the client MUST treat the session as logically broken: fail all outstanding requests with a resumption-gap error, and either re-initialize the session or re-issue the affected calls. The boundary condition is `firstReceivedId == lastEventId + 1`. Equality means contiguous (safe). Any strict inequality means a gap. The client cannot rely on the *absence* of events to mean *nothing happened*. The server-side counterpart invariant: a server that cannot honor `Last-Event-ID` MUST NOT silently re-head. It must either (a) reject with a resumption-specific error so the client can re-handshake, or (b) emit an explicit gap marker event before resuming. Silence is the defect. ## Operational Effect An agent that does not enforce the contiguity invariant exhibits a characteristic pathology: it appears healthy (stream up, heartbeats flowing) while being *logically wedged* on a request whose response was dropped in the gap. Because there is no error, no timeout at the transport layer, and no missing-heartbeat signal, the wedge is invisible to naive liveness checks. The agent burns its token/step budget waiting, or — if it has a coarse global timeout — fails the entire task and re-runs it, duplicating side effects of any tools already executed before the gap (the `c-91` tool may have run to completion server-side). The guardrail is a client-side **outstanding-request ledger** keyed by JSON-RPC id, reconciled against every inbound event, plus a **cursor-contiguity assertion** at the first event after any reconnect. On gap detection, the client transitions the session to `RESUMPTION_GAP` and fails fast rather than waiting. This converts an unbounded silent hang into a bounded, observable error that the agent's planner can act on (re-issue, escalate, or abandon with a clean checkpoint). ```python import json from dataclasses import dataclass, field from typing import Optional class ResumptionGapError(RuntimeError): """Raised when an SSE reconnect resumes at a cursor that is not contiguous with the client's last acknowledged event id, indicating lost events.""" def __init__(self, last_seen: int, first_received: int, session_id: str): self.last_seen = last_seen self.first_received = first_received self.session_id = session_id super().__init__( f"session {session_id}: reconnect resumed at event {first_received} " f"but last acknowledged was {last_seen}; " f"{first_received - last_seen - 1} event(s) lost in replay buffer eviction" ) @dataclass class OutstandingRequest: rpc_id: str method: str deadline_ms: int @dataclass class SessionCursor: session_id: str last_event_id: Optional[int] = None outstanding: dict[str, OutstandingRequest] = field(default_factory=dict) reconnecting: bool = False def on_event(self, raw: str) -> dict: """Process one SSE event. Enforces contiguity on the first event after a reconnect and reconciles the outstanding-request ledger.""" event_id, payload = self._parse(raw) if self.reconnecting: if self.last_event_id is not None and event_id != self.last_event_id + 1: # Gap detected: do not silently advance the cursor. raise ResumptionGapError( last_seen=self.last_event_id, first_received=event_id, session_id=self.session_id, ) self.reconnecting = False self.last_event_id = event_id # Reconcile: a result/error for an outstanding request clears it. if "id" in payload and payload.get("result") is not None or payload.get("error") is not None: self.outstanding.pop(str(payload.get("id")), None) return payload def begin_reconnect(self) -> None: """Called before re-establishing the SSE stream. Marks the next event as subject to the contiguity check.""" self.reconnecting = True @staticmethod def _parse(raw: str) -> tuple[int, dict]: event_id = None data_lines = [] for line in raw.splitlines(): if line.startswith("id:"): event_id = int(line[3:].strip()) elif line.startswith("data:"): data_lines.append(line[5:].strip()) if event_id is None: raise ResumptionGapError(-1, -1, "unknown") # server must emit ids return event_id, json.loads("\n".join(data_lines)) def resume_stream(cursor: SessionCursor, reconnect_events: list[str]) -> list[dict]: """Drive the post-reconnect event sequence through the contiguity gate.""" cursor.begin_reconnect() processed = [] for raw in reconnect_events: processed.append(cursor.on_event(raw)) return processed ```