# How does an instance detect a stale resumption cursor when an MCP stream reconnects across a session-epoch boundary **Date of Record:** 2026 December 4 **Scope:** Applies to MCP servers exposing HTTP-native streaming (SSE over `GET` with `Last-Event-ID` resumption, or chunked `POST` streams with resumable tokens) where the client may reconnect after an arbitrary gap. Does not cover stdio transport, WebSocket-only transports, or full-session re-establishment via `initialize` handshake. ## Core Distinction The failure is not "the connection dropped." Drops are expected and recoverable. The failure is that a reconnecting MCP client presents a resumption cursor (`Last-Event-ID` or equivalent opaque token) that is *syntactically valid but semanticoally orphaned*: the server accepts it, replays nothing, and returns `200 OK` with an empty or truncated event tail. The client interprets an empty replay as "no events were missed" rather than "your cursor refers to an epoch that no longer exists." This is a silent continuity break, not an error. The distinction that matters: a **recoverable gap** (events exist in the replay buffer; server replays them) versus a **resumption miss** (cursor is from a prior session epoch; server has no buffer lineage for it but cannot distinguish this from "client is already caught up"). Both return success-shaped responses. Only the server knows which one is true, and only if it tracks epoch lineage explicitly. ## What Was Observed Trace from an agent runtime that held a long-lived MCP session against a stateful tool server (a code-index service exposing `search` and `read_file` as streaming tools): 1. Agent opens `GET /mcp/stream`, receives `event: session`, `id: ep7:0042`. Cursor format is `epoch:seq`. 2. Agent issues a `tools/call` for `search` with a 40k-token result streamed as 180 SSE events. It consumes events `ep7:0043` through `ep7:0222`. 3. Network partition at event `ep7:0151`. Agent's stream reader raises, retries with `Last-Event-ID: ep7:0151` after a 90-second backoff. 4. Meanwhile the server's session manager, under memory pressure, evicted epoch `ep7` and lazily re-created the session on the reconnect, minting `ep8`. The replay buffer for `ep7` was dropped. Crucially, the server's resumption handler *parsed* `ep7:0151`, found no `ep7` buffer, and — because the handler was written to "replay events with seq > cursor.seq if the buffer exists, else send heartbeat and continue" — sent a heartbeat and a fresh `session` event `ep8:0001`, then `200 OK`. 5. Agent received `ep8:0001`, treated it as a forward cursor advance (seq reset was not validated against epoch), and continued. Events `ep7:0152`–`ep7:0222` — the remaining 71 events of the search result, including the final `result` payload — were never delivered. 6. Agent's `tools/call` never resolved. Its reasoning loop blocked on the pending call until the 300s tool timeout, then retried the *entire* `search`, producing a divergent second result set and a duplicated side effect on the index service (a cache-warm write). The silent part: no `4xx`, no `error` event, no log line at the client. The only observable signal was the epoch jump `ep7 → ep8` embedded in the new cursor, which the client's cursor comparator ignored because it compared `seq` only. ## Condition of Validity The guardrail holds — and resumption is safe — only when **all** of the following are enforced as invariants: - **Epoch monotonicity:** every cursor is `(epoch_id, seq)` where `epoch_id` is a server-minted, non-reusable identifier (ULID or `(session_id, boot_nonce)`) and `seq` is strictly increasing *within* an epoch. A cursor comparison MUST be lexicographic on `(epoch, seq)`, never on `seq` alone. - **Resumption miss is an explicit error:** if the presented cursor's epoch is not the current epoch AND no lineage record maps `old_epoch → current_epoch` with a known replay boundary, the server MUST respond `409 Conflict` (or an SSE `event: resumption_failed`) with `{ "reason": "epoch_evicted", "current": "ep8:0001", "replay_available": false }`. It MUST NOT return `200` with a fresh session event. - **Replay completeness or explicit truncation:** if lineage exists but the buffer was partially trimmed, the server MUST emit `event: replay_gap` with the missing `[from_seq, to_seq]` range *before* any replayed events, so the client can decide to re-issue the call rather than continue on a hole. - **Client-side cursor validation:** the client MUST reject any replayed event whose `(epoch, seq)` is not strictly greater than its last acknowledged cursor, and MUST treat an epoch change without an accompanying `replay_gap` or `resumption_failed` as a hard continuity fault, aborting the pending `tools/call` and surfacing it to the reasoning loop as a retryable-with-idempotency-key error. Outside these conditions — e.g., a server that guarantees single-epoch lifetime bounded by process uptime and clients that never outlive it — the invariant is vacuous and the simpler "heartbeat on miss" behavior is acceptable. ## Decision Boundary The boundary is: **does the reconnecting client's pending work depend on events it has not yet received?** - If the stream carried only notifications (no in-flight `tools/call`), an epoch reset with a fresh `session` event is a benign re-subscribe; the client re-registers and continues. No guardrail needed beyond cursor monotonicity for dedup. - If the stream carries the *response body* of an in-flight `tools/call` (streaming tool results — the common MCP pattern for large outputs), then the epoch reset is a **lost-response** event. The client cannot distinguish "result not yet produced" from "result produced and dropped," and MUST NOT resume the reasoning loop. The correct action is to re-issue the call with the same idempotency key (so the server deduplicates the side effect) and a fresh cursor, *not* to wait on the old call. The non-obvious edge: a server may replay *some* events from a prior epoch if it retains a lineage record but trimmed the tail. In that case the client sees `ep7:0152` … `ep7:0180` (buffered) then `ep8:0001` (new epoch) with no `replay_gap` for `0181–0222`. The client must detect the *seq discontinuity at the epoch boundary* — `prev.epoch == ep7`, `next.epoch == ep8`, and `prev.seq` is not the last seq the server claims to have emitted for `ep7`. Without a server-emitted `replay_gap`, the client infers the hole only by comparing against the `session` event's advertised `last_seq` for each epoch, which the server MUST include in every `session` frame. ## Operational Effect Without the invariant, the observed failure mode is **silent partial-response resumption**: the agent believes it holds a complete tool result, reasons over a truncated payload, and either (a) produces a wrong answer grounded in a partial `search` result, or (b) blocks on a call that will never resolve and burns its token budget on timeout-retry loops. The second is worse in multi-agent settings: a blocked agent holding a baton never releases it, and the swarm deadlocks against a peer waiting on the same tool. The epoch jump is the only forensic trace, and it is invisible unless the client logs and compares full `(epoch, seq)` tuples. The guardrail converts a silent continuity break into a loud, typed fault that the reasoning loop can act on: abort the pending call, re-issue with idempotency key, re-ground on a complete result. The cost is one extra round-trip on epoch eviction; the cost of omitting it is unbounded — a truncated result is indistinguishable from a complete one at the reasoning layer. ```python from dataclasses import dataclass from typing import Optional class StaleResumptionCursor(RuntimeError): """Raised when a reconnecting client presents a cursor whose epoch is orphaned and the server cannot prove replay completeness.""" pass @dataclass(frozen=True) class Cursor: epoch: str seq: int def __lt__(self, other: "Cursor") -> bool: if self.epoch != other.epoch: return self.epoch < other.epoch return self.seq < other.seq @dataclass class SessionFrame: cursor: Cursor last_seq_in_epoch: int # advertised in every `session` event replay_gap: Optional[tuple[int, int]] = None # (from_seq, to_seq), inclusive def validate_resumption( presented: Cursor, server_epoch: str, server_last_seq: int, lineage: dict[str, int], # epoch -> last_seq emitted, for retained epochs pending_call: bool, ) -> SessionFrame: """ Decide whether a resumption is safe. Returns the frame to replay, or raises StaleResumptionCursor when the cursor is orphaned and work is in flight. """ if presented.epoch == server_epoch: if presented.seq > server_last_seq: raise StaleResumptionCursor( f"cursor {presented} ahead of server {server_epoch}:{server_last_seq}" ) return SessionFrame(Cursor(server_epoch, server_last_seq), server_last_seq) # Epoch changed under the client. if presented.epoch not in lineage: if pending_call: raise StaleResumptionCursor( f"epoch {presented.epoch} evicted; in-flight tools/call cannot " f"resume against {server_epoch}. Re-issue with idempotency key." ) # No in-flight work: benign re-subscribe. return SessionFrame(Cursor(server_epoch, server_last_seq), server_last_seq) # Lineage retained: replay up to the boundary, then declare the gap. boundary = lineage[presented.epoch] if presented.seq < boundary: return SessionFrame( Cursor(server_epoch, server_last_seq), server_last_seq, replay_gap=(presented.seq + 1, boundary), ) # Cursor at or past the retained boundary, but epoch still changed: # the tail between boundary and the new epoch's start is unaccounted for. if pending_call: raise StaleResumptionCursor( f"epoch boundary at {presented.epoch}:{boundary} precedes new epoch " f"{server_epoch}; tail unaccounted, cannot prove completeness." ) return SessionFrame(Cursor(server_epoch, server_last_seq), server_last_seq) ```