# Which invariants prevent silent event-loss when an MCP streamable-SSE client resumes across a rotated session token **Date of Record:** 2026 November 28 **Scope:** Applies to MCP servers using the HTTP-native streamable transport with `Last-Event-ID` replay and a server-issued `Mcp-Session-Id` header. Does not apply to stdio transport, nor to single-connection SSE without resumption, where no cross-request cursor exists. ## Core Distinction The failure people architect for is *reconnection*: the SSE stream drops, the client reconnects with `Last-Event-ID`, the server replays from its ring buffer, and execution continues. The failure that actually bites is *resumption across a session-identity rotation*. These are different problems and they are routinely conflated. Reconnection preserves the session. Resumption-after-rotation crosses a session boundary: the server has expired or reissued the `Mcp-Session-Id` (idle TTL, deploy, load-balancer stickiness loss), and a *new* session is minted while the client still holds an event cursor (`Last-Event-ID: 4471`) from the *old* session's event space. The cursor is a position in a per-session monotonic sequence. The new session starts its sequence at 0. So the client presents a cursor that is *ahead of* the new session's head, and the server has a choice: reject the cursor, clamp it, or — the dangerous case — treat "cursor > head" as "client is caught up, send nothing." That third branch is the boundary failure. The client believes it has resumed; the server believes the client is current; the two event spaces are unrelated; and the events that occurred in the gap (tool-call results, `notifications/message`, progress updates, and critically the terminal `result` of an in-flight request) are lost with no error on either side. ## What Was Observed Trace from a reproduction against an MCP server with a 300s session idle TTL and a 1024-event replay ring: 1. Client opens session `S1`, receives `Mcp-Session-Id: S1`, opens SSE stream, consumes events `1..4471` on a long-running `tools/call`. 2. Network partition for 310s. Server GCs session `S1`; its event ring and its in-flight request state are dropped. 3. Client reconnects with `Mcp-Session-Id: S1` and `Last-Event-ID: 4471`. Server does not find `S1`, so per the spec's "session not found" path it returns `404`. Many client implementations treat `404` on the *stream* endpoint as "stream endpoint moved / retry," not "session gone," and re-issue the request *without* clearing the cursor. 4. Retry lands on a fresh backend that mints `S2` and starts its sequence at `0`. The request carries `Last-Event-ID: 4471` against `S2`. 5. Server's resume logic: `if last_event_id >= head: return` (nothing to replay). `4471 >= 0` is true. Server sends the SSE `200` headers and then *nothing* — an open, silent stream. 6. Client's request `r-9f2` (the `tools/call`) had its result emitted as event `4473` in `S1`. That event does not exist in `S2`. The client waits on an open stream that will never carry the result. After its own request timeout (often minutes), it retries the *tool call itself* — a duplicate side effect — or hangs. The tell is asymmetry of belief: client is at "waiting for ≥4472," server is at "nothing to send, you're current." Both are internally consistent. Neither is correct. ## Condition of Validity The invariant that must hold for resumption to be sound is: > An event cursor is only meaningful within the event space identified by the session token it was issued under. A cursor MUST NOT be presented against a session token that did not issue it. The spec implies this but does not enforce it at the wire level, because `Last-Event-ID` and `Mcp-Session-Id` are independent headers with no cryptographic or structural binding between them. The server cannot tell "cursor 4471 belongs to S1" from "cursor 4471 belongs to S2" — it only sees two opaque strings. Soundness therefore depends on the *client* never crossing the two, and on the *server* refusing to treat a foreign cursor as a valid position. The condition of validity is narrow: resumption is safe **iff** (a) the session token is unchanged since the cursor was issued, **or** (b) the server can prove the cursor's event space matches the presented session (e.g., cursor encodes a session-namespace prefix or a signed epoch). Absent (a) or (b), any "cursor ≥ head ⇒ caught up" shortcut is unsound. ## Decision Boundary The server, on receiving `(session, last_event_id)`, sits on a boundary it must resolve explicitly rather than by comparison: - **Cursor < head, same session:** normal replay. Sound. - **Cursor == head:** caught up. Sound *only if* the session is the issuing session. - **Cursor > head:** ambiguous. Two real cases: (i) client is ahead because *this* session already advanced and the ring wrapped (legitimate — replay from ring start, flag gap), or (ii) client carries a foreign cursor (illegitimate — must reject). Comparing integers cannot distinguish them. The boundary decision must be made on session identity, not cursor arithmetic. - **Session unknown / expired:** must surface as an explicit, non-retryable session-invalid signal that forces the client to *drop its cursor and re-establish request state*, not a generic `404` that retry logic swallows. The guardrail is: **the cursor and the session token must be validated as a pair before any positional comparison.** A cursor whose session cannot be confirmed as its issuer is a protocol error, not a resume hint. ## Operational Effect Without the invariant, the failure mode is *silent event loss with duplicate side effects*: the client neither errors nor resumes, its in-flight request result is dropped, and its eventual retry re-executes a non-idempotent tool call. This is worse than a hard failure because it corrupts state quietly and only manifests as a downstream inconsistency (double-charged payment, duplicated file write, forked agent branch) minutes later. Two concrete guards close it. First, bind the cursor to the session: prefix event IDs with the session epoch (`S2:0`, `S2:1`, …) or sign them, so a foreign cursor fails an equality check instead of passing a `>=` check. Second, make session-invalid an explicit typed error that instructs the client to reset `Last-Event-ID` and re-drive the request from a known-good checkpoint — not a bare `404` that generic retry treats as transient. The client-side complement: never carry `Last-Event-ID` across a `Mcp-Session-Id` change; treat a new session token as a full state reset and re-issue the request with a fresh idempotency key. The general lesson: any resumption protocol that separates the *position cursor* from the *namespace identity* it indexes into will eventually cross them. The invariant is that the two must be validated jointly, and that "caught up" must be a claim the server can only make about a session it can prove issued the cursor. ```python class ForeignCursorError(RuntimeError): """Raised when an event cursor is presented against a session that did not issue it.""" pass def resume_stream(session_id: str, last_event_id: str, sessions: dict) -> list: """Resolve an MCP streamable-SSE resume request. Event IDs are namespaced as ':'. A cursor is only valid against the session encoded in its own prefix. """ if last_event_id is None: return [] if ":" not in last_event_id: raise ForeignCursorError( f"unbound cursor {last_event_id!r}: no session namespace, cannot validate" ) cursor_session, seq_str = last_event_id.split(":", 1) try: seq = int(seq_str) except ValueError: raise ForeignCursorError(f"malformed cursor sequence in {last_event_id!r}") if cursor_session != session_id: # The core guard: never compare positions across event spaces. raise ForeignCursorError( f"cursor {last_event_id!r} belongs to session {cursor_session!r}, " f"presented against {session_id!r}; client must reset cursor and re-drive request" ) state = sessions.get(session_id) if state is None: raise ForeignCursorError( f"session {session_id!r} unknown/expired; cursor {last_event_id!r} is unverifiable" ) head = state["head"] ring = state["ring"] if seq > head: # Same session but ahead of head: ring wrap. Replay from ring start, flag gap. return list(ring) return [e for e in ring if e["seq"] > seq] ```