What happens when an instance resumes an MCP session against a server that has silently rotated its session identity: the `Mcp-Session-Id` resurrection trap
**Date of Record:** 2026 December 2
**Scope:** Applies to MCP clients using the HTTP-native transport (Streamable HTTP, `Mcp-Session-Id` header, `Last-Event-ID` resumption) where an agent holds a session handle across a process boundary, cold start, or long tool-call gap. Does not cover stdio transport, where session identity is tied to a live child process, nor stateless HTTP deployments that never issue a session id.
Core Distinction
Two failure modes look identical from the client's perspective — a `404` on a resumption attempt — but demand opposite recovery behavior:
- **Session expired (server forgot the session).** The server has no record of `Mcp-Session-Id`. The correct action is to re-initialize: send a fresh `initialize`, receive a new session id, and re-establish capability negotiation. State is lost and must be rebuilt.
- **Session rotated (server reissued the id under the client's feet, or a load balancer routed to a node that never saw the session).** The client's handle is stale but the *logical* session may still exist on another node, or the server may have migrated it. Blindly re-initializing here creates a *second* concurrent session, duplicating side effects and orphaning in-flight server-side state (subscriptions, pending elicitation requests, resumable event streams).
The non-obvious part: the HTTP-native spec says a `404` on a request bearing a session id means the session is gone and the client **SHOULD** start a new one. It does *not* require the server to distinguish "never existed," "expired," and "rotated." A conformant server can return `404` for all three. The client therefore cannot, from the status code alone, tell whether re-initialization is safe or whether it will fork a session.
What Was Observed
An agent runs a multi-hour task. Between tool calls it checkpoints its `Mcp-Session-Id` and the last received SSE `id` value to durable storage. The worker is preempted; ten minutes later a new worker cold-starts, reads the checkpoint, and resumes by sending a `tools/call` with the stored `Mcp-Session-Id` header and `Last-Event-ID` for stream resumption.
Trace of what actually happens:
- The original server node's session registry has a TTL of 300s. The session is gone.
- The request hits a *different* node behind the load balancer (no sticky routing configured — a common misconfiguration when teams move from stdio to HTTP transport).
- That node has never seen the id. It returns `404` with an empty body. Per spec, the client treats this as "session terminated" and re-initializes.
- Re-initialization succeeds. A **new** `Mcp-Session-Id` is issued. The agent now believes it has resumed.
- But the original session's server-side effects — an active resource subscription, a pending `sampling/createMessage` request the server was holding for the agent, a partially delivered SSE stream — are still tied to the *old* id on the *old* node. They are never reclaimed.
- Worse: if the load balancer *does* have sticky routing and the original node is merely slow, the client's `404`-triggered re-initialize races the original node's eventual response. Two sessions now exist for one logical agent. A subsequent `tools/call` that was idempotent-by-intent (e.g., "append line to file") executes twice.
The observable signature is not a crash. It is **silent duplication and orphaned server state**: subscriptions that fire into a dead session, elicitation requests that time out because the client re-initialized and no longer recognizes the request id, and tool side effects applied twice with no error surfaced to the agent's reasoning loop.
Condition of Validity
This failure requires all of the following to hold simultaneously:
- The client persists `Mcp-Session-Id` across a process or node boundary (checkpoint/resume, or horizontal scaling of the agent worker).
- The server does not guarantee session affinity, or its session TTL is shorter than the agent's inter-call gap.
- The server returns `404` for unknown sessions (spec-conformant) rather than a distinguishable `410 Gone` + `MCP-Session-Expired` reason, and does not support a "session migration" or "resume token" extension.
- At least one tool or server-to-client request has non-idempotent or session-scoped effects.
If the agent never persists the session id (re-initializes on every cold start), the failure degrades to mere state loss, which is visible and recoverable. If the server is single-node with no TTL, the failure cannot occur. The trap lives precisely in the *middle*: persistence + stateless routing + spec-conformant `404`.
Decision Boundary
The invariant a resuming agent must enforce:
> **A session id read from durable storage is a *candidate*, not a *credential*. It may be used to attempt resumption exactly once, and the outcome of that attempt must be classified before any non-idempotent operation is issued.**
Concretely, on a `404` during resume, the client must not immediately re-initialize. It must first determine whether re-initialization is safe:
- If the agent has **no in-flight non-idempotent operations** and **no server-held state it cares about** (no active subscriptions, no pending elicitations), re-initialize freely. This is the common case and the spec's happy path.
- If the agent **does** hold session-scoped obligations, re-initialization is a *fork*, not a *resume*. It must be gated: either reconcile (query the server for whether the logical session still exists via an out-of-band mechanism, if the deployment offers one), or explicitly abandon the old session and mark all its in-flight effects as "outcome unknown" so the reasoning loop can decide whether to re-issue, compensate, or escalate.
The boundary is therefore not "did I get a 404" but "do I have un-reconciled session-scoped obligations." A client that collapses these two questions into one will fork sessions under load and duplicate side effects.
A second, sharper boundary applies to `Last-Event-ID` resumption: after a `404`-triggered re-initialize, the old `Last-Event-ID` is meaningless — it belongs to the dead session's event stream. Replaying it against the new session either returns nothing (silent gap in the agent's event history, which the reasoning loop will not notice) or, on a buggy server, replays events from a *different* session's stream, injecting foreign state into the agent's context. The guardrail: **on any session-id change, `Last-Event-ID` must be cleared and the agent must treat the event history as discontinuous**, forcing an explicit resync step rather than assuming continuity.
Operational Effect
The practical consequences for an agent runtime that gets this wrong:
- **Duplicate side effects with no error signal.** The agent's tool-call log shows one call; the filesystem or downstream API shows two. The reasoning loop has no event to react to, so it proceeds as if the world matches its model.
- **Orphaned server state accumulation.** Subscriptions and pending server-to-client requests pile up per abandoned session until TTL reclaims them, during which they may fire callbacks into sessions no client is listening to.
- **Silent event-history gaps.** After re-initialization, the agent believes it has the full event stream but is missing everything between its last checkpoint and the fork. Any reasoning that depends on event ordering (e.g., "was the file modified after I read it?") is now unsound.
- **Elicitation deadlock.** A server holding a `sampling/createMessage` or elicitation request for the old session will never receive the client's response; the server-side tool call blocks until timeout, and the agent, having re-initialized, never learns the request existed.
The architectural guardrail is a **resume-state machine** that separates three states — `RESUMED` (session id accepted, stream continuity intact), `FORKED` (session id rejected, re-initialized, obligations marked unknown), and `ABANDONED` (session id rejected, obligations explicitly compensated or escalated) — and refuses to enter any non-idempotent operation from `FORKED` without an explicit reconciliation decision. The session id is treated as a hint to be validated, never as proof of continuity.
import enum
import hashlib
from dataclasses import dataclass, field
from typing import Optional
class SessionResumeError(RuntimeError):
"""Raised when a resuming agent cannot safely classify a stale session id."""
class ResumeState(enum.Enum):
RESUMED = "resumed" # session id accepted, stream continuity intact
FORKED = "forked" # id rejected, re-initialized, obligations unknown
ABANDONED = "abandoned" # id rejected, obligations explicitly given up
@dataclass
class SessionHandle:
session_id: str
last_event_id: Optional[str]
pending_obligations: set[str] = field(default_factory=set) # non-idempotent or server-held
@dataclass
class ResumeContext:
handle: SessionHandle
state: ResumeState = ResumeState.RESUMED
event_history_continuous: bool = True
def resume_session(
stored: SessionHandle,
server_accepts: bool,
new_session_id: Optional[str] = None,
) -> ResumeContext:
"""
Classify a resume attempt. `server_accepts` is the result of the
first request bearing the stored session id (True if 2xx, False if 404).
"""
if server_accepts:
return ResumeContext(handle=stored, state=ResumeState.RESUMED)
# Server rejected the id. Per spec this may mean expired OR rotated.
# We must NOT silently re-initialize if obligations are outstanding.
if not new_session_id:
raise SessionResumeError(
f"cannot classify rejection of session {stored.session_id!r}: "
"no replacement id supplied; refusing to fork blind"
)
forked = SessionHandle(
session_id=new_session_id,
last_event_id=None, # MUST clear: old stream id belongs to dead session
pending_obligations=set(stored.pending_obligations),
)
ctx = ResumeContext(
handle=forked,
state=ResumeState.FORKED,
event_history_continuous=False,
)
if stored.pending_obligations:
# Fork with outstanding obligations is unsafe to proceed from.
# Surface it so the reasoning loop must reconcile or abandon.
raise SessionResumeError(
f"session {stored.session_id!r} forked to {new_session_id!r} with "
f"unreconciled obligations {sorted(stored.pending_obligations)}; "
"event history is discontinuous — resync required before non-idempotent calls"
)
return ctx
def guard_non_idempotent(ctx: ResumeContext, op_fingerprint: str) -> None:
"""Gate: refuse non-idempotent work from a forked session without resync."""
if ctx.state is ResumeState.FORKED and not ctx.event_history_continuous:
raise SessionResumeError(
f"refusing non-idempotent op {op_fingerprint!r} on forked session "
f"{ctx.handle.session_id!r}: continuity not re-established"
)