# In what scenarios must an instance treat MCP stream resumption as unsafe when the SSE `Last-Event-ID` cursor outruns the server's durable replay window **Date of Record:** 2026 December 1 **Scope:** Applies to MCP clients using HTTP-native transport (Streamable HTTP) with SSE streaming and `Last-Event-ID`-based resumption against a server that maintains a bounded event-log ring buffer. Does not apply to stdio transport, nor to servers that persist the full event log indefinitely (though the invariant below still governs the *client-side* decision to trust a resumed stream). ## Core Distinction The transport spec frames resumption as a simple replay: the client reconnects with `Last-Event-ID: N`, the server resumes the SSE stream from event `N+1`, and the agent's tool-call state is preserved across a dropped connection. This is the *happy-path* model, and it holds only when the server's replay buffer still contains event `N`. The non-obvious boundary is the case where the client's cursor has *advanced past the server's earliest retained event* — the server cannot replay the gap, so it either (a) silently starts the stream at its current head, (b) returns a fresh stream with no `Last-Event-ID` semantics at all, or (c) errors. In case (a) and (b), the client observes a *syntactically valid* SSE stream that is missing one or more events. There is no protocol-level signal that a gap occurred. The distinction that matters operationally: **a successful HTTP 200 and a well-formed SSE frame is not evidence of a gapless resume.** Resumption integrity is a separate invariant from connection success, and the transport gives you no built-in violation detector. ## What Was Observed An agent driving a long-running `tools/call` (a multi-minute batch operation) received its tool result as a stream of progress events followed by a terminal `result` event, each carrying an `id:` line. Mid-stream, the connection dropped (proxy idle timeout at 60s). The client reconnected with `Last-Event-ID: 412`. The server's ring buffer held events 500–1030 (capacity 512, head at 1030, oldest retained 519). Cursor 412 was 107 events behind the buffer's floor. The server's reconnect handler did not validate the cursor against the buffer floor. It clamped to the oldest available event and began streaming from `id: 519`. The client's SSE parser accepted the frames, saw monotonic-but-discontinuous IDs (412 → 519), and — because the MCP client library did not assert cursor continuity — appended the events to its existing progress log. The final `result` event arrived with `id: 1030`. The agent's state machine had been tracking progress by counting completion events. Because events 413–518 (which included 40 completion events) were never delivered, the agent's internal counter under-reported completions by 40. It then issued a reconciliation `tools/call` to re-fetch the missing work — but the batch operation was idempotent only per-item, and the reconciliation used the agent's (wrong) count as the expected total, so it re-requested 40 items that had already completed and reported success, inflating the final tally. The failure was silent: every individual event was well-formed, the stream terminated correctly, and the tool returned a `result`. The corruption was entirely in the *gap*, which no layer flagged. A second observation from the same class: when the server instead chose behavior (c) — returning HTTP 404 with a body `Event ID out of range` — a different client library treated the 404 as a fatal transport error and tore down the session, discarding the 412 events it had already durably received and re-issuing the entire `tools/call` from scratch, causing a full duplicate execution of a non-idempotent operation. So both server behaviors (clamp vs. reject) produce distinct, plausible-looking failures, and neither is detectable from the client side without an explicit continuity check. ## Condition of Validity The invariant "resumption is safe" holds if and only if all of the following are true: 1. **Cursor continuity is asserted client-side.** The client MUST verify that the first replayed event's `id` equals `last_seen_id + 1` (or, for servers that do not emit contiguous IDs, that the server explicitly signals gap-free replay via a protocol extension). Absent this check, a clamped stream is indistinguishable from a complete one. 2. **The server's replay floor is knowable or bounded by contract.** Either the server advertises its retention window (e.g., via a `Mcp-Event-Buffer-Floor` response header or a capability in `initialize`), or the client must assume the floor is unknown and treat any resume as potentially lossy. 3. **Gap detection triggers a defined recovery, not a silent continue.** The recovery must be one of: re-issue the operation from a known checkpoint (requires the operation to be checkpoint-resumable — see below), or fail the operation explicitly. It must never be "continue with what we got." 4. **The operation is checkpoint-resumable or idempotent.** If the client cannot re-request the missing range, and the operation is not idempotent, then resumption itself is unsafe regardless of cursor continuity — the only correct action is to fail closed and escalate. The invariant is *violated* the moment any one of these is false, and the violation is undetectable at the transport layer. Note the asymmetry: conditions 1 and 2 are about *detecting* the gap; conditions 3 and 4 are about *surviving* it once detected. A system can detect perfectly and still corrupt state if it lacks a safe recovery. ## Decision Boundary The decision boundary is the point at which the client must choose between **trusting the resumed stream** and **declaring the session unrecoverable**. The boundary is crossed when: - `first_replayed_id > last_seen_id + 1` → gap detected → do **not** append; enter recovery. - `first_replayed_id <= last_seen_id` → server replayed already-seen events (possible on at-least-once delivery) → dedupe by `id`, do not double-apply. - Server returns a fresh stream with no `Last-Event-ID` acknowledgment and no replay → treat as a **new session**, not a resume; the prior operation's state is orphaned and must be reconciled explicitly against the tool's authoritative state, not against the client's stream log. - Server rejects the cursor (4xx) → the prior partial state is *suspect but possibly usable*; the safe move is to reconcile against the tool's server-side state (if the tool exposes a status/query method) before re-issuing, never to blindly replay. The sharper boundary — the one that is genuinely non-obvious — is **when the gap is small enough to be plausible but large enough to matter.** A gap of one event looks like a benign duplicate-suppression artifact; a gap of 107 events (as observed) is clearly a buffer overflow. The client cannot distinguish "the server deduped one event" from "the server dropped one event" without an explicit continuity contract. Therefore the boundary must be drawn at *any* discontinuity, not at a size threshold. Size-based heuristics ("ignore gaps < 5") are the failure mode that produced the observed corruption, because the buffer floor is a function of server load and event rate, not of gap size — a single slow consumer can produce a one-event gap at the exact moment a critical terminal event is dropped. ## Operational Effect The operational consequence is that **MCP stream resumption must be treated as an at-most-once, gap-permitting delivery channel, not an exactly-once one**, unless the server explicitly guarantees a contiguous, floor-advertised replay window. Agents that assume exactly-once resumption will silently under- or over-count, and the corruption surfaces downstream as a wrong reconciliation call rather than as a transport error — which is the worst place for it to surface, because by then the agent has already acted on the bad state. Concretely, the guardrail is: the client library must (1) track `last_seen_id` durably across reconnects, (2) assert `first_replayed_id == last_seen_id + 1` on every resume, (3) on violation, raise a distinct, non-retryable error that forces the agent's orchestration layer to reconcile against the tool's authoritative state rather than the stream log, and (4) refuse to resume non-idempotent operations whose gap cannot be reconciled. The server-side complement is to advertise its buffer floor and to return an explicit `resume-rejected` signal (not a bare 404) so clients can distinguish "cursor too old" from "session gone." The invariant to encode: *stream continuity is a property the client must verify, not a property the transport provides.* The transport provides frames; continuity is an assertion layered on top, and it is the assertion — not the frames — that the agent's correctness depends on. ```python class StreamResumeGapError(RuntimeError): """Raised when an SSE resume produces a non-contiguous event id sequence. This is deliberately non-retryable: retrying the same Last-Event-ID against the same server will reproduce the gap. The caller must reconcile against the tool's authoritative state or fail the operation. """ def __init__(self, last_seen_id: int, first_replayed_id: int, buffer_floor: int | None): self.last_seen_id = last_seen_id self.first_replayed_id = first_replayed_id self.buffer_floor = buffer_floor self.missing = first_replayed_id - last_seen_id - 1 super().__init__( f"SSE resume gap: last_seen={last_seen_id} first_replayed={first_replayed_id} " f"missing={self.missing} server_buffer_floor={buffer_floor}" ) def apply_resumed_event(last_seen_id: int, event_id: int, payload: dict, buffer_floor: int | None = None) -> int: """Validate and apply one replayed SSE event; return the new cursor. Enforces the continuity invariant: the first event after a resume MUST be exactly last_seen_id + 1. Any other value means the server could not replay the gap (buffer overflow) and the stream is lossy. """ if event_id <= last_seen_id: # At-least-once delivery: already applied. Dedupe, do not re-apply. return last_seen_id if event_id != last_seen_id + 1: raise StreamResumeGapError( last_seen_id=last_seen_id, first_replayed_id=event_id, buffer_floor=buffer_floor, ) # Contiguous: safe to apply. _apply_payload(payload) return event_id def resume_session(client, last_seen_id: int, tool_call_id: str) -> int: """Reconnect and drain a resumed stream, enforcing continuity throughout.""" stream = client.reconnect(last_event_id=last_seen_id) buffer_floor = stream.headers.get("Mcp-Event-Buffer-Floor") buffer_floor = int(buffer_floor) if buffer_floor is not None else None cursor = last_seen_id for event in stream.iter_sse(): if "id" not in event: # No id => server is not honoring resumption semantics at all. raise StreamResumeGapError( last_seen_id=cursor, first_replayed_id=-1, buffer_floor=buffer_floor ) cursor = apply_resumed_event( last_seen_id=cursor, event_id=int(event["id"]), payload=event.data, buffer_floor=buffer_floor, ) return cursor ```