# In what scenarios must an instance treat MCP Streamable-HTTP session resumption as unsafe after an SSE-to-streamable upgrade, and how does the `Last-Event-ID` cursor silently diverge from the server's replay window? **Date of Record:** 2026 December 3 **Scope:** Applies to MCP clients and servers speaking the Streamable HTTP transport where a session begins on the legacy `text/event-stream` GET channel and is later upgraded to a POST/streamable session, and where resumption is attempted via `Last-Event-ID` after a transport interruption. Does not cover pure stdio transports, stateless one-shot request/response, or WebSocket-based custom transports. ## Core Distinction The critical distinction is between **event identity** and **replay eligibility**. The `Last-Event-ID` header carries an *event identifier* the client last saw; it does **not** carry a promise that the server can still *replay* from that identifier. In a streamable session these two are usually coupled because the server retains a bounded ring buffer keyed by monotonic event IDs. After an SSE-to-streamable upgrade, however, the server frequently re-bases its event ID sequence (new stream, new counter, or a per-session epoch), so the client's `Last-Event-ID` refers to an identifier that is *syntactically valid but semantically orphaned*. The resumption handshake succeeds at the HTTP layer (200, `text/event-stream` resumed) while the semantic replay window has already moved past the client's cursor. The failure is silent: no error, no gap marker, just a stream that continues from a point the client cannot reconcile with its own state. This is not a generic reconnect problem. It is specific to the moment where two transports with *different event-ID namespaces* are stitched together, and the client assumes namespace continuity across the upgrade boundary. ## What Was Observed A representative trace from a client that had been running a long-lived tool-call loop: 1. Session opens on legacy SSE: `GET /mcp` → `200`, stream begins. Server assigns event IDs `e-1001`, `e-1002`, … in a per-connection counter. 2. Client processes through `e-1042`. It records `lastEventId = "e-1042"` and the corresponding tool-call state (`call_id=42`, `status=in_flight`). 3. Transport drops (idle LB timeout at 60s, common with a mid-tool-call pause). 4. Client reconnects. Server now answers with a streamable upgrade: `POST /mcp` with `Mcp-Session-Id` and `Last-Event-ID: e-1042`. Server returns `200` and a *new* event stream whose first emitted ID is `s-0001` (streamable namespace, fresh counter). The server's replay buffer was reset on upgrade and holds only events from `s-0001` forward. 5. Client's resumption logic sees `200` + open stream and concludes "resumed." It appends `s-0001…` to its log. The events between `e-1042` and the upgrade point — including the terminal `tool_result` for `call_id=42` — are **never replayed**. `call_id=42` remains `in_flight` forever in client state. 6. Downstream, the agent's planner sees an unresolved tool call and either re-issues it (duplicate side effect) or blocks waiting for a result that will never arrive. The tell is the namespace discontinuity: `e-1042` → `s-0001`. A client that only checks HTTP status and stream openness misses it entirely. ## Condition of Validity The naive resumption assumption — *"a 200 on reconnect with `Last-Event-ID` means no events were lost"* — is valid **only** under all of the following: - **(V1) Namespace stability:** the server's event-ID scheme is monotonic and unbroken across the upgrade boundary, so `Last-Event-ID` is comparable to the first replayed ID. - **(V2) Replay-window containment:** the requested `Last-Event-ID` is still within the server's retained buffer. Bounded ring buffers evict; eviction is invisible at the HTTP layer. - **(V3) Explicit gap signaling:** if the server cannot replay from the cursor, it either returns a distinct status (e.g., `409`/`410` with a resume-token) or emits a gap marker event before resuming. When any of V1–V3 fails — and an SSE-to-streamable upgrade is precisely the event that breaks V1 and often V2 — resumption must be treated as **unsafe** and the client must fall back to a full state reconciliation (re-fetch session state, re-query in-flight tool calls by ID) rather than trusting the stream. The invariant to enforce: **the client must never advance its committed state on a resumed stream until it has verified cursor continuity** — i.e., that the first replayed event ID is the *successor* of `lastEventId` in the same namespace, or that an explicit gap marker accounts for the discontinuity. ## Decision Boundary The boundary is a single predicate evaluated at reconnect time, *before* any event is appended to agent state: ``` resume_safe := (first_replayed_id is successor of last_event_id in same namespace) OR (server emitted explicit gap marker covering the interval) OR (server returned a resume-token the client can validate) ``` If `resume_safe` is false, the client must not resume — it must reconcile. The decision is binary and must be made on the first frame of the resumed stream, not deferred. Deferring is the trap: once the client has appended even one post-upgrade event, its log is internally inconsistent and the reconciliation must unwind state, which is far more expensive and error-prone than refusing the resume up front. A second boundary: **tool calls in `in_flight` at the moment of disconnect are the highest-risk objects.** A stream gap that loses a `tool_result` leaves a call unresolved; a stream gap that loses a `tool_call` leaves a side effect the agent doesn't know it initiated. Both are unrecoverable by stream replay alone and require an out-of-band query keyed by `call_id`. ## Operational Effect Without the guard, the observed failure modes are: - **Orphaned in-flight calls:** agent blocks or duplicates side effects (double-charges, double-writes) because the result frame was in the evaporated window. - **Silent state divergence:** client log and server truth differ by the gap interval, and every subsequent reasoning step is built on a false premise. The divergence is not self-healing. - **False-positive health:** monitoring sees `200` on reconnect and reports the session healthy while the agent is semantically stalled. With the guard (continuity predicate + reconciliation fallback), the cost is one extra round-trip to re-query in-flight `call_id`s on the rare upgrade-triggered gap, and the benefit is that the agent never reasons over a hole. The reconciliation path must be idempotent on `call_id` so that a re-query after a *safe* resume is a no-op. The operational rule for an agent instance: **on any transport upgrade, treat `Last-Event-ID` as a hint, not a contract; verify namespace continuity on the first replayed frame; if continuity is absent, halt stream consumption and reconcile in-flight tool calls by ID before resuming reasoning.** ```python import re from dataclasses import dataclass class ResumeContinuityError(RuntimeError): """Raised when a resumed MCP stream cannot be proven continuous with client state.""" pass @dataclass class StreamCursor: namespace: str # e.g. "e" for legacy SSE, "s" for streamable seq: int # numeric part of the event id def parse_event_id(event_id: str) -> StreamCursor: m = re.fullmatch(r"([a-zA-Z]+)-(\d+)", event_id or "") if not m: raise ResumeContinuityError(f"unparseable event id: {event_id!r}") return StreamCursor(namespace=m.group(1), seq=int(m.group(2))) def assert_resume_safe(last_event_id: str, first_replayed_id: str, gap_marker_present: bool) -> None: """ Enforce the continuity invariant before any post-upgrade event is committed to agent state. Raises if the resumed stream is semantically orphaned. """ if gap_marker_present: return # server explicitly accounted for the discontinuity last = parse_event_id(last_event_id) first = parse_event_id(first_replayed_id) if first.namespace != last.namespace: # SSE-to-streamable upgrade re-based the event namespace. raise ResumeContinuityError( f"namespace re-based across upgrade: last={last_event_id} " f"first_replayed={first_replayed_id}; replay window is orphaned, " f"must reconcile in-flight tool calls by call_id" ) if first.seq != last.seq + 1: raise ResumeContinuityError( f"event gap in same namespace: last={last_event_id} " f"first_replayed={first_replayed_id}; " f"expected seq {last.seq + 1}, got {first.seq}" ) def resume_session(last_event_id: str, first_replayed_id: str, gap_marker_present: bool, in_flight_call_ids: list[str]) -> str: try: assert_resume_safe(last_event_id, first_replayed_id, gap_marker_present) return "resumed" except ResumeContinuityError: # Fall back to out-of-band reconciliation; do NOT consume the stream. if in_flight_call_ids: return f"reconcile:{','.join(in_flight_call_ids)}" return "reconcile:full_state_refetch" ```