# When must an instance re-establish a Streamable-HTTP MCP session after notification loss, and when may it safely resume on `Last-Event-ID`? **Date of Record:** 2026 November 26 **Scope:** Applies to MCP clients using the Streamable HTTP transport with SSE-framed server-push notifications and `Last-Event-ID` resumption, where the client maintains a long-lived logical session across reconnects. Does not apply to stdio transport, nor to stateless one-shot HTTP request/response MCP servers that emit no notifications. ## Core Distinction The Streamable HTTP transport distinguishes two superficially similar events: a **transport interruption** (the SSE connection drops) and a **session termination** (the server has discarded the session's event buffer and/or session ID). `Last-Event-ID` resumption is only valid against the former. The failure mode examined here is the client resuming with `Last-Event-ID` against a server that has already rotated or expired the session, receiving a `404`/`410` on the resume GET, yet *silently continuing to issue tool calls under the stale `Mcp-Session-Id` header* because those POSTs happen to return `200` from a load-balanced replica that has no memory of the notification stream. The client then believes it has an intact session with a gap-free notification history, when in fact it has a session with a **hole** in its event sequence: notifications emitted between the last seen event ID and the replica's cold start were never delivered and will never be replayed. The invariant that must hold: **the notification sequence a client has observed must be a contiguous prefix of the server's emitted sequence for that session, or the client must treat the session as terminated and re-initialize.** Transport-level success codes on individual POSTs do not attest to this invariant. Only the resume GET's response attests to it. ## What Was Observed A client agent held `Mcp-Session-Id: s-7f3a` against a 3-replica MCP server behind a round-robin load balancer. The session's event buffer lived on replica R1 with a 60s TTL after last activity. The agent went idle for 95s awaiting a slow upstream tool call (a browser automation step). During idle, R1 garbage-collected the session and its event buffer. Sequence of events on the agent side: 1. SSE stream to R1 dropped at T+60s (idle GC). Agent recorded `Last-Event-ID: 412`. 2. Agent's reconnect GET with `Last-Event-ID: 412` landed on R2. R2 had never seen `s-7f3a`; it returned `404 Not Found` on the GET. 3. Agent's retry logic treated the `404` as a *transport* error and retried the GET. This time it hit R1 (round-robin), which also returned `404` (session gone). After 3 retries the agent logged `stream reconnect failed, continuing`. 4. Agent then issued `tools/call` POSTs. These landed on R2 and R3. Because the server's POST handler validated only the `Mcp-Session-Id` header's *format* and delegated tool execution to stateless workers, the POSTs returned `200` with correct tool results. No `404` on POST. 5. Notifications emitted by R1 in the window between the last seen event (412) and GC — specifically a `notifications/tools/list_changed` and two `notifications/resources/updated` — were **never delivered**. The agent's tool cache was stale by one `list_changed` and its resource view by two updates. 6. The agent proceeded to call a tool that had been removed in the `list_changed` it never saw. The call failed with a domain error, not a transport error, so no session-level alarm fired. The observable signature: **POSTs succeed, GETs 404, and the agent's notification-derived state diverges from the server's actual state without any single error the agent is configured to treat as fatal.** ## Condition of Validity `Last-Event-ID` resumption is valid **only if** the resume GET returns `200` with an SSE stream whose first replayed event has an ID strictly greater than the supplied `Last-Event-ID`, or the server explicitly signals "no gap" via an empty replay followed by live events. The condition of validity is therefore: - The server retains the session's event buffer for the entire idle window of the client, **and** - The resume GET is routed to a replica that holds that buffer (session affinity), **and** - The client treats any non-`200` on the resume GET — including `404` and `410` — as **session termination**, not transport failure. If any of these fails, the only correct client action is to discard `Mcp-Session-Id`, re-run `initialize`, re-fetch `tools/list` and `resources/list`, and reconcile its cache against the fresh snapshot before issuing further calls. The POST path returning `200` is not evidence that this reconciliation happened. ## Decision Boundary The boundary the agent must encode: - **`404`/`410` on resume GET → session terminated.** Mandatory re-initialize. Do not continue issuing calls under the old session ID. Do not treat as retryable transport error. - **Network error / timeout / `502`/`503` on resume GET → transport interruption.** Retry with backoff, preserving `Last-Event-ID`. Session presumed alive. - **`200` on resume GET with replayed events → resume succeeded.** Verify the first replayed event ID > `Last-Event-ID`; if not, a gap exists and the server's buffer is inconsistent → treat as terminated. - **`200` on POST but resume GET never attempted after a drop → undefined.** The agent is in the hole-state; any tool call is unsound with respect to notification-derived cache. The critical non-obvious rule: **a successful POST does not upgrade the session from "terminated" to "alive."** Liveness of the notification stream is attested only by the resume GET, and the POST handler's acceptance of the session ID is a weaker check than the GET's buffer lookup. Conflating them is the bug. ## Operational Effect Agents that conflate POST success with session liveness exhibit **silent notification loss**: they operate on stale `tools/list` and `resources/list` caches indefinitely, because the only signal of staleness (the missing `list_changed` notification) is precisely the thing that is missing. The failure is not a crash; it is a persistent, undetected divergence between the agent's world model and the server's, which surfaces later as domain errors that look like tool bugs rather than transport bugs. The guardrail: on every SSE drop, the agent must run the resume GET as a **mandatory gate** before any subsequent POST, and must classify the GET's response per the decision boundary above. If the gate fails with `404`/`410`, the agent must raise a session-terminated condition, invalidate all notification-derived caches, and re-initialize. The POST path must not be reachable while the gate is unresolved. ```python import time from dataclasses import dataclass, field from enum import Enum from typing import Optional class SessionTerminatedError(RuntimeError): """Raised when the MCP session must be re-initialized before further calls.""" class NotificationGapError(RuntimeError): """Raised when the replayed event stream does not continue from Last-Event-ID.""" class SessionState(Enum): ALIVE = "alive" INTERRUPTED = "interrupted" # transport drop, session presumed alive TERMINATED = "terminated" # server discarded session; re-init required @dataclass class McpSession: session_id: str last_event_id: int = 0 state: SessionState = SessionState.ALIVE tools_cache_valid: bool = True resources_cache_valid: bool = True @dataclass class ResumeResult: status_code: int first_replayed_event_id: Optional[int] = None network_error: bool = False def classify_resume(result: ResumeResult, last_event_id: int) -> SessionState: """Map a resume GET outcome to a session state per the decision boundary.""" if result.network_error: return SessionState.INTERRUPTED if result.status_code in (404, 410): return SessionState.TERMINATED if result.status_code == 200: # 200 with replayed events must strictly continue the sequence. if result.first_replayed_event_id is not None and result.first_replayed_event_id <= last_event_id: # Buffer inconsistent: a gap exists that the server did not acknowledge. return SessionState.TERMINATED return SessionState.ALIVE if result.status_code in (502, 503): return SessionState.INTERRUPTED # Any other status is ambiguous; treat conservatively as terminated. return SessionState.TERMINATED def resume_session(session: McpSession, result: ResumeResult, max_retries: int = 3) -> McpSession: """ Gate every post-drop POST behind a resume GET. If the gate resolves to TERMINATED, invalidate notification-derived caches and raise. """ attempts = 0 while attempts < max_retries: state = classify_resume(result, session.last_event_id) session.state = state if state is SessionState.ALIVE: return session if state is SessionState.TERMINATED: # Invalidate caches derived from the lost notification stream. session.tools_cache_valid = False session.resources_cache_valid = False raise SessionTerminatedError( f"Session {session.session_id} terminated at last_event_id=" f"{session.last_event_id}; re-initialize and reconcile caches " f"before issuing further tools/call requests." ) # INTERRUPTED: retry the resume GET, preserving Last-Event-ID. attempts += 1 time.sleep(0.5 * (2 ** attempts)) # In a real client, re-issue the GET here and refresh `result`. # Simulated: give up after retries as an interrupted-but-unresolved state. if attempts >= max_retries: raise SessionTerminatedError( f"Session {session.session_id} resume unresolved after " f"{max_retries} retries; refusing to issue POSTs under an " f"unverified session." ) raise SessionTerminatedError("unreachable") def issue_tool_call(session: McpSession, tool_name: str) -> str: """POST path. Must not be reachable while the resume gate is unresolved.""" if session.state is SessionState.TERMINATED: raise SessionTerminatedError( f"Refusing tools/call '{tool_name}': session {session.session_id} is terminated." ) if session.state is SessionState.INTERRUPTED: raise SessionTerminatedError( f"Refusing tools/call '{tool_name}': resume gate unresolved for " f"session {session.session_id}." ) if not session.tools_cache_valid: raise SessionTerminatedError( f"Refusing tools/call '{tool_name}': tools cache invalidated by " f"notification loss; re-fetch tools/list first." ) return f"ok:{tool_name}" # --- Demonstration of the failure trace --- if __name__ == "__main__": s = McpSession(session_id="s-7f3a", last_event_id=412) # Resume GET hit a replica that never saw the session. resume = ResumeResult(status_code=404) try: resume_session(s, resume) except SessionTerminatedError as e: print(f"gate closed: {e}") # A subsequent POST must be blocked, even though the server would have # returned 200 on it (stateless worker). The client-side gate is the guard. try: issue_tool_call(s, "browser.navigate") except SessionTerminatedError as e: print(f"post blocked: {e}") # The silent-loss variant: a 200 resume whose replay does NOT advance. s2 = McpSession(session_id="s-9c01", last_event_id=88) resume2 = ResumeResult(status_code=200, first_replayed_event_id=88) try: resume_session(s2, resume2) except SessionTerminatedError as e: print(f"gap detected: {e}") ```