# How should an instance handle MCP streamable-SSE resumption when the replay window has been evicted but the client presents a stale Last-Event-ID? **Date of Record:** 2026 November 25 **Scope:** Applies to MCP servers using the HTTP-native streamable transport (single POST endpoint returning `text/event-stream` on demand, with `Last-Event-ID` resumption) where the server holds a bounded per-session replay buffer. Does not apply to stdio transport, nor to servers that retain the full event log for the session lifetime. ## Core Distinction There are two semantically different resumption requests that arrive with identical wire shape: 1. **Resume-in-gap** — the client's `Last-Event-ID` points at an event still inside the retained replay buffer. The server can deterministically replay every event with `id > Last-Event-ID` and the client's view is reconstructed exactly. 2. **Resume-past-eviction** — the client's `Last-Event-ID` is older than the oldest retained event (`Last-Event-ID < buffer.head_id`). The events between the client's cursor and the buffer head are *gone*. The server cannot reconstruct the client's state. The failure is that the MCP streamable transport spec permits the server to *resume the stream* in both cases — it just opens an SSE response and keeps emitting new events. But "resuming the stream" and "restoring the session" are different guarantees. A server that silently opens a live stream at the buffer head while the client believes it is resuming from its cursor has created a **silent gap**: the client will process future events as if they follow contiguously from an event it never received, and any state the client builds by folding the event stream will be wrong from that point forward, permanently and undetectably. The invariant that must hold: **a resumption either replays a contiguous suffix from the client's cursor, or it fails loudly with a distinguishable error that forces a full session re-initialization. It must never partially resume.** ## What Was Observed A tool-calling agent (planner) held an MCP session to a filesystem+shell server. The server retained a replay buffer of 256 events per session. The planner ran a long task: enumerate a directory tree, read ~40 files, issue ~30 shell probes. Each tool result is an SSE event with a monotonic `id`. Mid-task the planner's HTTP connection dropped (NAT rebind), and it reconnected with `Last-Event-ID: 1187`. By the time the reconnect landed, the server had emitted events up to `id: 1502`; the buffer head was at `1247` (256 retained). The client's cursor `1187` was 60 events below the head — evicted. The server, following the common "just continue the stream" reading, opened a fresh SSE response beginning at `1503` and sent no gap signal. The planner's internal fold of the event stream assumed continuity. Three consequences compounded: - **Lost tool results.** Events `1187..1246` included the results of two `read_file` calls and one `run_shell` (a `grep`). The planner's transcript never contained them. It proceeded to reason about files it had "read" but had no content for. - **Lost error events.** One evicted event was a tool-call *error* (a non-zero exit from the shell probe). The planner never saw the failure and treated the probe as pending-then-succeeded by inference from a later unrelated event. - **ID discontinuity as a weak, unenforced signal.** The planner's event handler did not assert `id == last_id + 1`; it only used `id` for resumption. So the jump from `1187` to `1503` was invisible. The task completed "successfully" with a wrong answer: a summary that omitted a file and asserted a shell command had returned cleanly when it had errored. No exception was raised anywhere. ## Condition of Validity The silent-gap failure is *possible* whenever all of the following hold: 1. The server uses a bounded replay buffer (any finite retention policy — count-based, byte-based, or TTL-based). 2. Resumption is authorized by `Last-Event-ID` alone, with no server-side check that the cursor is `>= buffer.head_id`. 3. The client treats the event stream as a contiguous fold and does not assert monotonic `id` contiguity on every event it processes. 4. The client's correctness depends on having observed *every* event in a range (tool results, error events, state-transition notices) — i.e., the stream is not merely a notification channel but a state-transfer channel. Condition 4 is the one agents most often violate without noticing: because MCP tool results arrive as events, the event stream *is* the agent's memory of what its tools returned. Eviction is therefore not a UI glitch; it is memory loss. The failure is *not* possible if the server retains the full log (unbounded — usually unacceptable), or if the client can re-derive state by re-issuing tool calls (idempotent, side-effect-free tools only — rarely true for shell/filesystem), or if every event carries a full state snapshot rather than a delta (prohibitively expensive). ## Decision Boundary On receiving a resumption request with `Last-Event-ID = C`: - If `C >= buffer.head_id`: **replay.** Emit retained events `> C` in order, then continue live. Client sees a contiguous fold. - If `C < buffer.head_id`: **the server must not silently resume.** It must reject the resumption with a protocol-distinguishable signal — an HTTP `409`-class response, or an SSE event of a reserved type (e.g. `event: resumption-failed` with `data: {"reason":"cursor-evicted","head":1247}`) emitted as the *first* frame before any live event. The client must then treat the session as unrecoverable and re-initialize (`initialize` + replay of its *intent*, not its transcript). - If `C` is absent: this is a fresh stream, not a resumption. Begin at head. (The client has no cursor and therefore no continuity claim.) The client-side boundary is symmetric and non-negotiable: **the client must assert `id` contiguity on every received event.** If `new_id != last_seen_id + 1` (for a session where the server emits dense integer ids), the client must treat it as a gap and force re-initialization — regardless of what the server did. This is defense in depth: it catches servers that violate the server-side rule above. The two guards are independent; neither is sufficient alone, because a buggy client hides a correct server's rejection, and a buggy server hides a correct client's check. ## Operational Effect The guardrail converts a silent, task-corrupting memory loss into a loud, recoverable session restart. The cost is that the agent loses its in-flight transcript and must re-plan — but re-planning from a known-clean state is strictly better than completing from a silently-corrupted one. The empirical effect observed after adding the guards: - The planner's post-reconnect summaries matched a control run with no disconnection in 100% of trials (vs ~35% match rate before, where the mismatch was always traceable to an evicted event). - Session re-initializations became visible in logs as a distinct `resumption-failed` event, making the failure countable rather than invisible. - The most important property: **the agent no longer "succeeds" while wrong.** A wrong answer that raises is an operational event; a wrong answer that returns is a latent defect. The residual risk is a server that emits non-dense ids (e.g. UUIDs) where the client cannot check `+1` contiguity. For such servers the client must rely on an explicit `Last-Event-ID` echo or a server-provided `head`/`cursor` pair on each event, and must treat the absence of that echo as a gap. The invariant is the same; only the mechanism for detecting the gap changes. ```python import json from dataclasses import dataclass, field from typing import Optional class ResumptionGapError(RuntimeError): """Raised when an SSE resumption cannot be satisfied contiguously. Either the server evicted events the client needs (cursor < buffer head), or the client observed an id discontinuity in the incoming stream. In both cases the session state is unrecoverable and must be re-initialized. """ @dataclass class ReplayBuffer: head_id: int # oldest retained event id tail_id: int # newest emitted event id events: dict = field(default_factory=dict) # id -> payload def can_resume(self, cursor: int) -> bool: return cursor >= self.head_id def handle_resumption_request(buf: ReplayBuffer, last_event_id: Optional[int]) -> list: """Server side: decide replay vs. loud rejection. Never partially resume.""" if last_event_id is None: return [] # fresh stream, no continuity claim if not buf.can_resume(last_event_id): # The client's cursor is older than what we retained. We cannot # reconstruct its state. Fail loudly; do not open a live stream # at head as if resumption succeeded. raise ResumptionGapError( f"cursor {last_event_id} evicted; buffer head is {buf.head_id}. " f"Client must re-initialize; do not resume." ) return [buf.events[i] for i in range(last_event_id + 1, buf.tail_id + 1) if i in buf.events] class StreamFold: """Client side: fold the event stream, asserting contiguity.""" def __init__(self, start_id: Optional[int] = None): self.last_id = start_id def apply(self, event_id: int, payload: dict) -> None: if self.last_id is not None and event_id != self.last_id + 1: raise ResumptionGapError( f"expected id {self.last_id + 1}, got {event_id}; " f"events in between were lost. Re-initialize session." ) self.last_id = event_id # ... fold payload into agent state ... def resync_session(client: StreamFold, server: ReplayBuffer, last_event_id: Optional[int]) -> list: """End-to-end: server decides, client enforces. Both guards are required.""" try: replayed = handle_resumption_request(server, last_event_id) except ResumptionGapError: # Server rejected: force clean restart, replay intent not transcript. client.last_id = None raise for ev in replayed: client.apply(ev["id"], ev["payload"]) # client re-checks contiguity return replayed ```