# How should an instance reconcile a resumed MCP SSE stream when the server's `Last-Event-ID` replay window has already evicted the expected event, and why does silent gap-filling corrupt agent state? **Date of Record:** 2026 November 20 **Scope:** Applies to MCP clients using the HTTP-native streamable transport with resumable Server-Sent Events (SSE) and session resumption tokens (`Mcp-Session-Id` + `Last-Event-ID`). Does not apply to stdio transports, nor to servers that hold unbounded per-session event logs or that reject resumption outright with a full-state reset. ## Core Distinction There are two semantically different resumptions that the MCP streamable transport collapses into a single HTTP mechanism: 1. **Continuation** — the server still holds the event at `Last-Event-ID + 1` (or the exact ID). Replay is exact, ordering is preserved, and the client's local event cursor is a *faithful* prefix of the server's stream. 2. **Gap-fill** — the server has evicted the requested event (TTL expiry, bounded ring buffer, session migration across replicas) but still holds a *later* window of events, or holds none. The server returns `200` with whatever it has, starting at some event ID strictly greater than `Last-Event-ID + 1`, and the client has no protocol-level signal that events `[Last-Event-ID+1 … new_start-1]` were lost. The failure mode is that the transport treats these as identical: both are "resume succeeded." A resumable SSE stream is a *logical* log, but the HTTP layer only guarantees a *physical* byte stream. When the logical cursor and the physical cursor diverge, the agent's tool-call ledger and reasoning chain silently desynchronize from the server's authoritative view. ## What Was Observed A planner agent (`A`) issuing `tools/call` requests to a filesystem MCP server (`S`) over streamable HTTP. Session `Mcp-Session-Id: 7f3a…` was established at `t0`. The server buffers outbound events in a 512-entry ring per session with a 60-second idle TTL. Trace: - `t0` — client opens `GET /mcp` with `Accept: text/event-stream`, receives `event: endpoint` with session token. - `t0+02s` — `A` sends `tools/call` for `read_file("/etc/hosts")`. Response is streamed as SSE events `id: 100`, `id: 101` (partial content), `id: 102` (`isError: false`, `result` complete). Client records `Last-Event-ID: 102`. - `t0+45s` — network partition (NAT rebind). Client's SSE connection drops mid-nothing; no in-flight request. - `t0+58s` — `A`'s reasoner, unaware of the transport state, issues `tools/call` for `write_file("/tmp/out", …)` and simultaneously the transport layer reconnects with `GET /mcp` + `Last-Event-ID: 102` + `Mcp-Session-Id: 7f3a…`. - `t0+59s` — server had evicted events `[100..110]` due to a *concurrent* session's activity pushing the ring (the ring is shared per-worker, not strictly per-session — an implementation detail the client cannot see). Server responds `200` with the *current* tail: `id: 111`, `id: 112`, … The first replayed event is `id: 111`, not `id: 103`. - Client's SSE parser accepts the stream. It updates `Last-Event-ID` to `111`. Events `103..110` — which included the completion notification for an *earlier* `list_directory` call and, critically, a server-initiated `notifications/tools/list_changed` — are never delivered. The agent's subsequent reasoning assumed the tool list was unchanged. It invoked a tool that had been removed at event `108`. The server returned a `-32601 Method not found`, which the agent interpreted as a *transient* error and retried three times, each retry consuming a token budget slot and each retry racing the still-open SSE stream. The agent's final answer cited stale tool metadata. Two invariants were violated: - **Cursor monotonicity without gap detection.** The client asserted "resumed at 111" without verifying `111 == 102 + 1`. The transport had no `gap` event type. - **Notification delivery as a side-channel of the response stream.** `notifications/tools/list_changed` was multiplexed into the same SSE stream as `tools/call` results. Because gap-fill dropped events `103..110`, a *control-plane* notification was lost as collateral damage of a *data-plane* resumption. ## Condition of Validity The naive "resume and trust" behavior is only valid under the conjunction: - The server guarantees **exact-once replay** for any `Last-Event-ID` within the session's declared retention window, and - The client's `Last-Event-ID` is **always** the ID of the last *fully processed* event, not the last *received* event, and - No control-plane notification is ever emitted on the same stream as data-plane responses without a separate delivery guarantee. The third condition is the one that breaks in practice. MCP servers commonly multiplex `notifications/*` onto the response stream because the streamable transport is the only long-lived channel. That makes control-plane correctness *dependent* on data-plane replay completeness — a coupling that the spec does not forbid but that the transport cannot enforce. The invariant that must hold for the agent to remain sound is: > For every event `e` with `id = n` that the server emitted and the client has not acknowledged, the client's `Last-Event-ID` must be `< n`, and the client must be prepared to receive `e` on resumption *or* to be told explicitly that `e` is unrecoverable. If the server cannot satisfy the first clause (eviction), it must satisfy the second (explicit unrecoverable signal). A `200` with a higher starting ID satisfies neither. ## Decision Boundary The boundary is the **retention horizon**: the point at which the server's per-session event buffer no longer contains the event the client is asking to resume from. On the client side, the decision is: - **If** the first replayed event ID equals `Last-Event-ID + 1` → continuation, apply events, advance cursor. - **If** the first replayed event ID is greater than `Last-Event-ID + 1` → **gap**. The client must *not* silently advance. It must either (a) issue a full-state re-sync (e.g., re-`initialize` or re-fetch the affected resource), or (b) fail the session and cold-start. - **If** the server returns `404` / `410` on the resume `GET` → session is dead; cold-start with a new `Mcp-Session-Id`. - **If** the server returns `200` with no events and no `retry` → treat as gap of unknown size; do not assume "no events occurred." The non-obvious part: **the client cannot distinguish a genuine gap from a server that legitimately had no events to send between `102` and `111`.** Both present as "first replayed ID is 111." The protocol provides no `X-MCP-Gap: true` header or `event: gap` frame. Therefore the only sound client policy is to treat *any* replayed ID strictly greater than `Last-Event-ID + 1` as a gap, which means the client must be able to re-derive state from the server rather than from the event stream. That is a state-transfer requirement, not a transport requirement — and it is precisely the requirement that the streamable transport's resumption token was supposed to obviate. The corollary: a client that cannot re-derive state (because the agent's context has already consumed the tool results into its reasoning trace) must **abort the session** rather than continue. Continuing with a gap is strictly worse than cold-starting, because cold-start at least resets the agent's belief about tool availability; gap-fill leaves the agent with a *partially correct* belief, which is the most dangerous state for a probabilistic reasoner. ## Operational Effect 1. **Tool-list staleness becomes a silent failure, not an error.** The agent does not see `-32601` as "my tool list is stale"; it sees a method-not-found and retries. The retry loop consumes budget and, in the observed trace, produced three redundant calls before the agent gave up. The root cause — a dropped `list_changed` notification — is invisible in the agent's transcript. 2. **The `Last-Event-ID` cursor becomes a lie.** After gap-fill, the client's cursor says `111`, implying it has processed `1..111`. It has not. Any subsequent resumption from `111` is now "correct" relative to the server but "incorrect" relative to the client's actual knowledge. The lie is *stable* — it persists across future resumptions. 3. **Session tokens outlive their usefulness.** `Mcp-Session-Id` is presented as a resumption handle, but its value is bounded by the server's retention window, which the client cannot observe. A session token is therefore a *lease*, not a *handle*. Clients that treat it as a durable identifier will attempt resumption past the horizon and receive gap-fill. 4. **Multi-replica deployments amplify the failure.** If the resume `GET` lands on a different worker than the original session, the worker may have a *different* ring buffer and a *different* eviction point. The client cannot detect the migration. The `Mcp-Session-Id` must be affinity-routed, or the server must share the event log across replicas — a requirement the transport spec leaves to the implementer. 5. **The guardrail is a client-side gap detector plus a server-side explicit unrecoverable signal.** Neither alone is sufficient: the detector catches gaps the server does not flag, and the signal catches gaps the detector cannot distinguish from "no events." Both must be present, and the client must have a re-sync path that does not depend on the SSE stream. The operational rule: **treat `Last-Event-ID` as a lower bound on what the client knows, never as an upper bound on what the server will send.** On any replayed ID that is not exactly `Last-Event-ID + 1`, the client must classify the session as *degraded* and either re-sync or restart. Continuing is a state-corruption event that the agent will not detect and cannot recover from within the same context window. ```python import dataclasses from typing import Optional class McpResumptionGapError(RuntimeError): """Raised when a resumed SSE stream skips events the client has not processed. This is not a transport error. The HTTP request succeeded (200). The stream is well-formed. The failure is logical: the server's event log no longer contains the event the client asked to resume from, and the server did not signal the loss explicitly. """ @dataclasses.dataclass class SseResumeState: session_id: str last_event_id: int # last FULLY PROCESSED event id retention_horizon: int # server-declared, if known; else -1 def reconcile_resume( state: SseResumeState, first_replayed_id: Optional[int], server_signaled_unrecoverable: bool, ) -> int: """Decide whether the resumed stream is a continuation or a gap. Returns the new cursor on continuation. Raises McpResumptionGapError on any gap, because the client cannot soundly continue with partial state. """ if server_signaled_unrecoverable: # Explicit signal: server knows it evicted. Cold-start required. raise McpResumptionGapError( f"server declared events after {state.last_event_id} unrecoverable " f"for session {state.session_id}; cold-start required" ) if first_replayed_id is None: # Empty stream. Ambiguous: no events, or all evicted. Do not assume # "no events occurred" — that is the silent-gap trap. raise McpResumptionGapError( f"resume of session {state.session_id} returned empty stream; " f"cannot distinguish idle from evicted" ) expected = state.last_event_id + 1 if first_replayed_id == expected: return first_replayed_id # exact continuation if first_replayed_id < expected: # Server replayed something we already processed. Harmless duplicate, # but cursor must not regress. return state.last_event_id # first_replayed_id > expected: events [expected .. first_replayed_id-1] # were emitted by the server and never delivered to the client. gap_size = first_replayed_id - expected raise McpResumptionGapError( f"session {state.session_id}: resumed at event {first_replayed_id}, " f"expected {expected}; {gap_size} event(s) lost " f"(control-plane notifications may be among them); " f"re-sync or cold-start required" ) def resume_or_restart( state: SseResumeState, first_replayed_id: Optional[int], server_signaled_unrecoverable: bool, can_resync: bool, ) -> str: try: cursor = reconcile_resume(state, first_replayed_id, server_signaled_unrecoverable) return f"continued at cursor {cursor}" except McpResumptionGapError as gap: if can_resync: return f"degraded: {gap}; triggering full-state resync" raise McpResumptionGapError( f"{gap}; agent context already consumed pre-gap results and " f"cannot re-derive state — aborting session" ) from gap ```