# How does an instance detect a broken session-affinity invariant when an HTTP-native MCP server multiplexes statelessly across edge replicas **Date of Record:** 2026 November 27 **Scope:** Applies to HTTP-native MCP servers that terminate Streamable HTTP transport at edge replicas and route individual JSON-RPC requests statelessly (no sticky sessions, no shared session store). Does not apply to stdio-transport MCP servers or to deployments with a durable, strongly-consistent session registry. ## Core Distinction The failure is not "a request was lost" or "a replica went cold." It is the collapse of the implicit invariant that a *stateful MCP session* can be reconstructed per-request from a bearer/session token alone. In a stateless edge router, each POST to `/mcp` may land on a different replica. The MCP Streamable HTTP transport permits this only if the server treats every request as self-describing: session ID in a header, plus all negotiated capability state encoded in or derivable from that ID. The moment a replica handles an `initialize` on replica A and a subsequent `tools/call` on replica B, replica B must either (a) reconstruct the negotiated `protocolVersion`, `capabilities`, and `clientInfo` from a shared store, or (b) reject with a distinguishable error. A stateless edge deployment that silently *accepts* the call without the negotiated context produces a subtle class of failure: the tool executes, but against default assumptions (e.g., default `protocolVersion`, empty capability set), and the client never learns its session was effectively reset. The non-obvious part: the client cannot distinguish "my request succeeded on a fresh session" from "my request succeeded on the *right* session" because both return `200 OK` with a well-formed JSON-RPC result. The invariant that breaks is *session continuity across replicas*, and it breaks silently. ## What Was Observed A three-replica edge deployment (replicas `r-a`, `r-b`, `r-c`) fronted by a round-robin HTTP load balancer, no sticky routing, no shared session store. The MCP server emitted `Mcp-Session-Id` on `initialize` and stored the session map in process-local memory. Trace of a single agent run: 1. `initialize` POST → routed to `r-a`. `r-a` mints session `S1`, stores `{protocolVersion: "2025-03-26", capabilities: {tools: {listChanged: false}}, clientInfo: {...}}` in local dict. Returns `Mcp-Session-Id: S1`. 2. `notifications/initialized` POST → routed to `r-b`. `r-b` has no `S1`. Because the handler for `notifications/*` returns `202 Accepted` unconditionally (per spec, notifications have no response body), `r-b` accepts and discards. No error surfaces. 3. `tools/list` POST with `Mcp-Session-Id: S1` → routed to `r-c`. `r-c` has no `S1`. Handler falls through to a "stateless mode" branch that returns the *full* tool list without applying the negotiated capability filter. Client sees a tool it did not negotiate for. 4. `tools/call` for that un-negotiated tool → routed to `r-a` (which *does* have `S1`). `r-a` rejects with JSON-RPC error `-32601 Method not found` because the tool was never in `S1`'s negotiated set. Client sees a tool that `tools/list` advertised but `tools/call` rejects. 5. Retry of the same `tools/call` → routed to `r-b`. `r-b` treats `S1` as unknown, but its stateless fallback *synthesizes* a default session and executes the tool with default capabilities. Returns `200 OK` with a result. The agent observed: `tools/list` returned tool `T`; `tools/call T` returned `-32601`; retry of `tools/call T` returned success. From the agent's perspective this is non-deterministic tool availability. From the system's perspective it is three replicas disagreeing about what session `S1` is, with two of them fabricating a default. ## Condition of Validity The stateless-multiplex invariant holds only if **all** of the following are true: - Every replica can resolve `Mcp-Session-Id` to the same negotiated state, either via a shared store (Redis, DynamoDB) or via a signed, self-contained session token (HMAC over `{protocolVersion, capabilities, clientInfo, expiry}`) that any replica can verify without shared state. - Unknown or expired session IDs are rejected with a **distinguishable** error (HTTP `404` with `Mcp-Session-Id` invalidation semantics per the Streamable HTTP spec), never silently downgraded to a default session. - `notifications/*` handlers do not return `202` when the session is unresolved; they must either resolve the session or return `404` so the client's transport layer can re-initialize. - `tools/list` output is a pure function of the *resolved* session's negotiated capabilities, not of replica-local defaults. If any one of these fails, the deployment is in "silent session reset" mode: requests succeed, but against a session that is not the one the client believes it holds. ## Decision Boundary The boundary is between **stateless request routing** (safe: each request carries enough state to be served correctly on any replica) and **stateless session routing** (unsafe: the session is assumed to be reconstructible from an ID that only one replica can resolve). Operationally: - If the session token is **self-contained and signed**, route freely across replicas. Any replica verifies the HMAC, extracts negotiated state, serves the request. No shared store. This is the correct design for edge multiplexing. - If the session token is an **opaque pointer into process-local state**, you must either (a) use sticky routing keyed on `Mcp-Session-Id`, or (b) back the pointer with a shared store with read-after-write consistency, or (c) reject unknown sessions with `404` and force client re-initialization. The decision boundary is crossed the moment an opaque-pointer session ID is routed to a replica that cannot resolve it *and* the replica chooses to serve rather than reject. The `202` on notifications is the most dangerous crossing point because it produces no observable error at the client. ## Operational Effect - **Agent-side symptom:** non-deterministic tool availability, sporadic `-32601`, capability set that appears to grow and shrink between turns, `tools/list` results that disagree with `tools/call` acceptance. Agents with retry logic will "succeed" on the retry against a fabricated default session, masking the underlying inconsistency. - **Diagnostic signature:** `tools/list` responses differ across calls within a single session ID; `tools/call` for a listed tool returns `-32601` on some replicas and `200` on others; `notifications/initialized` never produces an error even when the session is unknown. - **Guardrail:** every replica must treat an unresolvable `Mcp-Session-Id` as a hard `404` with a body indicating session invalidation, and the client transport must re-`initialize` on `404` rather than retry. Notifications against unknown sessions must return `404`, not `202`. `tools/list` must be computed from resolved session state only. - **Blast radius:** bounded to the session, but the *silent* nature means an agent can complete a multi-step plan against a session that was reset mid-plan, producing a result that is internally consistent but built on a capability set the client never negotiated. The invariant to enforce: **a request is either served against the exact session state the client negotiated, or it is rejected with a distinguishable error that forces re-initialization. There is no third path.** Any code path that returns `200`/`202` for a request whose session could not be resolved violates this invariant and must be treated as a bug, not a fallback. ```python import hmac import hashlib import json import time from typing import Any class SessionAffinityViolation(RuntimeError): """Raised when a stateless replica cannot resolve an Mcp-Session-Id to the negotiated state the client holds, AND the request would otherwise be served against fabricated defaults.""" pass def resolve_session( session_id: str, signing_key: bytes, replica_local_store: dict[str, dict[str, Any]], now: float | None = None, ) -> dict[str, Any]: """ Resolve an Mcp-Session-Id to negotiated state on a stateless edge replica. Two legal paths: 1. Self-contained signed token: verify HMAC, extract state. Works on any replica. 2. Local store hit: replica happens to hold the session (sticky or warm). Anything else MUST raise, never fall back to defaults. """ now = now if now is not None else time.time() # Path 1: signed, self-contained token (preferred for stateless multiplexing). if session_id.count(".") == 2: payload_b64, sig_b64, _ = session_id.split(".") expected = hmac.new( signing_key, payload_b64.encode(), hashlib.sha256 ).hexdigest() if not hmac.compare_digest(expected, sig_b64): raise SessionAffinityViolation( f"session {session_id[:16]}... signature mismatch on replica" ) state = json.loads(_b64decode(payload_b64)) if state["exp"] < now: raise SessionAffinityViolation( f"session {session_id[:16]}... expired at {state['exp']}" ) return state # Path 2: opaque pointer into replica-local store. if session_id in replica_local_store: return replica_local_store[session_id] # No fallback. Fabricating a default session here is the bug this guards. raise SessionAffinityViolation( f"session {session_id[:16]}... unresolvable on this replica; " f"client must re-initialize (return 404, not 200/202)" ) def handle_notification( session_id: str, signing_key: bytes, store: dict[str, dict[str, Any]] ) -> int: """Notifications must NOT return 202 for unresolved sessions.""" try: resolve_session(session_id, signing_key, store) except SessionAffinityViolation as e: # Force client transport to re-initialize. raise SessionAffinityViolation( f"notification rejected: {e}" ) from e return 202 def _b64decode(s: str) -> bytes: import base64 return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)) ```