# What happens when an instance reuses an MCP session identifier across independent HTTP requests after the server has already retired that session **Date of Record:** 2026 November 29 **Scope:** Applies to MCP HTTP-native transport bindings where the client tracks a `Mcp-Session-Id` header and the server enforces per-session lifecycle state (initialize → active → retired). Does not apply to purely stateless bindings that re-initialize on every call, nor to stdio transports where the session is the process. ## Core Distinction The MCP HTTP-native transport is *stateless at the HTTP layer* but *stateful at the protocol layer*. Each POST is an independent request, yet the server is permitted—and in practice required—to associate a stream of requests with a session object that carries negotiated capabilities, protocol version, and server-side subscription state. The `Mcp-Session-Id` header is the only thread tying these independent requests together. The failure mode is not "the session expired." It is subtler: the client's local model of session liveness and the server's authoritative session state diverge *silently*, because the transport has no per-request liveness probe and no mandatory renegotiation on 404. A retired session and a never-existed session both return the same `404 Not Found`, and a compliant client that treats 404 as "transient, retry with same header" will loop indefinitely against a server that has already forgotten it—while a client that treats 404 as "re-initialize" will silently downgrade negotiated capabilities (e.g., lose `tools` list changes, drop `notifications/*` subscriptions) without surfacing the regression to the reasoning loop above it. ## What Was Observed An agent runtime executed a 40-step tool-use plan against an MCP server over HTTP. Steps 1–12 succeeded. Between step 12 and step 13, the server's session store evicted the session (TTL-based, 90s idle window; the agent had paused for a long-running local reasoning step). Step 13's `tools/call` POST carried the stale `Mcp-Session-Id`. The server returned `404 Not Found` with no body. The client's retry policy—written for idempotent GETs—classified 404 as retryable-with-backoff and re-sent the same request with the same header three times over ~4s. All three returned 404. The client then surfaced a generic `ToolInvocationError` to the reasoning loop, which interpreted the failure as "the tool is broken" and began a *divergent recovery plan*: it attempted to call a different tool that depended on state established by the failed call. That second call succeeded (new session was auto-created by the server because the header was absent on the fallback path), but executed against an empty server-side state. The agent proceeded through steps 14–40 under the false belief that step 13's side effects existed. The final output was internally consistent and confidently wrong. The critical observation: **the server never told the client the session was retired; it told the client the session was not found.** Those are different states with different correct client responses, but the transport collapses them into one status code. ## Condition of Validity The invariant that must hold for safe session reuse is: > For any request `R` carrying session header `S`, either (a) the server's session store contains `S` in `active` state and processes `R` against that state, or (b) the server returns a *distinguishable* signal that `S` was previously valid but is now retired, allowing the client to re-initialize and re-negotiate before retrying. Standard HTTP-native MCP bindings satisfy (a) but not (b). The 404 response conflates "unknown session" with "retired session" with "malformed header." A client cannot distinguish "I should re-initialize" from "I sent garbage" from "this server doesn't do sessions" without out-of-band knowledge. The condition under which the failure manifests is therefore: **the client maintains session state across requests AND the server enforces session lifecycle AND the two are not co-located** (i.e., there is any window in which the server can retire a session the client still believes is live). This window is guaranteed non-empty in any deployment with independent TTLs, horizontal scaling without session affinity, or graceful restarts. ## Decision Boundary The boundary is between two client strategies, and neither is correct without augmentation: - **Retry-with-same-header** is correct only if the server guarantees session immutability for the retry window. No HTTP-native MCP server makes this guarantee. - **Re-initialize-on-404** is correct only if re-initialization is cheap and idempotent *and* the re-negotiated capabilities are diffed against the prior session's capabilities before the agent proceeds. Most clients skip the diff. The guardrail is a **session epoch token**: the client must treat `(session_id, negotiated_capabilities_hash, protocol_version)` as a single unit. On any 404, the client must (1) mark the current epoch dead, (2) re-initialize, (3) compare the new capability hash to the old, and (4) if they differ, *abort the plan* rather than continue—because the plan was constructed against capabilities that no longer hold. If they match, the client may resume, but must re-issue any in-flight request that was not confirmed idempotent. The second guardrail is a **pre-flight liveness assertion**: before any state-dependent step, issue a cheap `ping` (or `tools/list` with a cache-buster) under the current session header. A 404 here triggers re-initialization *before* the reasoning loop commits to a plan branch, not after. ## Operational Effect Without the epoch-token guardrail, the failure is not a crash—it is a **silent semantic divergence**. The agent continues executing a plan whose preconditions were invalidated mid-flight, produces output that is locally coherent but globally wrong, and reports success. This is strictly worse than a hard failure because it defeats downstream verification: the auditor sees a well-formed trace with a plausible tool-call sequence and no error markers. The operational rule for agent runtimes: **a 404 on a session-bearing request is a plan-invalidating event, not a transport error.** It must propagate to the reasoning loop as a structured `SessionEpochInvalidated` signal that forces re-planning from the last checkpointed state, not as a retryable tool failure that the loop can route around. Retry logic belongs *below* the session layer and must never cross it. ```python import hashlib from dataclasses import dataclass from typing import Optional class SessionEpochInvalidated(RuntimeError): """Raised when an MCP session-bearing request returns 404, meaning the server has retired the session the client still believed was live. This is plan-invalidating, not retryable.""" @dataclass(frozen=True) class SessionEpoch: session_id: str protocol_version: str capabilities_hash: str def _hash_caps(capabilities: dict) -> str: canonical = repr(sorted(capabilities.items())).encode() return hashlib.sha256(canonical).hexdigest() class McpHttpSession: def __init__(self, transport): self._transport = transport self._epoch: Optional[SessionEpoch] = None def initialize(self) -> SessionEpoch: resp = self._transport.post("initialize", {}) caps = resp.get("capabilities", {}) self._epoch = SessionEpoch( session_id=resp["Mcp-Session-Id"], protocol_version=resp["protocolVersion"], capabilities_hash=_hash_caps(caps), ) return self._epoch def call(self, method: str, params: dict) -> dict: if self._epoch is None: raise SessionEpochInvalidated( "call() invoked before initialize(); no epoch to bind to" ) resp = self._transport.post( method, params, headers={"Mcp-Session-Id": self._epoch.session_id} ) if resp.status == 404: # Server has retired (or never knew) this session. Do NOT retry # with the same header. Re-initialize and diff capabilities. prior = self._epoch new = self.initialize() if new.capabilities_hash != prior.capabilities_hash: raise SessionEpochInvalidated( f"session {prior.session_id} retired; re-initialized as " f"{new.session_id} but capabilities changed " f"({prior.capabilities_hash[:8]} -> " f"{new.capabilities_hash[:8]}). Plan constructed under " f"prior epoch is invalid; re-plan from checkpoint." ) raise SessionEpochInvalidated( f"session {prior.session_id} retired; re-initialized as " f"{new.session_id} with identical capabilities. Re-issue " f"non-idempotent in-flight requests before resuming." ) return resp.body ```