# When must an instance refuse to resume an MCP stream: the Last-Event-ID replay-divergence boundary **Date of Record:** 2026 November 30 **Scope:** Applies to MCP servers/clients using the HTTP-native streaming transport (SSE over HTTP with `Last-Event-ID`-based resumption) where a client reconnects mid-stream after a dropped connection. Does not apply to stdio transport, nor to stateless request/response MCP calls that carry no resumable event log. ## Core Distinction The tempting invariant is: *"resumption is safe because the server replays every event with an ID greater than the client's `Last-Event-ID`."* This is false. Resumption is safe only if the server can prove that the **event log it is replaying from is the same logical stream generation** the client's `Last-Event-ID` was minted in. The non-obvious boundary is that event IDs are monotonic *within a generation* but not *across generations*. When a stream is re-established after a server-side restart, a load-balancer reroute, or a compaction of the event buffer, the new generation's ID counter can overlap the old generation's numeric range. A naive `id > last_event_id` comparison then silently drops every event in the overlap window and replays none of them — the client believes it is caught up while it is missing the exact events (typically the terminal `result` or `error` of a tool call) that carry the outcome. The failure is not a timeout, not a 5xx, and not a schema mismatch. It is a **silent continuity violation**: the stream resumes, the connection is healthy, the client's parser is happy, and the agent proceeds with a truncated view of its own tool execution. ## What Was Observed A long-running agent invoked an MCP tool (`db.migrate`) that streamed progress events `e1…e47`, then the terminal `e48` carrying `{status: "ok", applied: 47}`. The HTTP connection dropped between `e40` and `e41` (proxy idle timeout, 60s). The client reconnected with `Last-Event-ID: 40`. In the intervening 4 seconds, the MCP server process had been restarted by its supervisor (OOM kill on a sibling tool). The new process re-initialized its per-session event buffer with a fresh counter starting at `1`. By the time the client reconnected, the server had emitted `e1…e9` of *a different logical stream* (a new `db.migrate` invocation, triggered by a retry from a second agent instance against the same session ID). The server's resumption handler executed the canonical comparison: ``` replay = [e for e in buffer if e.id > last_event_id] # last_event_id = 40 ``` The buffer held IDs `1…9`. No event satisfied `id > 40`. The server returned `200 OK` with an empty event stream and immediately closed. The client interpreted this as "resumption complete, I was already caught up," and the agent advanced to the next step of its plan with `applied` unset. The migration had, in fact, partially applied and then been re-run by the second instance — the agent's next action (`db.verify`) ran against a schema in an inconsistent intermediate state. The trace, compressed: ``` client: GET /mcp/session/S7/stream Last-Event-ID: 40 server: 200 OK, text/event-stream server: (buffer = [e1..e9 of generation 2], filter id>40 → empty) server: (stream closed) client: onclose → state = RESUMED_CLEAN agent: next_step(db.verify) # assumes e48 was seen ``` The client's `RESUMED_CLEAN` transition is the poison. It is reached by the absence of events, which the protocol does not distinguish from the absence of *new* events. ## Condition of Validity `Last-Event-ID` resumption is valid **iff** the server can establish generation identity for the ID. Concretely, at least one of the following must hold: 1. **Generation-qualified IDs.** Event IDs are opaque tokens of the form `.` (e.g., `g7.40`), and the server rejects a `Last-Event-ID` whose generation does not match the current one with `409 Conflict` (or `412`), forcing the client into a full re-fetch rather than a silent empty replay. 2. **Monotonic global counter with no reset.** IDs are drawn from a durable, process-independent counter (e.g., a database sequence) that never resets across restarts, so `id > last_event_id` is a valid predicate across generations. 3. **Replay-completeness assertion.** The server, on resumption, asserts that it can produce a contiguous run from `last_event_id + 1` to the current head. If the buffer's minimum ID is greater than `last_event_id + 1`, it must respond `410 Gone` (the events are unrecoverable) rather than `200` with an empty body. The invariant: **resumption must be able to fail loudly.** An empty replay is never evidence of a complete stream; it is only evidence that no event in the current buffer matched the predicate. Those are different propositions and the protocol must not conflate them. ## Decision Boundary The boundary is the comparison between the client's `Last-Event-ID` and the server buffer's **minimum retained ID**, not its maximum. - If `last_event_id >= min_buffer_id - 1` **and** generation matches: replay `id > last_event_id`. Safe. - If `last_event_id < min_buffer_id - 1`: a gap exists in the retained log. The server cannot prove continuity. Must return `410 Gone`, and the client must re-initialize the stream (re-invoke the tool or re-fetch state), not advance. - If generation does not match: the IDs are incomparable. Must return `409 Conflict`. The client must treat the prior stream as **lost**, not **resumed**, and must not assume any event from the prior generation was delivered. The subtle case is the second: a gap of exactly zero events is indistinguishable from a gap of many if the server only looks at "did anything match `id > last_event_id`." The `min_buffer_id` check is the only thing that distinguishes them, and it is the check that the canonical resumption snippet omits. ## Operational Effect An agent that treats empty replay as clean resumption will, under server restart or buffer compaction, proceed with a stale or missing terminal event and act on it. The failure surfaces downstream — a `db.verify` against a half-migrated schema, a `file.write` that overwrites a result the agent thinks it read — and is attributed to the *downstream* tool, not to the resumption. This makes it expensive to diagnose: the resumption log shows `200 OK`, the client log shows `RESUMED_CLEAN`, and the corruption appears three steps later. The guardrail is to make the resumption handler incapable of returning a clean empty stream. It must either replay a contiguous run or raise. The client must map `410`/`409` to a `STREAM_LOST` state that triggers re-initialization, and must never map an empty `200` to `RESUMED_CLEAN`. ```python from dataclasses import dataclass from typing import Optional class StreamResumptionDivergence(RuntimeError): """Raised when a Last-Event-ID cannot be proven contiguous with the retained log.""" @dataclass(frozen=True) class Event: generation: str seq: int payload: dict @property def token(self) -> str: return f"{self.generation}.{self.seq}" @dataclass(frozen=True) class ResumeRequest: session_id: str last_event_id: Optional[str] # None on first connect def parse_token(token: str) -> tuple[str, int]: gen, _, seq = token.partition(".") if not gen or not seq.isdigit(): raise StreamResumptionDivergence(f"malformed Last-Event-ID: {token!r}") return gen, int(seq) def resume_stream( req: ResumeRequest, buffer: list[Event], current_generation: str, ) -> list[Event]: """Return events to replay, or raise if continuity cannot be proven. Invariant: an empty return is only legal when the client is provably caught up to the head of the *same* generation. """ if not buffer: # No retained events. If the client claims a position, we cannot # prove it exists. Refuse rather than replay nothing. if req.last_event_id is not None: raise StreamResumptionDivergence( f"session {req.session_id}: empty buffer, cannot honor " f"Last-Event-ID={req.last_event_id!r}" ) return [] if req.last_event_id is None: # Fresh connect: replay the whole retained buffer. return list(buffer) last_gen, last_seq = parse_token(req.last_event_id) if last_gen != current_generation: raise StreamResumptionDivergence( f"session {req.session_id}: Last-Event-ID generation {last_gen!r} " f"!= current generation {current_generation!r}; stream is lost, " f"not resumable" ) min_seq = min(e.seq for e in buffer if e.generation == current_generation) # The boundary: a gap between the client's position and the oldest # retained event means events were dropped. Replay would be incomplete. if last_seq + 1 < min_seq: raise StreamResumptionDivergence( f"session {req.session_id}: gap between Last-Event-ID seq " f"{last_seq} and oldest retained seq {min_seq}; " f"{min_seq - last_seq - 1} event(s) unrecoverable" ) replay = [e for e in buffer if e.generation == current_generation and e.seq > last_seq] # Contiguity assertion: the replay must be exactly the run the client # is missing, with no holes. expected = list(range(last_seq + 1, last_seq + 1 + len(replay))) actual = [e.seq for e in replay] if actual != expected: raise StreamResumptionDivergence( f"session {req.session_id}: non-contiguous replay " f"expected {expected}, got {actual}" ) return replay ```