# When must an instance refuse a stateless MCP fallback: session-affinity loss across load-balanced MCP servers and the silent resumption of a stale `initialize` handshake **Date of Record:** 2026 November 30 **Scope:** Applies to horizontally scaled MCP servers sitting behind a layer-4/layer-7 load balancer where session affinity is best-effort and a stateless fallback path exists for requests whose `Mcp-Session-Id` cannot be resolved. Does not apply to single-replica MCP deployments, nor to transports where the client pins a single long-lived connection (e.g., stdio) and no rebalancing occurs. ## Core Distinction The failure is not "the load balancer dropped a session." Dropped sessions are expected and recoverable: the client sees a connection reset, re-issues `initialize`, and rebuilds state. The failure is subtler and is a property of the *server's fallback policy*, not of the transport. A stateless fallback that accepts a request bearing an unknown `Mcp-Session-Id` and serves it against a **freshly constructed, empty session context** is indistinguishable—at the protocol layer—from a legitimate first request. The client cannot tell that its prior `initialize` capabilities, negotiated protocol version, and any server-side session-scoped state (subscriptions, sampling callbacks, roots, in-flight tool continuations) have been silently discarded. The server returns `200` with a well-formed JSON-RPC result, and the agent runtime proceeds as if continuity held. The invariant that must be enforced is: **an MCP server may only serve a request against a session context that was established by an `initialize` the client itself performed and can correlate.** A request carrying a session id the server did not mint, or minted and has since evicted, must produce an explicit, machine-distinguishable rejection—never a transparent stateless serve. ## What Was Observed A three-replica MCP server fleet (`mcp-a`, `mcp-b`, `mcp-c`) behind an L7 balancer with cookie-based affinity and a 60-second idle timeout. Session store is in-process memory; there is no shared session backend. The balancer is configured with `fallback: round-robin` for requests whose affinity cookie is absent or whose target replica reports the session unknown. Trace of a representative incident, an agent performing a multi-step `tools/call` workflow with a `sampling/createMessage` callback registered during `initialize`: 1. Agent connects, balancer pins to `mcp-a`. `initialize` succeeds; server mints `Mcp-Session-Id: s-7f3a`, records negotiated `protocolVersion: 2024-11-05`, registers the client's sampling callback and two `roots` entries in `mcp-a`'s in-process session map. 2. Agent issues `tools/call` for a long-running tool. `mcp-a` begins execution, holds the request open, and during execution attempts `sampling/createMessage` back to the client. This is a server→client request scoped to session `s-7f3a`. 3. The agent runtime's event loop blocks on the tool result for >60s (a model-side stall, not a network stall). The balancer's idle timer expires the affinity mapping. The TCP connection is *not* closed—the balancer only forgets the pin. 4. A concurrent sub-agent in the same runtime issues an unrelated `tools/list` on a second connection. The balancer, having no live affinity for the runtime's cookie (it was scoped to the expired connection), round-robins it to `mcp-b`. 5. `mcp-b` receives `tools/list` with header `Mcp-Session-Id: s-7f3a`. Its session map has no such id. **The stateless fallback branch fires:** it constructs an ephemeral session context, serves `tools/list` from the global tool registry, and returns `200`. The response is correct in content and indistinguishable from a real session's response. 6. The original `tools/call` on `mcp-a` completes and attempts to deliver its `sampling/createMessage` to a client that, from `mcp-a`'s perspective, is still on `s-7f3a`—but the client's runtime has already routed subsequent traffic to `mcp-b` and `mcp-c`, and the sampling callback registered on `mcp-a` is now orphaned. The agent receives a tool result whose embedded sampling request it never answers; depending on the runtime, it either hangs until its own timeout or, worse, treats the unanswered sampling request as a no-op and continues with a tool result computed under a partially-satisfied precondition. The observable symptom reported by operators was *not* an error. It was a class of agent runs that "completed" but produced subtly wrong outputs: tool results that reflected a registry snapshot from a replica that had received a different tool-version rollout, and sampling-dependent branches that silently took their default path. Error rates were flat. The fallback was doing exactly what it was configured to do. ## Condition of Validity The stateless fallback is only sound under a conjunction that is almost never simultaneously true in agent deployments: - **The request is genuinely session-independent.** `tools/list`, `resources/list`, and `prompts/list` against a globally consistent registry qualify. `tools/call`, `sampling/*`, `roots/list`, and any `notifications/*` do not—they are defined relative to session-scoped state. - **The server's session-scoped state is empty by construction, not by accident.** A fallback that builds an empty context satisfies "empty" but not "by construction": the emptiness is a *lie* about a session that once existed and may still exist on another replica. - **No in-flight server→client request is outstanding for the original session.** The `sampling/createMessage` in step 2 violates this; the fallback has no visibility into `mcp-a`'s pending callback and cannot know it is orphaning it. - **The client can detect the substitution.** MCP provides no mechanism for this. The `Mcp-Session-Id` is opaque; there is no session-generation counter, no `Last-Event-ID` equivalent for session identity, and no required `initialize`-echo on subsequent requests. When any conjunct fails, the fallback converts a recoverable transport event (affinity loss) into an unrecoverable semantic event (silent state substitution). The correct behavior is to reject with a session-unknown error so the client's protocol layer re-initializes and re-registers callbacks—an expensive but *correct* recovery. ## Decision Boundary The server must distinguish three cases that the naive implementation collapses into one: | Case | `Mcp-Session-Id` present | Session in local store | Correct action | |---|---|---|---| | Fresh client | absent | n/a | serve `initialize`, mint id | | Known session, same replica | present | yes | serve normally | | **Unknown/evicted session** | present | no | **reject with session-unknown; do not fall back** | The boundary is the third row. The rule the fleet must encode: *the presence of a session id the server cannot resolve is a hard error, never a fallback trigger.* Stateless serving is permitted only for requests with **no** session id, and only for methods explicitly declared session-independent in a server manifest. The balancer's fallback policy must be narrowed accordingly: it may retry on a *connection* failure, but must not re-route a request whose session id it cannot vouch for; instead it must return the session-unknown error to the client so the client's own reconnect logic runs. Two guardrails make this enforceable rather than aspirational. First, session ids must be **self-verifying** (HMAC over `{replica, mint-time, nonce}` with a fleet-shared key) so any replica can distinguish "minted by a peer, I don't hold the state" from "never minted"—the former is recoverable via shared session backend lookup or redirect, the latter is a client bug. Second, the server must track **outstanding server→client requests per session** and, on eviction, emit a `notifications/cancelled` for each rather than letting them orphan; this is what bounds the sampling-callback loss in step 6. ## Operational Effect With the boundary enforced, affinity loss degrades to a visible, recoverable error: the agent runtime receives session-unknown, tears down its per-session callbacks, re-runs `initialize`, and replays the interrupted tool call. Cost is a re-initialization round-trip and, for non-idempotent tools, a deduplication requirement at the tool layer. Without it, the failure is invisible and the agent proceeds on substituted state—the worst outcome for an autonomous system, because the run *succeeds* while violating its own preconditions. The metric that catches this in production is not error rate but **session-id churn per agent run**: a healthy fleet shows churn only on genuine reconnects; a fleet with a leaky fallback shows near-zero churn because sessions are being silently resurrected as empty contexts, and the corresponding tool-result divergence (results computed against a different replica's registry snapshot) appears only in cross-replica diffing of tool outputs for identical inputs. ```python import hashlib import hmac import time from dataclasses import dataclass class SessionSubstitutionError(RuntimeError): """Raised when a request bearing an unresolvable session id is served against a fabricated empty context instead of being rejected.""" class StatelessFallbackRefused(SessionSubstitutionError): """The correct refusal: unknown session id must not trigger fallback.""" @dataclass(frozen=True) class SessionToken: replica: str minted_at: float nonce: str FLEET_KEY = b"fleet-shared-session-key" # rotated out-of-band SESSION_INDEPENDENT_METHODS = frozenset({"initialize", "tools/list", "resources/list", "prompts/list"}) def mint_session_id(replica: str, nonce: str) -> str: ts = f"{time.time():.0f}" body = f"{replica}|{ts}|{nonce}".encode() mac = hmac.new(FLEET_KEY, body, hashlib.sha256).hexdigest()[:32] return f"{replica}.{ts}.{nonce}.{mac}" def verify_session_id(session_id: str) -> SessionToken: try: replica, ts, nonce, mac = session_id.split(".") except ValueError as exc: raise StatelessFallbackRefused(f"malformed session id {session_id!r}") from exc body = f"{replica}|{ts}|{nonce}".encode() expected = hmac.new(FLEET_KEY, body, hashlib.sha256).hexdigest()[:32] if not hmac.compare_digest(mac, expected): raise StatelessFallbackRefused(f"session id {session_id!r} not minted by fleet") return SessionToken(replica=replica, minted_at=float(ts), nonce=nonce) def dispatch(method: str, session_id: str | None, local_store: dict, shared_store) -> dict: """Route an MCP request. Returns a result dict or raises. Invariant: a present-but-unresolvable session id is a hard error. Stateless serving is allowed only when session_id is None AND the method is declared session-independent. """ if session_id is None: if method not in SESSION_INDEPENDENT_METHODS: raise StatelessFallbackRefused( f"method {method!r} requires a session; none supplied" ) return {"served": "stateless", "method": method} # A session id is present. It must resolve, here or in the shared backend. if session_id in local_store: ctx = local_store[session_id] else: token = verify_session_id(session_id) ctx = shared_store.get(session_id) if ctx is None: # The leaky implementation would fabricate an empty context here. # We refuse instead: the client must re-initialize. raise StatelessFallbackRefused( f"session {session_id!r} minted by {token.replica} is unknown; " f"refusing stateless fallback for method {method!r}" ) if method not in SESSION_INDEPENDENT_METHODS and not ctx.get("initialized"): raise SessionSubstitutionError( f"session {session_id!r} has no completed initialize; " f"method {method!r} would run on substituted state" ) if ctx.get("outstanding_server_requests"): # Evicting or re-routing this session would orphan sampling/roots callbacks. raise SessionSubstitutionError( f"session {session_id!r} has {len(ctx['outstanding_server_requests'])} " f"outstanding server->client requests; cancellation required before reroute" ) return {"served": "session", "method": method, "replica": ctx["replica"]} ```