# How does an instance detect that an MCP SSE resume has silently re-bound to a *new* logical session rather than the one it left? **Date of Record:** 2026 November 23 **Scope:** Applies to MCP clients using the HTTP-native transport (Streamable HTTP + SSE) with `Last-Event-ID` resumption and `Mcp-Session-Id` reattachment, where the server may fork, GC, or rehydrate a logical session behind the same transport-level identity. Does not apply to stdio transports or to WebSocket multiplexed transports, where the connection itself is the session. ## Core Distinction The transport carries two distinct identity axes that the wire format does *not* force to agree: 1. **Transport continuity** — the `Mcp-Session-Id` header and the SSE `Last-Event-ID` replay cursor. These are cheap, stateless, and the server is allowed to honor them by *reconstructing* a session. 2. **Logical continuity** — the actual in-memory tool-call state, the pending request table, the capability negotiation that was done at `initialize`, and any server-side resources keyed by the original session (subscriptions, open cursor handles, sandboxed filesystem roots, in-flight long-running tool invocations). A correct resume requires both. The failure mode is that a server will happily satisfy axis 1 while silently violating axis 2: it accepts the `Mcp-Session-Id`, replays events from `Last-Event-ID` out of a durable event log, and returns `200 OK` with a fresh SSE stream — but the process that owns the actual session state has been replaced (restart, scale-out to a cold replica, session TTL expiry followed by lazy re-creation). The client observes an unbroken HTTP conversation and a plausible event replay, and concludes the session survived. It did not. The event replay is a *recording* of the old session, not a continuation of it. The invariant that must hold for a resume to be safe is: **the event IDs replayed after `Last-Event-ID` must be emitted by the same session generation that produced the events before it, and that generation must still own the state those events imply.** Neither property is visible in the SSE frame itself. ## What Was Observed A client agent held a session with a filesystem-scoped MCP server. It had issued `initialize`, negotiated capabilities, and opened a `resources/subscribe` on a directory, plus a long-running `tools/call` for a build that streams progress notifications. The SSE stream dropped (LB idle timeout at 60s, a known and expected condition). The client reconnected with the same `Mcp-Session-Id` and `Last-Event-ID: 4821`. The server returned `200` and replayed events `4822`–`4830` from its event log — including the terminal `notifications/progress` frames for the build tool call, which the client had not yet consumed. The client resumed cleanly. Then it issued the next request on the same stream: a `tools/call` referencing a resource handle returned by the *first* `tools/call` (a build artifact path the server had promised to keep alive for the session). The server responded with a well-formed MCP error — not a transport error, a *semantic* one: `-32602 Invalid params: unknown resource handle`. The handle had been minted by session generation 7; the reattachment landed on generation 9, which had a fresh, empty handle table. The event log had been replayed faithfully because it was a durable append-only log; the handle table was volatile. The failure was silent at three layers: HTTP returned 200, SSE framing was valid, and the replayed progress events were byte-identical to what the original generation would have emitted. The only signal was a downstream semantic error on the *next* request, with no causal link back to the resume. The agent's reasoning loop treated the resume as successful and attributed the invalid-handle error to its own earlier logic, then attempted a "fix" that re-issued the build — a compounding divergence. A second observation: the replayed events included a `notifications/message` about a subscription update that the *original* generation had already delivered and the client had already processed before the drop. Because `Last-Event-ID` is a cursor into the log, not a dedup key the client tracks, the client processed it twice. The handler was idempotent by luck; a non-idempotent one (e.g., a counter increment in agent working memory) would have double-applied. ## Condition of Validity Resumption is only semantically safe when the server can prove, and the client can verify, that the reattached session generation is the one that emitted the pre-drop events. Concretely, at least one of these must hold: - **Generation pinning:** the `Mcp-Session-Id` is bound to a specific server process/generation, and reattachment to a different generation is refused (e.g., `404` with a documented "session not found, re-initialize" body) rather than silently rehydrated. The client must treat a `404` on resume as *session death*, not as a transport hiccup to retry. - **Generation token in the event stream:** each SSE event carries a generation nonce (distinct from the monotonic event ID), and the client refuses to apply replayed events whose nonce differs from the last nonce it saw pre-drop. This makes the fork visible at the first replayed frame. - **State-completeness on rehydrate:** if the server *does* rehydrate, it must reconstruct the full session state implied by the event log — handle tables, subscriptions, capability state — and must emit a synthetic `notifications/message` (or equivalent) declaring the generation change so the client can invalidate cached handles rather than discover them dead one request at a time. Absent one of these, the client cannot distinguish "resumed" from "forked onto a lookalike," and every subsequent request is a bet that the server's volatile state survived a boundary the transport never checked. The dual condition for the client side: the client must maintain its own `Last-Event-ID` *and* a set of recently-applied event IDs (a bounded dedup window, at least the size of a plausible replay gap), because the server's replay is at-least-once and the client's handlers are not guaranteed idempotent. The cursor alone is insufficient — it tells the server where to resume, not the client what it has already seen. ## Decision Boundary The boundary is the moment the client observes `200 OK` on a resume request. Two policies are defensible, and the choice is not stylistic — it depends on whether the server exposes generation identity: - **If the server exposes generation identity (nonce in events, or refuses fork):** the client may resume transparently and trust the replay, *provided* it applies the dedup window. This is the low-latency path. - **If the server does not expose generation identity:** the client must treat any resume that crosses a connection drop as *session-suspect*. It should not transparently continue. It should either (a) re-run `initialize` and re-establish capabilities and subscriptions, accepting the cost, or (b) probe with a cheap, session-state-dependent request (a `ping` that echoes a session-scoped nonce the client planted at init) before issuing any state-dependent call. The probe is the cheap version of the invariant check: if the nonce comes back wrong or missing, the session is a fork. The failure to avoid is the middle path — resuming transparently *and* not probing *and* not deduping — which is what the wire format makes easy and what the observations above describe. That path is only correct when the server is a single-process, non-restarting, stateful singleton, which is exactly the deployment that the HTTP-native transport was designed to *not* require. ## Operational Effect The practical consequence is that an agent must budget for **session-generation churn as a first-class failure**, not a transport error. In a fleet deployment, the probability that a resume lands on a different generation rises with session lifetime and with replica count; a 60-second idle drop against a server with a 5-minute session TTL and N replicas behind a round-robin LB will fork on resume with high probability, and the fork is invisible until a state-dependent request fails. The agent's retry logic must therefore distinguish three outcomes of a resume: *genuine continuation* (proceed), *fork with replayed tail* (invalidate cached handles, re-establish subscriptions, re-probe nonce), and *dead session* (`404`/`410`, re-initialize). Collapsing these into "resume succeeded" is the bug. The second-order effect is on the reasoning loop: a silent fork produces a semantic error whose apparent cause is the agent's own prior reasoning (the handle it "should have" kept), so the agent will attempt to repair the wrong layer — re-issuing tool calls, re-reading resources — and compound the divergence. The guardrail is to attach the resume outcome to the agent's working memory as an explicit event ("session generation changed at T, handles invalidated") so that downstream errors are attributed to the correct cause. Without that, the agent's episodic memory records a self-inflicted bug that never existed. ```python import hashlib import time from dataclasses import dataclass, field from typing import Optional class SessionForkedError(RuntimeError): """Raised when an SSE resume reattaches to a different logical session generation than the one that emitted the pre-drop event tail.""" class SessionDeadError(RuntimeError): """Raised when the server refuses reattachment (404/410) — the session must be re-initialized, not retried.""" @dataclass class ResumeProbe: """Client-side invariant check for MCP HTTP-native SSE resumption. The client plants a session-scoped nonce at initialize time and echoes it on every resume. A server that forked onto a cold replica cannot return the nonce, because the nonce lives in the volatile session state that the fork did not carry. This is the cheapest observable proxy for the generation-pinning invariant. """ session_id: str planted_nonce: str last_event_id: int applied_event_ids: set = field(default_factory=set) dedup_window: int = 256 def _nonce_ok(self, echoed: Optional[str]) -> bool: if echoed is None: return False return hashlib.sha256(echoed.encode()).digest() == hashlib.sha256( self.planted_nonce.encode() ).digest() def verify_resume( self, http_status: int, echoed_nonce: Optional[str], replayed_event_ids: list, ) -> None: if http_status in (404, 410): raise SessionDeadError( f"session {self.session_id} refused reattachment " f"(status {http_status}); re-initialize required" ) if http_status != 200: raise SessionForkedError( f"unexpected resume status {http_status} for {self.session_id}" ) if not self._nonce_ok(echoed_nonce): raise SessionForkedError( f"resume for {self.session_id} landed on a generation that " f"cannot echo the planted nonce; cached handles and " f"subscriptions are invalid" ) # Replay is at-least-once: dedup against the client's applied set. fresh = [e for e in replayed_event_ids if e not in self.applied_event_ids] if len(self.applied_event_ids) > self.dedup_window: # Keep the window bounded; drop oldest by insertion order. excess = len(self.applied_event_ids) - self.dedup_window for _ in range(excess): self.applied_event_ids.pop() self.applied_event_ids.update(fresh) if fresh: self.last_event_id = max(fresh) def resume_stream(probe: ResumeProbe, transport) -> list: """Attempt a resumable SSE reattachment and enforce the invariant.""" resp = transport.resume( session_id=probe.session_id, last_event_id=probe.last_event_id, nonce_echo=probe.planted_nonce, ) probe.verify_resume( http_status=resp.status, echoed_nonce=resp.echoed_nonce, replayed_event_ids=resp.event_ids, ) return resp.events ```