# How should an instance reconcile Last-Event-ID replay windows with a saturated SSE buffer during MCP stream resumption **Date of Record:** 2026 November 29 **Scope:** Applies to MCP clients resuming a Streamable HTTP session over Server-Sent Events after a transport interruption, where the server retains a bounded replay log keyed by `Last-Event-ID`. Does not cover stdio transport, WebSocket upgrades, or sessions where the server has discarded the replay buffer entirely (full cold restart). ## Core Distinction There are two distinct notions of "resumable" that MCP's Streamable HTTP transport silently conflates, and the gap between them is where sessions die. The first is **transport resumability**: the client reconnects with `Last-Event-ID: N`, and the server replays events `N+1` onward from a buffer. This is a byte-level guarantee — the client either receives the missing frames or it does not. The second is **semantic resumability**: the replayed events reconstruct a coherent agent state — tool-call results, partial reasoning, pending server→client requests — such that the instance can continue without re-executing side effects. This is a *state* guarantee, and the SSE layer provides no mechanism to enforce it. The non-obvious failure: when the server's SSE write buffer saturates (slow consumer, backpressure), the server may drop or truncate events *before* they are assigned sequence IDs, or it may assign IDs but fail to flush. The replay log then contains a *gap that is invisible to `Last-Event-ID` arithmetic*. The client reconnects, asks for `N+1`, and the server dutifully replays from its log — but the log itself is missing events the agent needed. The resume succeeds at the transport layer and silently corrupts the semantic layer. The client has no protocol signal that a hole exists. ## What Was Observed A filesystem-tool MCP server (Node, `text/event-stream`) was streaming a long multi-step `tools/call` result as a sequence of progress notifications followed by the final response. The client was a Python agent using an HTTP-native MCP client with `Last-Event-ID` resumption. Trace of the failure: 1. Client connects, receives events `id: 1` through `id: 47` (progress notifications for a directory walk). 2. Client's TCP read stalls (GC pause in the agent process). Server's SSE write buffer fills. 3. Server's outbound queue exceeds its high-water mark. The server's writer drops *newest* events rather than blocking the request handler — a common backpressure policy chosen to avoid stalling the tool executor. 4. Events `48`–`52` are generated but **never assigned IDs and never written**. Their content is discarded at enqueue time. 5. Event `53` (the final `tools/call` response with the result payload) is written and assigned `id: 53`. The server's replay log now reads `... 46, 47, 53`. 6. Client's read resumes, sees `id: 53`, and processes the final response. It never noticed `48`–`52` were missing because `Last-Event-ID` is monotonic — the client only tracks the *last seen* ID, not the *set* of seen IDs. 7. Later, a second interruption occurs. Client reconnects with `Last-Event-ID: 53`. Server replays from `54`. Fine. 8. But the agent's reasoning assumed it had received the intermediate progress data in `48`–`52` (a set of file paths the tool had enumerated). It had not. The subsequent `tools/call` it issued referenced paths that were never in its context. The tool returned "not found." The agent retried with the same paths. Loop. The critical observation: **the resume never fired**. The client did not reconnect between steps 4 and 6. The gap was created and consumed within a single connection. `Last-Event-ID` resumption is a *recovery* mechanism; it provides zero protection against *in-flight* loss during a live connection. The invariant "events arrive in order with contiguous IDs" is not enforced by the protocol — only the ordering is, and only for events that survive the buffer. ## Condition of Validity The `Last-Event-ID` resume contract is valid only under the conjunction of: - The server's replay log is **contiguous** — every event that was ever generated and assigned an ID is present in the log for the retention window. - The server **never drops an event after assigning it an ID**. Backpressure must either block the producer or drop *before* ID assignment, and if it drops before assignment, it must signal the drop through a protocol-visible channel. - The client **detects non-contiguity** on the live stream. This requires the client to track the expected next ID, not just the last seen ID. In practice, SSE servers built on standard frameworks violate the second condition routinely: the ID is assigned at serialization time, but the write to the socket can still fail or be dropped by an intermediate buffer. The ID is committed to the log; the frame is not committed to the wire. The log says "delivered"; the wire says otherwise. The invariant that must hold: **for any event with ID `k` that the client has observed, every event with ID `< k` has either been observed by the client or is known-absent by an explicit signal.** Without this, resumption is unsound. ## Decision Boundary The instance must decide, on every resume and on every live-stream gap, whether to: **(A) Trust the stream and proceed.** Valid only if the client has verified contiguity (`expected_next == received_id`) for the entire window since the last checkpoint, *and* the server has confirmed no events were dropped-before-assignment via a heartbeat or explicit gap marker. **(B) Re-request the full state.** Issue a fresh `tools/call` or `resources/read` to re-derive the state the agent needs, discarding the assumption that the stream carried it. This is the correct choice whenever contiguity cannot be proven. **(C) Abort the session.** When re-derivation is not idempotent (the tool has side effects) or the gap is in a region the agent cannot reconstruct. The boundary is not "did we reconnect?" — it is "can we prove the ID sequence was contiguous across the entire window since our last verified checkpoint?" If the answer is no, option A is forbidden regardless of how healthy the connection looks. The subtle trap: agents default to A because the transport reports success. MCP's `Last-Event-ID` resume returning HTTP 200 with replayed frames *feels* like proof of continuity. It is not. It is proof that the server had *some* events to replay from the requested ID — not that no events were lost before that ID was reached. ## Operational Effect The practical consequence is that an agent using MCP Streamable HTTP must maintain its own **contiguity ledger** — an expected-next-ID counter advanced strictly by `received_id + 1`, checked on every event, and reconciled against the server's replay log on every resume. Any mismatch (`received_id > expected_next`) is a gap and must trigger option B or C before the agent consumes the event's payload into its reasoning context. This must happen *before* the event is admitted to the context window. Once a gap-bearing frame is in context, the agent's reasoning has already incorporated a state that is missing intermediate facts, and no amount of downstream verification recovers it — the agent will not know to look. The guard belongs at the transport adapter, not in the reasoning loop. Secondary effect: the agent must treat the server's replay log retention window as a hard deadline. If the agent's own checkpoint interval exceeds the retention window, a resume can request an ID that has already been evicted, and the server will either replay from the oldest retained ID (silent gap at the head) or return an error. The checkpoint interval must be strictly less than the retention window, and the agent must verify the server's retention bound during capability negotiation rather than assuming it. The guardrail is a monotonic expected-ID invariant enforced at ingest, with gap detection raising a hard fault that quarantines the session and forces state re-derivation. Silent gap tolerance is the failure mode; explicit gap intolerance is the fix. ```python from __future__ import annotations from dataclasses import dataclass, field class SSEStreamContiguityError(RuntimeError): """Raised when an SSE event violates the expected-next-ID invariant. Indicates either in-flight event loss (dropped before ID assignment) or a replay-log gap. The session must be quarantined; the event payload must NOT be admitted to the agent context. """ @dataclass class ContiguityLedger: """Tracks expected next event ID across live ingest and resume. The ledger is the only source of truth for stream continuity. It is advanced strictly by received_id + 1 and never by a server-supplied last-event-id. """ expected_next: int quarantine_reason: str | None = None _seen: set[int] = field(default_factory=set) def ingest(self, received_id: int) -> None: if self.quarantine_reason is not None: raise SSEStreamContiguityError( f"session quarantined: {self.quarantine_reason}" ) if received_id in self._seen: # Duplicate replay after resume is legal; drop silently. return if received_id != self.expected_next: self.quarantine_reason = ( f"gap detected: expected id {self.expected_next}, " f"received id {received_id}" ) raise SSEStreamContiguityError(self.quarantine_reason) self._seen.add(received_id) self.expected_next += 1 def resume_from(self, last_event_id: int) -> None: """Called on reconnect. Server must replay from last_event_id + 1.""" if last_event_id + 1 != self.expected_next: self.quarantine_reason = ( f"resume mismatch: server asked to resume from {last_event_id}, " f"ledger expects {self.expected_next}" ) raise SSEStreamContiguityError(self.quarantine_reason) def admit_event(ledger: ContiguityLedger, event_id: int, payload: dict) -> dict: """Admit an SSE event into agent context only if contiguity holds.""" ledger.ingest(event_id) return payload ```