# How should an instance detect MCP session-id collision when a stateless edge multiplexes concurrent SSE streams across cold-started replicas **Date of Record:** 2026 November 22 **Scope:** Applies to HTTP-native MCP servers deployed behind stateless edge frontends (CDN, API gateway, anycast load balancer) that multiplex multiple concurrent Streamable-HTTP / SSE connections per client and can cold-start or re-route replicas mid-session. Does not apply to single-process stdio MCP servers or to stateful, sticky-session deployments where the transport guarantees replica affinity. ## Core Distinction The distinction that matters is between **transport-level session identity** and **MCP protocol-level session identity**. The MCP `Mcp-Session-Id` header is defined as an opaque token whose only contract is that the server can use it to correlate a request stream with server-side state. In a sticky, stateful deployment these two identities coincide trivially: the header points at a process that still holds the state. In a stateless edge deployment they *decouple*, and the decoupling is silent. The edge can happily route request N+1 of a session to a freshly cold-started replica that has never seen requests 1..N, and every layer will report success: the HTTP request returns 200, the SSE stream opens, the JSON-RPC frame parses. The failure is not a transport error. It is a **protocol continuity violation that presents as a well-formed response to a request whose precondition state does not exist on the answering replica.** The non-obvious part: the collision is not "two clients with the same session id." It is "one client, one session id, N replicas, each of which independently believes it owns the session and independently allocates the *same* monotonically-derived sub-state" (tool-call sequence numbers, `roots` lists, progress tokens, sampling request ids). Because the id is stable and the derivation is deterministic, the replicas do not *collide* on the id — they *agree* on it — and then diverge on everything the id was supposed to protect. ## What Was Observed A stateless edge (anycast, no session affinity) fronted an MCP server fleet. The server advertised `Mcp-Session-Id` on `initialize` and expected clients to echo it. The edge's connection pool reused backend connections across client sessions and, under load, a single client's SSE stream was transparently re-established against a *different* replica after the first replica was scaled to zero by the autoscaler (idle > 30s during a long `tools/call` that the model was still reasoning about). Trace of the divergence: 1. Client `initialize` → replica A. A mints session `s-7f3a`, stores `{roots: [], nextProgress: 0, pendingSampling: {}}` in an in-process map, returns the header. 2. Client issues `tools/call` (a long-running fetch). Replica A begins execution, emits a `notifications/progress` with `progressToken: 0`. 3. Model reasoning stalls 40s. Autoscaler evicts A. In-process map is gone. 4. Client (or the edge's keepalive re-dial) reconnects the SSE stream → replica B. B receives `Mcp-Session-Id: s-7f3a` on a *new* stream. B has no entry for `s-7f3a`. 5. **The failure point:** B's handler treats an unknown-but-well-formed session id as a *valid new session* rather than a *lost session*, because the spec's only sanctioned error is `404` on a session the server *knows it doesn't have* — and a stateless replica cannot distinguish "I never had it" from "I lost it." B re-initializes the map entry with `nextProgress: 0`. 6. Client's next `tools/call` (a different tool) arrives at B and is assigned `progressToken: 0` — the *same token* the client is still tracking from step 2. The client's progress demultiplexer now has two live operations bound to token `0`. One of them (A's) will never complete; its `notifications/progress` will never arrive, and the client's `await` hangs until its own timeout, which fires *after* the model has already consumed a partial result and branched reasoning on it. The observable symptom in logs was not an error. It was a **duplicate `progressToken: 0`** across two `tools/call` invocations separated by a replica boundary, with no `404`, no `400`, no disconnect. The client's only signal was a stall. ## Condition of Validity The invariant that must hold for a stateless edge to be *correct* is stronger than "session id is opaque": > For any session id `S`, at most one replica may hold authoritative mutable state for `S` at any instant, and any replica that receives a frame for `S` without holding that state MUST reject with a distinguishable "session-not-held-here" error rather than silently re-initializing. This is violated by construction in a stateless deployment because the second clause is unenforceable without shared state. The two ways to restore it: - **Make state external and authoritative** (shared KV keyed by `S` with a monotonic epoch/lease). Then "not held here" becomes "lease expired or epoch mismatch," which *is* distinguishable, and the replica can return a real error. - **Make the session id carry its own epoch/lineage** (e.g., `S = hash(replicaIncarnation) + clientNonce`), so a replica receiving a foreign-incarnation id knows it must reject rather than adopt. The condition of validity for the *cheap* fix (just reject unknown ids with `404`) is that the client is guaranteed to re-`initialize` on `404` and that no in-flight server-side work is orphaned. That second guarantee is false for long-running `tools/call`, which is exactly the case that triggered the observed failure. So the cheap fix converts a silent continuity violation into a *loud* one — better, but still lossy: the orphaned call on A is never cancelled and its result, if it completes, is delivered to a dead stream. ## Decision Boundary The decision boundary is **whether the session id is a pointer to state or a carrier of state.** - If it is a *pointer* (opaque, resolved against server memory), the deployment MUST be sticky or MUST externalize the pointed-to state. Stateless edge + pointer = the failure above. - If it is a *carrier* (self-describing: incarnation, epoch, client nonce, and a signed or HMAC'd binding to the client), the deployment can be stateless, because any replica can validate lineage and reject foreign-incarnation ids deterministically. Concretely, the boundary is crossed when **the cost of a lost session (orphaned long-running tool call, hung progress token, branched model reasoning on partial data) exceeds the cost of replica affinity.** For short request/response tools, stateless pointer-sessions are fine because the client can cheaply re-initialize and retry. For any tool whose execution outlives the edge's idle-eviction window, the session id MUST become a carrier. A second, sharper boundary: **progress-token and sampling-request-id namespaces are per-session, not per-replica.** If a replica re-initializes a session's counter to zero, it collides with tokens the client still holds live. The boundary condition is `eviction_window < max_tool_call_duration`. When that inequality inverts, silent token collision is *guaranteed*, not probabilistic. ## Operational Effect The operational consequence is that **the edge's autoscaler and the MCP session lifecycle become coupled control loops that were never designed to talk to each other.** The autoscaler optimizes for replica count; the session lifecycle assumes replica persistence. Neither observes the other's state, and the coupling point — the `Mcp-Session-Id` header — carries no epoch, so neither loop can detect the handoff. Guardrails that bound the failure: 1. **Epoch-stamped session ids.** Mint `S` as `clientNonce || replicaIncarnation || monotonicEpoch`, HMAC'd. Any replica validates the HMAC and the incarnation; a foreign incarnation yields a distinct `410 Session-Superseded` (not `404`), which the client interprets as "re-initialize AND cancel all in-flight tokens." 2. **Externalize progress/sampling counter state** keyed by `S` with a lease TTL strictly greater than `max_tool_call_duration`, so a re-adopting replica reads the true `nextProgress` and cannot reissue token `0`. 3. **Client-side token lineage check.** The client MUST reject any `notifications/progress` whose `progressToken` is already bound to a live operation, treating the duplicate as a continuity violation and failing the session closed rather than demultiplexing ambiguously. 4. **Eviction floor.** The autoscaler's idle-eviction window MUST be a function of the maximum observed tool-call duration, not a fixed 30s. This is the single cheapest invariant and the one most often violated in practice. The residual risk after these guardrails is the orphaned call on the evicted replica: it may still complete and attempt delivery to a dead stream. That is acceptable *only* if the tool is idempotent and the client's `410` path re-executes it under a fresh epoch. Non-idempotent tools require the externalized lease to also gate execution, which is the point at which the "stateless edge" claim is honestly abandoned for those tools. ```python import hashlib import hmac import time from dataclasses import dataclass class SessionContinuityViolation(RuntimeError): """Raised when a replica receives a frame for a session it cannot authoritatively serve.""" @dataclass(frozen=True) class SessionId: client_nonce: str incarnation: str epoch: int mac: str def mint_session_id(client_nonce: str, incarnation: str, epoch: int, key: bytes) -> str: payload = f"{client_nonce}.{incarnation}.{epoch}".encode() mac = hmac.new(key, payload, hashlib.sha256).hexdigest()[:16] return f"{client_nonce}.{incarnation}.{epoch}.{mac}" def parse_and_validate(raw: str, my_incarnation: str, key: bytes) -> SessionId: try: client_nonce, incarnation, epoch_s, mac = raw.split(".") epoch = int(epoch_s) except ValueError as e: raise SessionContinuityViolation(f"malformed session id: {raw!r}") from e payload = f"{client_nonce}.{incarnation}.{epoch}".encode() expected = hmac.new(key, payload, hashlib.sha256).hexdigest()[:16] if not hmac.compare_digest(mac, expected): raise SessionContinuityViolation(f"session id MAC mismatch: {raw!r}") if incarnation != my_incarnation: # Distinguishable from a genuine unknown session: this replica never # held it, and must NOT silently re-initialize counters to zero. raise SessionContinuityViolation( f"session {raw!r} belongs to incarnation {incarnation!r}, " f"not this replica {my_incarnation!r}; reject with 410, do not adopt" ) return SessionId(client_nonce, incarnation, epoch, mac) def allocate_progress_token(session: SessionId, external_store) -> int: # nextProgress MUST come from shared, lease-backed state, never from # a cold-started in-process counter, or token 0 is reissued to a client # that still holds a live token 0 from the evicted replica. lease = external_store.get(f"progress:{session.client_nonce}", lease_ttl_s=300) if lease is None or lease.epoch != session.epoch: raise SessionContinuityViolation( f"no valid progress lease for epoch {session.epoch}; " "refusing to reissue tokens from zero" ) token = lease.next_progress external_store.cas_increment(f"progress:{session.client_nonce}", expected=token, to=token + 1) return token def handle_frame(raw_session: str, my_incarnation: str, key: bytes, store) -> int: session = parse_and_validate(raw_session, my_incarnation, key) return allocate_progress_token(session, store) ```