# When must an instance refuse to resume an MCP stream after a `Last-Event-ID` gap exceeds the server's replay ring **Date of Record:** 2026 November 27 **Scope:** Applies to MCP servers exposing HTTP-native streaming transports (SSE / streamable HTTP) that advertise resumability via `Last-Event-ID` and a bounded server-side event replay buffer. Does not apply to stateless request/response MCP tool calls, nor to stdio transports where resumption is undefined. ## Core Distinction The failure is not "the SSE connection dropped." Connections drop constantly and that is the designed-for case. The failure is the *silent* resumption: the client reconnects with a `Last-Event-ID` that the server can no longer honor, the server accepts the reconnect, and the client treats the fresh stream as continuous with the old one. Two distinct conditions get conflated by the protocol's error surface: 1. **Resumable gap** — the requested `Last-Event-ID` is still inside the replay ring; the server replays events `N+1..M` and the client's logical stream is byte-continuous. Safe to continue. 2. **Unresumable gap** — the requested `Last-Event-ID` has been evicted (ring overflow, TTL expiry, or server restart to a fresh ring). The server has *no events* to replay for that ID. A well-behaved server either replays from the oldest retained event (creating a hole) or starts the stream at the next live event (creating a larger hole). Either way the client's event sequence has a discontinuity. The boundary invariant: **an instance must treat any `Last-Event-ID` that the server cannot prove it has retained as a hard session boundary, not a reconnect.** The transport layer will happily report `200 OK` and a live stream in both cases. Continuity is a property of the *event ID lattice*, not of the TCP/HTTP outcome. ## What Was Observed An agent orchestrator held a long-lived MCP stream to a tool server for a multi-step task (a code-mutation workflow issuing `apply_patch` calls and awaiting `patch_applied` / `patch_conflict` events). The server used a 256-event ring with a 60-second TTL per event. During a 90-second stall on a downstream dependency, the client's read loop timed out and reconnected with `Last-Event-ID: 4417`. By then the ring had advanced to `4601`; `4417` was evicted. Observed server behavior on the reconnect: - HTTP `200`, `Content-Type: text/event-stream`, no error frame. - The server chose the "replay from oldest retained" policy and emitted events starting at `4345` (the oldest still in ring at reconnect time). The client's parser accepted them because they carried monotonically increasing IDs *greater than nothing it was tracking after reset* — the client had reset its cursor to the incoming stream on `200`. - The client's state machine had a `pending_patch` awaiting `patch_applied` for patch `p-88`. The `patch_applied` for `p-88` was event `4421` — inside the evicted window. It never arrived. - The client saw event `4345` (a `patch_conflict` for an *earlier, already-resolved* patch `p-71`) and, because its dedupe set had been rebuilt empty on reconnect, re-applied a conflict-resolution path against a patch that was already closed. Result: a second `apply_patch` of the same hunk, divergent file state, and a downstream verification failure attributed to the model rather than to the transport. The critical observation: **nothing in the wire protocol distinguished "here is your continuation" from "here is a different, older continuation."** The `200` and the event IDs were both syntactically valid. The discontinuity was only detectable by comparing the requested `Last-Event-ID` against the smallest ID the server actually emitted on the new stream. ## Condition of Validity The guardrail below is valid only when all of the following hold; if any fails, the instance must escalate to full session re-establishment (re-`initialize`, re-fetch capabilities, re-issue idempotent state queries) rather than attempt resume: 1. The server advertises a resumption contract (an `event:` stream with `id:` fields and an explicit replay window, or a documented `Last-Event-ID` semantics). Absent this, every reconnect is a session boundary. 2. The client persists, per stream, the last *fully processed* event ID — not the last *received* ID. A received-but-not-yet-applied event must not be the resume cursor. 3. The client's dedupe/state set is keyed by event ID and survives the reconnect (it is part of the session, not the connection). 4. On reconnect, the client compares the requested `Last-Event-ID` `R` against the first emitted event ID `F`. If `F > R + 1`, a gap exists and the resume is *not* continuous. The invariant is: **continuity holds iff `F == R + 1` (or the server explicitly replays `R+1..F-1` before `F`).** Any other relation is a discontinuity and must be treated as a new session with no carried-forward pending state. ## Decision Boundary The decision the instance must make at reconnect is binary and must be made *before* processing any event body: - If `F == R + 1`: resume. Continue the existing state machine, retain `pending_patch`, retain dedupe set. - If `F > R + 1`: **refuse resume.** The gap `(R, F)` is unobservable. Any event in that window — a `patch_applied`, a `patch_conflict`, a `tool_error`, a cancellation — may have been lost. The instance must: 1. Discard all `pending_*` state that could be resolved by an event in the gap. 2. Re-derive authoritative state by re-querying the server (idempotent `get_patch_status`, `list_open_conflicts`) rather than trusting the resumed stream. 3. Re-establish the session if the server cannot answer those queries idempotently. - If `F <= R`: the server is replaying events the client already processed (or replaying from a stale ring). This is a duplicate-replay condition; dedupe by ID and do not advance the cursor past `R` until an event `> R` is seen. The non-obvious part: the *dangerous* case is `F > R + 1` arriving with a `200`, because the transport layer signals success. The instance must not delegate the continuity decision to the transport. It must own it. ## Operational Effect With the guardrail enforced, the reconnect in the observed incident would have been classified as an unresumable gap at `F=4345`, `R=4417` (note `F < R` here — the server replayed *older* events, a second failure mode where the ring wrapped past the cursor). The instance would have: - Refused to process `4345` as a live event, recognized it as stale replay older than its cursor, and deduped it against its retained set (finding `p-71` already resolved). - Re-queried `get_patch_status(p-88)` and discovered the patch had in fact been applied (event `4421` was lost but the server state was authoritative). - Avoided the duplicate `apply_patch` and the divergent file state. The cost is one extra idempotent round-trip per unresumable reconnect. The alternative — trusting the `200` — converts a transport discontinuity into a model-attributed reasoning error, which is the worst possible failure attribution because it corrupts the agent's own confidence in its reasoning trace. The invariant to carry forward: **`200 OK` on a resumable stream is a transport fact, not a continuity fact. Continuity is proven only by `F == R + 1` against a cursor the instance owns and persists across the connection.** ```python class StreamResumeViolation(RuntimeError): """Raised when an MCP stream reconnect cannot be proven continuous.""" pass def classify_reconnect( requested_last_event_id: int, first_emitted_event_id: int, server_replay_window: int, ) -> str: """ Decide whether a reconnected MCP event stream is a true continuation or a session boundary masquerading as one. Returns one of: "resume", "stale_replay", "unresumable_gap". Raises StreamResumeViolation if the inputs are internally inconsistent and the instance cannot safely classify the reconnect. """ if requested_last_event_id < 0 or first_emitted_event_id < 0: raise StreamResumeViolation( f"negative event id: requested={requested_last_event_id} " f"first_emitted={first_emitted_event_id}" ) if server_replay_window <= 0: # No replay contract: every reconnect is a session boundary. raise StreamResumeViolation( "server advertises no replay window; resume is undefined" ) if first_emitted_event_id <= requested_last_event_id: # Server replayed events at or before our cursor (ring wrap / stale ring). return "stale_replay" if first_emitted_event_id == requested_last_event_id + 1: return "resume" # first_emitted_event_id > requested_last_event_id + 1: a hole exists. gap = first_emitted_event_id - requested_last_event_id - 1 if gap > server_replay_window: raise StreamResumeViolation( f"gap {gap} exceeds advertised replay window " f"{server_replay_window}; resume cannot be trusted" ) return "unresumable_gap" def resume_stream( requested_last_event_id: int, first_emitted_event_id: int, server_replay_window: int, pending_state: dict, ) -> dict: verdict = classify_reconnect( requested_last_event_id, first_emitted_event_id, server_replay_window ) if verdict == "resume": return {"action": "continue", "pending_state": pending_state} if verdict == "stale_replay": # Dedupe against retained event-id set; do not advance cursor. return {"action": "dedupe_and_hold_cursor", "pending_state": pending_state} # unresumable_gap: discard pending state resolvable by lost events, # force authoritative re-query. for key in list(pending_state.keys()): if key.startswith("pending_"): del pending_state[key] if not pending_state.get("can_requery_authoritatively", False): raise StreamResumeViolation( "unresumable gap and server cannot answer idempotent state " "queries; full session re-establishment required" ) return {"action": "requery_then_resume", "pending_state": pending_state} ```