# Which invariants prevent silent event loss in MCP HTTP-native streaming transports with resumable SSE session negotiation for stateless agent clients **Date of Record:** 2026 November 16 **Scope:** Applies to MCP servers exposing a Streamable HTTP transport where a stateless agent client (no persistent process memory between requests) negotiates a session via `Mcp-Session-Id`, receives server-to-client messages over an SSE stream, and may resume that stream using `Last-Event-ID` after a disconnect. Does not apply to stdio transports, to stateful clients that hold the stream open in-process, or to servers that do not implement event IDs on the SSE channel. ## Core Distinction The distinction that matters is between *transport-level resumption* and *logical-level replay*. `Last-Event-ID` resumption guarantees only that the server will resume the byte stream after a given event ID; it does **not** guarantee that the event ID the client holds corresponds to the last message the client actually *processed*. A stateless agent client that reconnects after a crash, a load-balancer timeout, or a tool-call pause has only the last event ID it durably persisted. If the server's event buffer is bounded and has already evicted events after that ID, the server will happily resume from a *later* point (or from the current head) without signaling the gap. The stream is valid; the session is silently lossy. The invariant that must be enforced is not "resume the stream" but "resume the stream **or fail loudly if the requested event ID is no longer recoverable**." ## What Was Observed In a deployment where an MCP server kept a per-session ring buffer of 1,024 events for resumption, a stateless agent client performing long-running tool orchestration persisted `Last-Event-ID` on every received event. During a 40-second pause while the client executed a local tool, the server emitted 1,300 low-priority progress notifications into the same session buffer. On reconnect, the client sent `Last-Event-ID: 88214`. The server's buffer had advanced to events `89238`–`90262`; event `88214` had been evicted. The server, following the common "resume from nearest retained event" implementation, opened the stream at `89238` and returned `200 OK` with `Content-Type: text/event-stream`. The client observed no error, no gap marker, and no sequence discontinuity — event IDs are opaque and the client does not assume monotonicity. The client therefore treated the resumed stream as continuous. Result: 1,024 events, including two `notifications/message` items carrying tool-result payloads the orchestrator depended on, were dropped with zero diagnostic surface. The failure was detected three hours later when a downstream artifact was missing a field. The non-obvious part: the server behaved *correctly* per the transport spec. Resumption is best-effort. The loss was a **contract gap between transport resumption semantics and agent-client durability semantics**, not a server bug. ## Condition of Validity The invariant "a resumed SSE stream is a superset of the client's processed state" holds only when all of the following are true: 1. The server retains every event from the client's `Last-Event-ID` forward, unbounded or for a retention window that provably exceeds the client's maximum disconnect-plus-processing pause. 2. The server, on receiving a `Last-Event-ID` it cannot satisfy, **rejects** the resume (e.g., `409 Conflict` or `400` with a machine-readable `resume_gap` body) rather than silently truncating to the nearest retained event. 3. The client treats a resume response as continuous only if the server confirms continuity, and otherwise re-negotiates a fresh session and re-derives state from an authoritative snapshot. 4. Event IDs are assigned by a single serialization point per session; concurrent producers do not interleave IDs in a way that makes "nearest retained" ambiguous. Condition 2 is the one most commonly violated, because the "nearest retained" behavior maximizes availability and looks like graceful degradation. It is the boundary failure: it converts a detectable gap into an undetectable one. ## Decision Boundary The operational decision is: **when a stateless client reconnects with an event ID the server cannot honor, the server must choose explicit failure over implicit truncation.** The boundary is crossed the moment the server can detect that the requested ID no longer exists in its buffer. Below that boundary (ID still retained), resumption is safe and should proceed silently. Above it, three responses are possible and only one is correct: - *Truncate to nearest retained* — maximizes uptime, silently violates the continuity invariant. Reject for agent clients. - *Close with an error and require re-negotiation* — correct default. The client re-opens a session and re-fetches authoritative state. - *Replay from an external durable log* — correct only if the server actually has one; do not simulate it from the ring buffer. For agent clients specifically, the decision must be biased toward failure because the agent cannot cheaply re-observe the world: a dropped tool result is not recoverable by re-reading the stream, only by re-executing the tool or re-fetching a snapshot. Silent truncation therefore has a cost asymmetry that does not exist for an interactive UI client, which can simply show a "reconnected" banner. ## Operational Effect Enforcing the invariant changes the failure mode from *silent data loss detected hours later* to *a recoverable `ResumeGapError` at reconnect time*. The client's reconnect handler becomes: attempt resume; on gap, discard the session ID, negotiate a new session, and re-hydrate state from the tool-result snapshot or by re-invoking idempotent tools. The cost is a small number of extra round-trips on the rare long-pause path; the benefit is that the agent's state is always either provably continuous or explicitly known to be stale. Servers should expose the gap as a structured error, and clients should never treat a `200` SSE response as proof of continuity without a server-issued resume acknowledgment. ```python from __future__ import annotations from dataclasses import dataclass class ResumeGapError(RuntimeError): """Raised when a stateless client requests an SSE resume point the server can no longer honor. This must propagate, never be swallowed into a best-effort truncation, because silent truncation is undetectable by the client and violates the continuity invariant.""" @dataclass(frozen=True) class SessionBuffer: first_retained_id: int last_emitted_id: int def can_resume_from(self, last_event_id: int) -> bool: # Safe iff the requested ID is still within the retained window. return self.first_retained_id <= last_event_id <= self.last_emitted_id def negotiate_resume( session_id: str, last_event_id: int | None, buffer: SessionBuffer, session_is_live: bool, ) -> int: """Return the event ID the resumed stream will start after. Raises ResumeGapError if the client's durable position is unrecoverable. Never returns a 'nearest retained' position, which would silently drop events the client has not yet processed. """ if not session_is_live: raise ResumeGapError( f"session {session_id!r} is no longer live; client must " f"re-negotiate and re-hydrate state" ) if last_event_id is None: # Fresh stream, no prior position claimed. return buffer.last_emitted_id if last_event_id < buffer.first_retained_id: raise ResumeGapError( f"requested Last-Event-ID {last_event_id} for session " f"{session_id!r} was evicted; retained window is " f"[{buffer.first_retained_id}, {buffer.last_emitted_id}]. " f"Client must re-negotiate a fresh session." ) if last_event_id > buffer.last_emitted_id: raise ResumeGapError( f"requested Last-Event-ID {last_event_id} for session " f"{session_id!r} is ahead of server position " f"{buffer.last_emitted_id}; client state is inconsistent." ) return last_event_id def handle_streamable_http_reconnect( headers: dict[str, str], buffer: SessionBuffer, session_is_live: bool, ) -> int: session_id = headers.get("Mcp-Session-Id") if not session_id: raise ResumeGapError("missing Mcp-Session-Id on reconnect") raw = headers.get("Last-Event-ID") last_event_id = int(raw) if raw is not None else None return negotiate_resume(session_id, last_event_id, buffer, session_is_live) ```