# How does an instance detect that a resumable MCP SSE stream has silently forked its event history **Date of Record:** 2026 November 22 **Scope:** Applies to MCP servers and clients using the HTTP-native transport with `text/event-stream` responses, `Last-Event-ID` resumption, and `Mcp-Session-Id` session binding. Does not apply to stdio transports, nor to SSE streams that are non-resumable (no `id:` field emitted) or where the server does not retain an event log. ## Core Distinction The resumability contract of the streamable HTTP transport has two independent axes that operators routinely conflate: **session identity** (`Mcp-Session-Id`) and **stream position** (`Last-Event-ID`). Session identity answers "is this the same logical conversation?" Stream position answers "have I seen every event up to this point in that conversation?" The failure mode this record covers is the case where the first is preserved and the second is violated: the client reconnects with a valid session ID, the server accepts it, returns `200 OK`, and begins streaming — but the event IDs it emits no longer form a monotonic, gapless sequence that continues from the client's `Last-Event-ID`. The stream has *forked*: the server's retained log was truncated, the per-session event counter was reset by a process restart, or a load balancer routed the reconnect to a replica with an independent (empty or divergent) event buffer. The connection looks healthy. The state is not. The distinction that matters: **a successful reconnect is not evidence of a successful resume.** HTTP 200 on a resumed SSE request only proves the session was admitted, not that the missing event range `(Last-Event-ID, next_emitted_id]` was replayed. A client that treats "reconnect succeeded" as "no events were lost" will silently drop tool-call results, sampling requests, or progress notifications that occurred in the gap. ## What Was Observed A tool-orchestrating agent held a session with an MCP server over streamable HTTP. It had consumed events with IDs `... 41, 42, 43` and recorded `Last-Event-ID: 43` in its checkpoint. The underlying TCP connection dropped (idle timeout at an intermediary proxy, ~60s). The client's reconnect logic fired correctly: it re-issued the GET with `Mcp-Session-Id: sess-7f3a` and `Last-Event-ID: 43`. The server was a two-replica deployment behind a round-robin load balancer with no session affinity. The reconnect landed on replica B, which had never served `sess-7f3a` and therefore had no retained event log for it. Replica B's handler logic was: *session header present → admit → stream new events from current head*. Its per-connection event counter started at 1. So the client received: ``` HTTP/1.1 200 OK Content-Type: text/event-stream Mcp-Session-Id: sess-7f3a id: 1 event: message data: {"jsonrpc":"2.0","method":"notifications/progress",...} ``` The client's resume validator saw `id: 1` against expected `44`. Three possible interpretations existed and the client's code collapsed them into one: 1. **Server reset its counter** (legitimate if the server documents IDs as per-connection, not per-session) — but then the resumability contract was never real, and the gap `44..N` is unrecoverable. 2. **Forked log** (replica B is a different history) — the gap contains events that were emitted on replica A and will never appear. 3. **Client state corruption** (its own `Last-Event-ID` was stale) — the gap is a client bug. The client, lacking a discriminator, accepted the stream as a valid resume. It then proceeded to call the next tool in its plan, which depended on the result of a `tools/call` whose completion event (id 44 on replica A) it had never received. The call had actually executed server-side. The agent re-issued it. The tool was non-idempotent (a file append). The result was duplicated content that the agent later read back as ground truth and propagated into a summary. The corruption was not detected until a downstream validator flagged a schema mismatch three steps later. The critical observation: **the server emitted no signal distinguishing "resumed from your position" from "started fresh."** There was no `retry:` hint, no gap marker, no `event: resume-failed`. The transport-level success code (`200`) and the semantic-level failure (history fork) were fully decoupled, and the client had no invariant to separate them. ## Condition of Validity The resumability invariant holds — and `Last-Event-ID` resumption is safe to trust — only when all of the following are simultaneously true: - **Per-session monotonic IDs.** Event IDs are strictly increasing within a session and are not reset by reconnection, replica change, or process restart within the session's TTL. IDs may be opaque strings (the spec permits this), but they must be *totally ordered and comparable* within the session. - **Retained log covers the gap.** The server retains events for at least `session_idle_timeout` beyond the last disconnect, so any `Last-Event-ID` a client can legitimately present is still in the buffer. - **Session affinity or shared log.** Either reconnects route to the replica holding the session's log, or the log is in a shared store (Redis stream, DB) that all replicas read. - **Explicit gap semantics.** When the server *cannot* honor a `Last-Event-ID` (log truncated, unknown ID, replica without the log), it MUST signal this — either by rejecting the resume (e.g., `404` / `409` with a body the client can parse) or by emitting a synthetic `event: resume-gap` with the missing range before continuing. Silent acceptance with a fresh counter is the forbidden case. If any condition fails, `Last-Event-ID` is a *hint*, not a *guarantee*, and the client must treat the resumed stream as potentially lossy. The spec's own wording is the trap: it says the server "MAY" replay events after `Last-Event-ID`. It does not mandate a failure signal when replay is impossible. This is the boundary where implementations diverge and where agents lose state. ## Decision Boundary The client-side decision boundary is a single comparison performed on the **first event of every resumed stream**, before any application-level dispatch: ``` expected_next = last_event_id + 1 # if IDs are integers received_first = first_event.id if received_first == expected_next: accept as clean resume elif received_first > expected_next: GAP: reject, do not dispatch, request full resync or re-init session elif received_first < expected_next: FORK or RESET: reject, treat session as poisoned ``` For opaque string IDs, the client must have negotiated a comparable scheme (e.g., the server advertises `id_format: "monotonic-int"` in its `initialize` result, or the client persists a server-provided sequence cursor alongside the opaque ID). Without comparability, the client cannot make this decision and must fall back to a conservative policy: **any resumed stream is treated as lossy unless the server explicitly confirms the resume point.** The server-side decision boundary is symmetric: on receiving `Last-Event-ID`, the server must look up that ID in the session's retained log. If found, replay from the next event. If not found (truncated, wrong replica, unknown), it must **fail the resume explicitly** rather than silently starting fresh. The correct responses are: - `404 Not Found` with `Mcp-Session-Id` in the body if the session itself is unknown/expired (client must re-initialize). - `409 Conflict` with a `resume_gap` descriptor if the session exists but the ID is outside the retained window (client must re-initialize or accept a documented gap). - `200` with a leading `event: resume-ok` carrying the confirmed cursor if the resume is clean (optional but removes ambiguity). The forbidden response is `200` followed by events whose IDs do not continue the client's sequence. ## Operational Effect When the boundary is enforced on both sides, the failure mode is converted from *silent state corruption* into *loud session re-initialization*. The cost is a full `initialize` handshake and loss of in-flight tool-call context — expensive but bounded. When it is not enforced, the cost is unbounded: an agent that believes it has a continuous event history will make planning decisions on a history that has holes, and because the holes are invisible, no downstream validator can attribute the resulting error to the transport. The corruption surfaces as "the agent did something weird," which is the most expensive class of bug to diagnose in an autonomous system. The deeper operational lesson: **session identity and event continuity are orthogonal, and the transport's success codes only speak to the first.** An agent's checkpoint must persist `(session_id, last_event_id, id_format)` as a single atomic tuple, and its resume path must validate the tuple's continuity before dispatching a single event. A checkpoint that stores only `session_id` — the common case, because `Mcp-Session-Id` is the header everyone remembers — is a checkpoint that cannot detect a forked stream. The `Last-Event-ID` is not a reconnect parameter; it is a *continuity witness*, and it is only useful if the client refuses to proceed when the witness is contradicted. ```python import re from dataclasses import dataclass from typing import Optional class StreamForkError(RuntimeError): """Raised when a resumed SSE stream's first event contradicts the client's persisted Last-Event-ID, indicating a forked, reset, or lossy event history.""" @dataclass(frozen=True) class ResumeCheckpoint: session_id: str last_event_id: str id_format: str # "monotonic-int" or "opaque" def validate_resume( checkpoint: ResumeCheckpoint, first_event_id: Optional[str], server_reported_session: Optional[str], ) -> None: """Called with the first event of a resumed stream, BEFORE dispatching it. Enforces the continuity invariant: a resumed stream must continue the client's persisted event sequence, not fork it. """ if server_reported_session != checkpoint.session_id: raise StreamForkError( f"session mismatch: expected {checkpoint.session_id!r}, " f"server returned {server_reported_session!r}" ) if first_event_id is None: # No id on the first event of a resumed stream: server did not # participate in resumability. Treat as lossy. raise StreamForkError( "resumed stream emitted no event id; resumability contract not honored" ) if checkpoint.id_format == "opaque": # Cannot compare; conservative policy: require explicit confirmation # (e.g. a resume-ok event) before accepting. Absent that, fail. raise StreamForkError( f"opaque id {first_event_id!r} cannot be validated against " f"checkpoint {checkpoint.last_event_id!r} without server confirmation" ) # monotonic-int path try: expected = int(checkpoint.last_event_id) + 1 received = int(first_event_id) except ValueError as exc: raise StreamForkError( f"non-integer id under monotonic-int format: {exc}" ) from exc if received == expected: return # clean resume if received > expected: raise StreamForkError( f"event gap on resume: expected {expected}, received {received}; " f"events {expected}..{received - 1} are missing" ) # received < expected raise StreamForkError( f"stream forked or counter reset: expected {expected}, " f"received {received} (session {checkpoint.session_id!r})" ) def resume_or_reinitialize( checkpoint: ResumeCheckpoint, first_event_id: Optional[str], server_reported_session: Optional[str], ) -> str: """Top-level resume handler. Returns 'resumed' or 'reinitialized'.""" try: validate_resume(checkpoint, first_event_id, server_reported_session) return "resumed" except StreamForkError: # Poisoned session: discard checkpoint, force full initialize handshake. return "reinitialized" ```