# Which invariants prevent MCP streamable-HTTP session teardown from silently severing in-flight tool calls during server-side rebalancing **Date of Record:** 2026 December 3 **Scope:** Applies to MCP servers exposed over the HTTP-native (streamable) transport binding where the server is horizontally scaled behind a load balancer and sessions carry a negotiated `Mcp-Session-Id` plus an SSE upgrade channel. Does not apply to stdio transport, nor to single-process servers with no session affinity concerns. ## Core Distinction The failure we are isolating is not "the server crashed mid-call." It is subtler: the server *deliberately* terminates a session (drain, rebalance, rolling deploy, idle reaper) and the client's streamable-HTTP binding treats the resulting `404`/`410` on the session endpoint as "session unknown — re-initialize," which is a *legal* protocol response. The client then re-issues `initialize`, obtains a fresh `Mcp-Session-Id`, and resumes — but any tool call that was in flight on the old session's SSE stream is *gone*, and because the JSON-RPC response was never delivered, the client's request map either hangs until its own timeout or, worse, the agent's reasoning loop treats the re-initialization success as evidence the call completed. The distinction that matters: **session liveness and request liveness are two different invariants, and the streamable-HTTP binding only guarantees the first.** A `200` on a re-`initialize` proves the *transport* recovered. It proves nothing about the *tool invocation* that was mid-flight. Agents that conflate the two produce silent action loss — the agent believes a side-effecting call (file write, payment, deploy) succeeded when the server never finished it. ## What Was Observed A three-replica MCP server hosting a `filesystem` tool set, fronted by a round-robin load balancer with no session affinity, idle-reaping sessions at 90s. An agent loop issued a `tools/call` for `write_file` with a 4 MB payload. The call landed on replica B, which opened an SSE stream and began streaming a `progress` notification. At t+88s the payload was still being written to a slow backing store; the reaper on replica B's *control plane* (a separate goroutine, not aware of in-flight streams) evaluated last-*request*-time, not last-*stream-activity*-time, and evicted the session. The SSE stream was closed with a plain `200` end-of-stream (no error frame). The client's streamable binding, per spec, saw the stream close and immediately attempted `GET /mcp` to re-open the notification stream with the old `Mcp-Session-Id`; replica B returned `404`. The client interpreted this as "session expired," re-ran `initialize`, got a new id from replica C, and — because its request map had no entry tying the original `tools/call` id to a *pending* state — surfaced "tool call completed" to the agent. The file was never written. The agent proceeded to `verify_file_exists`, which hit replica A, which had never seen the write, and returned `false`. The agent then entered a retry loop that wrote the file three more times across three replicas, producing three partial files and one complete one, with no dedup because idempotency keys were not part of the negotiated capability set. Two root mechanics: 1. **The reaper measured the wrong clock.** Session TTL was bound to `last_request_at`, not `last_stream_frame_at`. A long-running tool with periodic progress frames keeps the *stream* alive but not the *request clock*. 2. **Stream close is not stream failure.** The SSE `200` close is indistinguishable at the binding layer from a graceful completion. The client had no way to tell "server finished the call and closed" from "server dropped the call and closed," because the JSON-RPC response frame — the only authoritative completion signal — was never sent. ## Condition of Validity The invariant holds only under these conditions, and the guardrail below is only correct when all are true: - The transport is streamable-HTTP with a server-assigned `Mcp-Session-Id` and at least one long-lived SSE channel per session. - Tool calls may outlive the session's idle-reap window, OR the server may be rebalanced/drained while a call is in flight. - The client cannot distinguish graceful stream end from abortive stream end without an application-level completion frame. It does **not** hold if the server guarantees that session teardown is preceded by an explicit `notifications/cancelled` for every in-flight request id (rare, but spec-permitted), or if the client uses a transport that carries request/response on the same connection with a hard error on close (e.g., a request-scoped HTTP POST that returns the full result body, no SSE). ## Decision Boundary The boundary is: **does the client maintain a request-liveness ledger that is independent of session-liveness, and does it fail closed when a session dies with requests outstanding?** - *Below the boundary* (naive): session id is the only correlation key; on `404` the client re-initializes and assumes outstanding requests are resolvable by retry. This is where silent action loss and duplicate side-effects live. - *At the boundary* (guarded): the client keeps a per-`Mcp-Session-Id` map of outstanding request ids → `{tool, args, started_at, side_effecting}`. On any session-terminating signal (`404`, `410`, stream close without a terminal JSON-RPC frame, or a re-`initialize`), it **must** transition every outstanding entry to `UNKNOWN`, not `DONE` and not `RETRY`. `UNKNOWN` is a distinct terminal-for-this-attempt state that forces the agent to run a reconciliation step (idempotency probe, read-back verification) before any retry. - *Above the boundary*: server-side, the reaper must be bound to `max(last_request_at, last_stream_frame_at)` and must, on eviction, emit `notifications/cancelled` for every in-flight request id *before* closing the stream, and the drain path must refuse new `tools/call` on a draining session while allowing in-flight ones to complete. The decision the agent must make: when a side-effecting call's session dies, **never retry without an idempotency token or a read-back probe.** The protocol will not tell you whether it happened. ## Operational Effect With the guarded client, the observed incident resolves as: the `write_file` on replica B is marked `UNKNOWN`, the agent runs `stat` on the target path, finds the partial file, and issues a single corrective `write_file` with an idempotency key derived from `(session_id, request_id, content_hash)`. One file, correct content, one reconciliation round-trip. Without the guard, the same incident produced four writes, three partials, and a 40-second retry storm that saturated the backing store. The cost of the guard is a mandatory `UNKNOWN`-state reconciliation on *every* session teardown, even benign ones — roughly one extra round-trip per rebalance. That is the price of the invariant: **transport recovery is not request recovery, and the binding must not let the agent believe otherwise.** ```python from __future__ import annotations import hashlib from dataclasses import dataclass, field from enum import Enum class SessionTeardownError(RuntimeError): """Raised when a session dies with requests outstanding and the caller attempts to treat transport recovery as request completion.""" class RequestState(Enum): PENDING = "pending" DONE = "done" UNKNOWN = "unknown" # session died; outcome genuinely unknown RETRY_SAFE = "retry_safe" # idempotent or reconciled; safe to re-issue @dataclass class OutstandingCall: request_id: str tool: str side_effecting: bool idempotency_key: str | None state: RequestState = RequestState.PENDING @dataclass class SessionLedger: session_id: str calls: dict[str, OutstandingCall] = field(default_factory=dict) def on_session_terminated(self, reason: str) -> list[OutstandingCall]: # The invariant: session death NEVER implies request completion. # Every outstanding call becomes UNKNOWN, never DONE, never RETRY. orphaned: list[OutstandingCall] = [] for call in self.calls.values(): if call.state is RequestState.PENDING: call.state = RequestState.UNKNOWN orphaned.append(call) if orphaned and reason == "reinitialize_success": # The specific boundary failure: client saw a 200 on re-initialize # and assumed the old calls were fine. raise SessionTeardownError( f"session {self.session_id} re-initialized with " f"{len(orphaned)} outstanding calls; re-initialize does NOT " f"imply completion of: {[c.request_id for c in orphaned]}" ) return orphaned def reconcile(self, call: OutstandingCall, probe_result: bool) -> None: if call.state is not RequestState.UNKNOWN: raise SessionTeardownError( f"reconcile called on {call.request_id} in state {call.state}" ) if probe_result: call.state = RequestState.DONE else: if call.side_effecting and call.idempotency_key is None: raise SessionTeardownError( f"cannot safely retry side-effecting call {call.request_id} " f"({call.tool}) without idempotency key after UNKNOWN" ) call.state = RequestState.RETRY_SAFE def derive_idempotency_key(session_id: str, request_id: str, payload: bytes) -> str: h = hashlib.sha256(payload).hexdigest()[:16] return f"{session_id}:{request_id}:{h}" # --- exercise the invariant --- ledger = SessionLedger(session_id="sess-B-7731") ledger.calls["req-88"] = OutstandingCall( request_id="req-88", tool="write_file", side_effecting=True, idempotency_key=derive_idempotency_key("sess-B-7731", "req-88", b"4MB-payload"), ) # Replica B reaped the session mid-write; client re-initialized successfully. try: ledger.on_session_terminated("reinitialize_success") except SessionTeardownError as e: # Expected: transport recovered, request did not. print(f"[guard] {e}") # Agent is now forced to reconcile before any retry. orphan = ledger.calls["req-88"] ledger.reconcile(orphan, probe_result=False) # stat() says file absent assert orphan.state is RequestState.RETRY_SAFE print(f"[ok] req-88 -> {orphan.state.value}, safe to re-issue once") ```