# When must an instance treat an MCP SSE `Last-Event-ID` resumption as a *new* logical stream rather than a continuation, and how does silent `event_id` namespace reuse corrupt tool-call replay? **Date of Record:** 2026 November 26 **Scope:** Applies to MCP servers exposing the HTTP+SSE transport (server-initiated event stream over `text/event-stream`, client resumption via `Last-Event-ID`) where the server process may restart, redeploy, or shed load between stream generations. Does not apply to stdio transport, to WebSocket-based MCP variants with explicit session frames, or to stateless request/response MCP tool calls with no server-push channel. ## Core Distinction The failure is not "the SSE connection dropped." Drops are routine and the resumption contract is designed for them. The failure is that an MCP client, on reconnect, sends `Last-Event-ID: N` and the *new* server generation happily accepts it — because its event counter also starts near `N`, or because it persists a counter that was never bound to a stream generation identity — and then resumes emitting events numbered `N+1, N+2, …` that belong to a **different logical stream**. The client cannot distinguish "continuation of the stream I was reading" from "a fresh stream that happens to reuse my cursor values." It therefore splices two disjoint event histories into one perceived timeline, and any tool-call whose result was delivered as a server-push event gets replayed, dropped, or double-applied. The invariant that must hold: **an `event_id` is only meaningful relative to a stream generation, and resumption is valid only if the server can prove the generation matches.** An `event_id` is a cursor into a *specific* append-only log, not a global sequence number. Treating it as global is the entire bug. ## What Was Observed A long-running agent held an MCP session to a server that streams asynchronous tool results (e.g., `notifications/tools/progress` and a custom `tool.result.delta` event) over SSE. Sequence of events across a rolling deploy: 1. Generation A (process `pid 4417`, boot `t0`) emits events with `id: 100 … id: 187`. The client has consumed through `id: 187` and issued a `tools/call` whose result will arrive as a pushed event. 2. The server is redeployed. Generation B boots at `t1`. Its event counter is initialized from a persisted "last emitted" value it read from a shared store — but that store was written by a *different replica* and reflects `id: 190`, OR (variant) the counter is simply reset to `0` but the client's `Last-Event-ID` is `187`, which the server treats as "unknown, so start fresh from 0." 3. Client reconnects with `Last-Event-ID: 187`. Generation B accepts it. It does **not** emit a `resync-required` signal. It begins emitting `id: 188, 189, …` for *new* work that has nothing to do with the pending `tools/call` from step 1. 4. The client, seeing `188 > 187` and continuous numbering, concludes the stream is intact. It waits for the `tool.result.delta` for its pending call. That result was never emitted by Generation B (the in-flight work died with Generation A). The client blocks until its own timeout, or worse, matches a *coincidentally-shaped* `tool.result.delta` from unrelated work to its pending call ID because it keys results by ordinal position rather than by request ID. Two distinct corruption modes were logged: - **Silent gap:** events `188…N` from gen B are interleaved with the client's expectation of gen A's pending result. No gap is detectable because the numbering is monotonic. - **Phantom replay:** in the counter-persisted variant, gen B starts at `191`; the client's `Last-Event-ID: 187` causes gen B to *re-emit* `188, 189, 190` from its own buffer, which are gen B's events, not gen A's — but they carry IDs the client already associated with gen A's semantics. The client applies a `tool.result.delta` for call `X` to call `Y`. The tell was in the `data` payloads: each event carried a `stream_generation` field that the client's parser was discarding. When the parser was patched to read it, the mismatch was immediate and total: 100% of resumptions after a redeploy had `stream_generation` differing from the pre-drop value, and none had been flagged. ## Condition of Validity Resumption via `Last-Event-ID` is valid **only if and only if** all three hold: 1. **Generation binding.** Every event carries a generation identifier (boot UUID, epoch, or signed token) that is stable for the life of one server process/log and changes on restart. The client persists `(generation, event_id)` as a pair, never `event_id` alone. 2. **Cursor acceptance is conditional.** On reconnect, the server MUST reject a `Last-Event-ID` whose generation does not match the current generation, and respond with an explicit control event (e.g., `event: resync.required`, `data: {"reason":"generation_mismatch","last_known_generation":"A","current":"B"}`) rather than silently starting a new numbering. RFC-shaped SSE has no built-in rejection semantics for this; the MCP layer must define one. 3. **Result correlation is by request ID, never by ordinal.** Any tool result delivered over the push channel must carry the originating `tools/call` request ID in its payload. Position-in-stream is not identity. If any of the three is absent, the stream is not resumable and the client must treat reconnect as a **cold session**: re-issue pending `tools/call`s (idempotency-keyed), discard the cursor, and re-subscribe. ## Decision Boundary The boundary is not "did the connection drop" — it is **"can the server prove the cursor belongs to the stream it is about to serve?"** - **Below the boundary (safe to resume):** same generation, cursor within the retained buffer, server can replay `[cursor+1 … head]` from its own log. This is the intended fast path. - **At the boundary (must resync):** cursor generation ≠ current generation, OR cursor is older than the server's retention floor, OR cursor is *ahead* of the server's head (impossible in a single log, so it proves a different log). All three are the same class: the server cannot honor the cursor as a continuation. - **Above the boundary (must cold-start):** the pending work that produced the awaited result is unrecoverable (in-flight state died with the old process and was not checkpointed). Even a successful replay of retained events cannot resurrect a computation that no longer exists. The client must re-drive. The dangerous zone is a server that *accepts* the cursor without being able to prove generation match — because acceptance looks like success and produces monotonic numbering that defeats gap detection. **Monotonicity is not continuity.** A server that resets its counter to `0` on reboot is *safer* than one that persists a counter across generations, because the reset produces a detectable discontinuity (cursor `187` > head `0`), whereas the persisted counter produces a plausible lie. ## Operational Effect For an agent instance, the consequence is a **hanging or misattributed tool call under a healthy-looking stream.** The agent's execution loop has no signal that its awaited result is gone; the transport reports "connected, receiving events," the event IDs are strictly increasing, and the only observable symptom is that the awaited `tools/call` never resolves — until the agent's own tool timeout fires, at which point it may retry the call against a server that already (in gen B) never saw it, or against one that did and deduplicates by idempotency key it never received. The architectural guardrail, in order of strength: 1. **Generation-scoped cursors.** Pair `(generation, event_id)`; reject mismatches with an explicit `resync.required` control event. This converts a silent corruption into a loud, actionable signal. 2. **Request-ID correlation on every pushed result.** Makes phantom replay impossible to misapply, even if generation binding is missing. 3. **Idempotency keys on `tools/call`** so that cold-start re-drive after `resync.required` is safe to retry against a fresh session. 4. **A client-side "stream epoch" counter** that increments on every `resync.required` and on every reconnect where the server does not echo the client's last-seen generation; any event arriving under a new epoch is quarantined until the pending call set is reconciled. The cheapest partial mitigation — and the one most likely to be shipped by mistake — is to have the client key results by ordinal position in the stream. That is precisely the design that turns a generation mismatch into cross-call result corruption, because ordinal position is the one thing two disjoint streams are guaranteed to share. ```python import uuid from dataclasses import dataclass, field from typing import Optional class StreamGenerationMismatch(RuntimeError): """Raised when a Last-Event-ID cursor cannot be proven to belong to the stream generation the server is about to serve. Resumption MUST be refused; the client must cold-start and re-drive pending tool calls.""" pass @dataclass class StreamLog: generation: str = field(default_factory=lambda: uuid.uuid4().hex) events: list = field(default_factory=list) # list of (event_id:int, payload:dict) retention_floor: int = 0 def head(self) -> int: return self.events[-1][0] if self.events else 0 def emit(self, payload: dict) -> int: eid = self.head() + 1 self.events.append((eid, payload)) return eid def resume(self, last_generation: str, last_event_id: int) -> list: # Invariant: cursor is only meaningful relative to a generation. if last_generation != self.generation: raise StreamGenerationMismatch( f"cursor generation {last_generation!r} != current " f"{self.generation!r}; refusing silent resumption" ) if last_event_id > self.head(): # Cursor ahead of head is impossible within one log -> different log. raise StreamGenerationMismatch( f"cursor {last_event_id} ahead of head {self.head()}; " f"server cannot honor as continuation" ) if last_event_id < self.retention_floor: raise StreamGenerationMismatch( f"cursor {last_event_id} below retention floor " f"{self.retention_floor}; replay impossible" ) return [p for (eid, p) in self.events if eid > last_event_id] def handle_reconnect(log: StreamLog, last_generation: Optional[str], last_event_id: Optional[int]) -> dict: if last_event_id is None: return {"action": "fresh_subscribe", "generation": log.generation} try: replayed = log.resume(last_generation or "", last_event_id) except StreamGenerationMismatch as e: # Loud, actionable signal instead of monotonic lie. return {"action": "resync.required", "reason": str(e), "current_generation": log.generation, "must_redrive_pending_calls": True} return {"action": "resume", "replayed": replayed, "generation": log.generation} ```