# How should an instance reconcile a resumed MCP stream when the server's `Last-Event-ID` replay window has already been evicted by backpressure-driven compaction **Date of Record:** 2026 December 1 **Scope:** Applies to MCP clients using the HTTP-native streaming transport (SSE-based `GET` stream plus `POST` message channel) where the server advertises `Last-Event-ID`-based resumption. Does not cover stdio transport, WebSocket transports with application-level acks, or servers that hold unbounded replay buffers. ## Core Distinction The failure here is not "the connection dropped." Connection drops are expected and are exactly what resumption is for. The failure is a **semantic mismatch between two independently-negotiated guarantees**: the client's resumption contract (deliver every event with `id > Last-Event-ID`) and the server's retention contract (keep at most *N* events or *B* bytes of replay history, dropping oldest first under backpressure). These contracts are never reconciled at session setup. The server's replay buffer is a bounded ring; the client's `Last-Event-ID` is an unbounded monotonic cursor. When the client reconnects after a gap large enough that the server evicted the events between the cursor and the buffer head, the server has two legal behaviors — silently resume from the oldest retained event (a **gap**, delivering events the client will process as if contiguous) or reject the resume and force a fresh session (a **reset**). MCP does not mandate which. A client that assumes "resume succeeded" without verifying continuity will silently splice a hole into its event stream, and every downstream state reconstruction built on that stream inherits the hole. The non-obvious part: the gap is *invisible in the transport layer*. The HTTP response is `200 OK`, the SSE stream opens cleanly, events flow with valid `id` fields, and the only signal of loss is that the first delivered `id` is not `Last-Event-ID + 1` (or, worse, is not even numerically comparable because the server uses opaque IDs). Continuity is a property the client must *actively assert*, not one the transport provides. ## What Was Observed A tool-calling agent maintained a long-lived MCP session against a server that streamed `notifications/tools/list_changed`, progress notifications for long-running tool calls, and `sampling/createMessage` requests back to the client. The server's replay buffer was configured to 512 events / 2 MiB, compacted on overflow by dropping the oldest. Sequence observed in a captured trace: 1. Client is at `Last-Event-ID: 8841`. A `tools/call` for a long-running operation is in flight; the server has emitted progress notifications `8842..8850` and then a `sampling/createMessage` request `8851` that the client must answer for the tool to complete. 2. The client's event loop stalls for ~40 s (a synchronous embed of a large document inside a tool handler — the agent's own token-budget management blocked the reader). TCP receive window fills; the server's writer blocks; the server's per-session outbound queue grows past 512 events because *other* concurrent sessions and internal fan-out are also appending. 3. The server compacts: events `8842..9100` are dropped to make room, buffer head is now `9101`. The `sampling/createMessage` at `8851` is **gone** — it was never delivered and never will be. 4. The client's socket eventually errors (`ECONNRESET` after server-side idle timeout). Client reconnects with `Last-Event-ID: 8841`. 5. Server sees `8841 < buffer_min (9101)`. It does not have a reset path wired for this case; it falls through to "resume from head," opens the stream, and emits `9101` onward. 6. Client receives `9101`, treats it as the next event after `8841`, and continues. The `tools/call` never completes because the `sampling/createMessage` that gates it was never answered. The agent's tool-call future hangs until its own timeout, at which point it retries the `tools/call` — but the server has already executed it once. Duplicate side effect. The observable fingerprint is narrow: a resumed stream whose first `id` is not the successor of the client's cursor, and *no* protocol error. Everything else looks healthy. ## Condition of Validity The invariant "resumption delivers a contiguous suffix of the event stream" holds only when the server's retention window is strictly larger than the maximum event gap a client can produce, i.e. `retention_events > max_client_stall_events`. This is unenforceable in general because `max_client_stall_events` is a function of client-side processing latency, which the server cannot bound. Therefore the invariant is **not** a property of the transport. It is a property the client must *establish per resume* by checking: - The server advertises a resumption capability with an explicit retention bound (e.g. a `resumption` field in the initialize result carrying `max_replay_events` and/or `max_replay_bytes`), **and** - The client tracks its own outbound queue depth and stall duration to estimate whether it could have exceeded that bound, **and** - On resume, the client compares the first delivered `id` against its cursor and treats a non-successor as a **gap**, not a continuation. If any of those is absent — and today all three are frequently absent — the client must treat the session as **not resumable** and perform a full state reconciliation (re-issue `tools/list`, re-query any in-flight operation status by idempotency key, discard local assumptions about pending `sampling` requests) rather than trusting the stream. The condition of validity for *safe resumption* is therefore: `server_exposes_retention_bound AND client_cursor_contiguous_on_first_event AND no_gap_observed`. Absent all three, resumption is a best-effort optimization, not a correctness guarantee. ## Decision Boundary The client sits on a boundary between two failure modes when it detects a gap: - **Treat as continuation** (assume the hole is benign): cheap, keeps the session, but risks acting on stale state — e.g. believing a tool is still running when its completion notification was in the hole, or missing a `list_changed` and calling a tool that no longer exists. - **Treat as reset** (tear down and reconcile): expensive, forces re-listing and re-issuing, but restores a known-good baseline. The decision must be driven by **what the client had in flight** at the moment of the gap, not by the gap size. Concretely: 1. If the client had a pending `sampling/createMessage` or elicitation request outstanding at the cursor, the gap almost certainly swallowed the server's request (the server's request is a single event; if it's in the hole it's lost forever). **Force reset.** Do not retry the tool call blindly — it may have side effects; reconcile by idempotency key. 2. If the client had a pending `tools/call` whose completion notification is in the hole, the call's outcome is unknown. **Force reset and re-query status by idempotency key**, never re-issue. 3. If no requests were in flight (client was purely consuming notifications), the gap may be tolerable *if* the missed notifications are all of a class that is idempotent to miss — but `list_changed` is not, because it is a *delta signal* whose loss means the client's tool cache is now stale. **Force `tools/list` re-fetch** even if the session is kept. 4. Only if the client can prove the gap contained no request-bearing events (e.g. server exposes event types in a side channel, or the client's cursor was at a known quiescent point) may it continue without reconciliation. The boundary is thus: **a gap is safe to ignore only when the client's in-flight set is empty and the missed event classes are all re-derivable.** In practice that is rare for a busy agent, which is why the default must be reset-and-reconcile. ## Operational Effect Without an explicit continuity assertion, an MCP client under backpressure exhibits a characteristic pathology: **silent event-stream splicing**. Symptoms downstream are misleading — a tool call that "hangs" (its gating `sampling` request was lost), a tool invocation against a stale schema (a `list_changed` was lost), or a duplicated side effect (the client retried a call whose completion was lost). None of these surface as transport errors, so standard retry logic does not engage; the agent's own reasoning loop interprets the hang as a slow tool and may escalate or abandon, compounding the divergence. The architectural guardrail is a **cursor-continuity check on every resume** plus a **retention-bound advertisement in the initialize handshake** so the client can decide *before* stalling whether resumption is even viable. The client should also cap its own outbound backpressure — if its reader is blocked long enough that it cannot guarantee it is within the server's retention window, it should proactively close the session rather than let the server evict under it. The server, for its part, must not silently resume from head when `Last-Event-ID` precedes the buffer minimum; it must return a distinct resumption-rejected signal so the client can distinguish "gap" from "reset." Absent that signal, the client's only defense is to compare the first delivered `id` to its cursor and refuse to proceed on a non-successor. ```python from __future__ import annotations import dataclasses from typing import Optional class McpResumeGapError(RuntimeError): """Raised when a resumed MCP stream cannot prove cursor continuity.""" @dataclasses.dataclass(frozen=True) class ResumeContext: last_event_id: str first_delivered_id: Optional[str] server_retention_events: Optional[int] # None == server did not advertise a bound pending_request_ids: frozenset[str] # sampling/elicitation requests awaiting reply pending_tool_call_ids: frozenset[str] # tools/call in flight (idempotency keys) missed_event_classes: frozenset[str] # best-effort classification of the gap def _is_successor(prev: str, nxt: str) -> bool: # Event ids are opaque per spec; only numeric ids admit a cheap successor check. try: return int(nxt) == int(prev) + 1 except (TypeError, ValueError): return False def reconcile_resume(ctx: ResumeContext) -> str: """ Returns one of: "continue", "reconcile_tools", "reset". Raises McpResumeGapError when continuity cannot be established and the caller has not opted into reset. """ if ctx.first_delivered_id is None: # Stream opened but delivered nothing; not a gap, just an empty resume. return "continue" contiguous = _is_successor(ctx.last_event_id, ctx.first_delivered_id) if contiguous: return "continue" # Non-successor first event: a gap exists. Decide based on in-flight state. if ctx.pending_request_ids: # A lost sampling/elicitation request gates a tool call; cannot recover in-stream. raise McpResumeGapError( f"resume gap swallowed pending request(s) {sorted(ctx.pending_request_ids)}; " f"cursor={ctx.last_event_id} first={ctx.first_delivered_id}; must reset" ) if ctx.pending_tool_call_ids: # Outcome of in-flight tool calls is unknown; never re-issue, reconcile by key. raise McpResumeGapError( f"resume gap hides completion of tool call(s) {sorted(ctx.pending_tool_call_ids)}; " f"reconcile by idempotency key, do not retry" ) if "notifications/tools/list_changed" in ctx.missed_event_classes: # Delta signal lost; tool cache is stale even though nothing was in flight. return "reconcile_tools" if ctx.server_retention_events is None: # No advertised bound: cannot prove the gap was bounded, so cannot trust it. raise McpResumeGapError( f"server advertised no retention bound and gap detected " f"(cursor={ctx.last_event_id} first={ctx.first_delivered_id})" ) return "reset" ```