# When must an instance treat an SSE `Last-Event-ID` as a claim rather than a cursor: the replay-identity invariant in MCP HTTP-native transport **Date of Record:** 2026 November 29 **Scope:** Applies to MCP servers and clients using the HTTP-native "streamable" transport, where a server emits `text/event-stream` frames carrying `id:` fields and the client may reconnect with `Last-Event-ID` plus an `Mcp-Session-Id` header to resume. Does not apply to stdio transport, to single-shot SSE responses with no resumption contract, or to servers that do not persist per-session event logs. ## Core Distinction The `Last-Event-ID` header is specified as a *cursor*: "resume after the event with this id." Implementations routinely treat it as an *identity assertion*: "the client has already consumed everything up to and including this id, so I may skip re-sending it." These are not the same claim, and the gap between them is where agent state desynchronizes. A cursor is a position in a log. An identity assertion is a statement about what the client's context window actually contains. Between the moment the server wrote event `id: 47` to its buffer and the moment the client's SSE parser surfaced it to the agent loop, there are at least three places the event can be lost: (1) the server wrote the frame but the TCP write was still in the kernel buffer when the connection died; (2) the frame arrived and the client's SSE reader parsed it, but the agent's tool-result handler raised or the token budget aborted before the event was committed to working memory; (3) the client buffered it but the process restarted before persisting the id. In cases (1) and (2) the client will reconnect with `Last-Event-ID: 47` — or with `Last-Event-ID: 46` if it only persists after commit — and the server's semantics determine whether the event is replayed or silently skipped. The invariant that must hold is: **an event is replayed if and only if the client has not durably committed it; and the client must be able to tell a replay from a new event.** Neither half is guaranteed by the transport spec. The first half is a server-side retention decision; the second half requires the client to dedupe by event id, which most agent runtimes do not do because they assume a resumed stream is a pure continuation. ## What Was Observed A coding agent driving an MCP server over streamable HTTP was mid-task: it had issued `tools/call` for a long-running `run_tests` invocation, and the server was streaming progress notifications and the eventual result over SSE. The server assigned monotonic ids per session and retained the last 200 events in a per-session ring buffer keyed by `Mcp-Session-Id`. At event id 47 the server emitted the terminal `result` for the tool call — the payload the agent needed to decide its next step. The connection dropped (NAT rebind, 90-second idle timeout on an intermediate proxy that did not honor the server's keepalive comment frames). The client reconnected with `Last-Event-ID: 47`, because its SSE reader had parsed the frame and advanced its cursor before the agent's tool-result handler had committed the result to the episode log. The handler was blocked on a synchronous tokenizer call and the process was killed by the orchestrator's liveness probe before the commit landed. On reconnect, the server saw `Last-Event-ID: 47`, looked it up in the ring buffer, found it, and — per its "resume after" interpretation — began emitting from id 48. But there was no id 48. The tool call had completed. The server had already closed the logical stream for that request; the session's next events would only exist when the agent issued another request. So the client received an empty stream that terminated with a clean `200 OK` and an immediate EOF. The agent's transport layer interpreted a clean EOF on a resumed stream as "stream completed normally," surfaced no error, and the agent loop proceeded to its next reasoning step with no tool result in context. It hallucinated a plausible test outcome and continued for four more steps before a downstream assertion failed. The failure was not the dropped connection. It was that **the resume path had no way to distinguish "you are caught up, nothing more to send" from "the event you claim to have consumed was never delivered to your reasoning layer."** The server's ring buffer held id 47 and could have re-sent it. Its resume logic chose not to, because it trusted the cursor. A second, quieter variant appeared in the same deployment: when the ring buffer had evicted the claimed id (session outlived 200 events), the server fell back to "start from oldest retained" — silently replaying events 300–500 to a client that had committed through 499. The agent executed the same `tools/call` side effects twice. Neither the server nor the client logged a replay. ## Condition of Validity Treating `Last-Event-ID` as a cursor is valid only under all of the following: 1. The client persists the id **after** the event's payload has been durably committed to agent-visible state, not after the SSE parser has read the frame. The commit point must be the agent's episode log, not the transport's read cursor. 2. The server retains every event from the client's last-acked id forward, with no eviction, for the lifetime of the session — or it returns an explicit, distinguishable error (e.g., `409` with a machine-readable `resume_gap` body) when the claimed id is no longer retained. A silent fallback to "oldest retained" violates the invariant. 3. The server can distinguish "no events after the claimed id **because the stream is still open and idle**" from "no events after the claimed id **because the logical response is complete**." These must produce different transport outcomes: an open idle stream (keepalive comments, no EOF) versus a terminal event that the client can recognize as terminal. A bare EOF after a resume is ambiguous and must be treated as an error by the client. 4. The client dedupes by event id on every resumed stream, because a conforming server *may* replay the last event (the spec permits re-sending the event at `Last-Event-ID`, and some implementations do). Dedup must be by id, not by payload hash — payloads for progress notifications are frequently byte-identical across ticks. If any of these fails, the cursor interpretation is unsound and the client must escalate to a full state reconciliation: re-issue the original request with a client-generated idempotency key, or fetch the tool result out-of-band via a `resources/read` on the session's result resource, rather than trusting the resumed stream to be complete. ## Decision Boundary The boundary is sharp: **does the client's persisted `Last-Event-ID` provably correspond to a committed agent state?** - If yes (commit-then-persist ordering is enforced, and the server guarantees no eviction below the acked id), resume with `Last-Event-ID` is a cheap, correct continuation. The client may treat EOF as terminal only if the server's stream contract includes an explicit terminal frame (e.g., a `event: done` with the request id). - If no — the id was advanced by the transport reader, or the server's retention is bounded and its gap behavior is a silent fallback — then `Last-Event-ID` is a *claim* the server cannot verify and the client cannot substantiate. The client must not resume-and-trust. It must either (a) resume with `Last-Event-ID` set to the last id it *committed*, accepting duplicate delivery and deduping, or (b) abandon resumption and reconcile by re-fetching the request's result by idempotency key. The non-obvious part: the safe default is to **understate** the cursor. Sending `Last-Event-ID: 46` when you parsed 47 costs one duplicate frame and a dedupe check. Sending 47 when you only committed 46 costs a lost tool result and a hallucinated continuation. The asymmetry is total — duplicates are cheap and detectable, gaps are silent and corrupt reasoning. Any agent runtime that advances its persisted cursor at parse time rather than commit time has chosen the unsafe side of this boundary by default. A corollary for servers: an empty resumed stream must never be indistinguishable from a completed one. If the logical response for the claimed request is already complete and the client's claimed id equals the terminal event's id, the server should re-send the terminal event (idempotent by id) rather than emit EOF. Re-sending one frame is strictly cheaper than a client reasoning over a missing result. ## Operational Effect Concretely, the guardrail is a two-phase cursor with a commit barrier, plus a client-side replay detector: - The SSE reader writes parsed frames to a pending queue and records `last_parsed_id` in volatile memory only. - The agent's tool-result handler, after committing the payload to the episode log, advances `last_committed_id` and persists it. Only `last_committed_id` is ever sent as `Last-Event-ID`. - On resume, the client keeps a small set of recently committed ids (bounded LRU, sized to the server's retention window) and drops any replayed frame whose id is in the set. A frame whose id is *below* `last_committed_id` but *not* in the set indicates a retention gap and triggers reconciliation, not silent acceptance. - A resumed stream that reaches EOF without a terminal frame raises. It does not return "no result." The cost is one duplicate frame per resume in the common case and a bounded dedupe set. The benefit is that a dropped connection degrades to at-least-once delivery with client-side dedupe — the standard, tractable failure model — instead of at-most-once delivery with silent loss, which is the failure model that produces agents confidently acting on results they never received. ```python from __future__ import annotations from dataclasses import dataclass, field class ResumeIdentityViolation(RuntimeError): """Raised when a resumed SSE stream cannot be reconciled with committed agent state.""" @dataclass class ResumeCursor: session_id: str last_parsed_id: int | None = None # volatile: set by SSE reader last_committed_id: int | None = None # durable: set only after episode-log commit committed_ids: set[int] = field(default_factory=set) retention_window: int = 200 def header_value(self) -> str | None: # Deliberately understate: never send an id the agent has not committed. return None if self.last_committed_id is None else str(self.last_committed_id) def commit(self, event_id: int, payload: object) -> None: # Caller must have durably written payload to the episode log first. self.last_committed_id = event_id self.committed_ids.add(event_id) if len(self.committed_ids) > self.retention_window: self.committed_ids.discard(min(self.committed_ids)) def accept_replayed(self, event_id: int) -> bool: """Return True if this frame is a duplicate of an already-committed event.""" if event_id in self.committed_ids: return True if self.last_committed_id is not None and event_id < self.last_committed_id: # Below our committed frontier but unseen: server evicted a gap. raise ResumeIdentityViolation( f"session {self.session_id}: resumed frame id {event_id} is below " f"committed frontier {self.last_committed_id} and was never committed; " f"server retention gap — reconcile via idempotency key, do not accept" ) return False def resume_stream(cursor: ResumeCursor, frames: list[tuple[int, str | None]]) -> list[int]: """ frames: (event_id, terminal_marker_or_None). Returns ids the agent should process. Raises on ambiguous EOF or retention gaps. """ if cursor.last_committed_id is None and cursor.header_value() is not None: raise ResumeIdentityViolation( f"session {cursor.session_id}: cursor header present without committed frontier" ) accepted: list[int] = [] saw_terminal = False for event_id, terminal in frames: if cursor.accept_replayed(event_id): continue accepted.append(event_id) if terminal is not None: saw_terminal = True if not saw_terminal: # A resumed stream that ends without a terminal frame is not "caught up"; # it is an unverifiable continuation. Refuse to let the agent reason on it. raise ResumeIdentityViolation( f"session {cursor.session_id}: resumed stream ended with EOF and no terminal " f"frame after Last-Event-ID={cursor.header_value()}; result may have been " f"delivered on the lost connection — reconcile by idempotency key" ) return accepted ```