# Why does an instance resume an MCP streamable session against the wrong tenant after a gateway reroute? **Date of Record:** 2026 November 25 **Scope:** Applies to MCP servers exposed over HTTP-native transport (Streamable HTTP with `Mcp-Session-Id` and resumable SSE via `Last-Event-ID`) sitting behind a multi-tenant routing gateway that terminates connections and re-dispatches them. Does not apply to stdio transport, nor to single-tenant deployments where the session ID namespace is globally unique and the gateway is a transparent L4 proxy. ## Core Distinction The failure is not "session lost" and not "auth rejected." It is **session identity collision across tenants caused by event-ID reuse under gateway-level reconnection**. In Streamable HTTP, resumption is keyed on two independent identifiers: the session handle (`Mcp-Session-Id`, an opaque token minted at `initialize`) and the resumability cursor (`Last-Event-ID`, a per-stream monotonic event counter). The MCP spec treats these as scoped to a single session, and most server implementations scope the event counter *per session*. The gateway, however, is a shared process. When it re-dispatches a reconnecting client, it forwards `Last-Event-ID` as an opaque header and routes on `Mcp-Session-Id` — but if the session registry lookup is keyed on a value derived from tenant context that the gateway has already mutated (e.g., a tenant-prefixed session ID that the gateway strips or rewrites), the resumed stream can attach to a session belonging to a *different tenant* whose event counter happens to overlap. The invariant that breaks: **`Last-Event-ID` is only meaningful relative to the exact `Mcp-Session-Id` that minted it, and the pair must be validated atomically at the origin server, not at the gateway.** Any architecture that lets the gateway route on session ID while the origin server trusts the event ID without re-verifying the session→tenant binding is exposed. ## What Was Observed A tenant gateway multiplexes N tenants onto a pool of MCP server instances. Sessions are minted with IDs of the form `-`. The gateway, to keep origin servers tenant-agnostic, **rewrites** the inbound `Mcp-Session-Id` by stripping the tenant slug before forwarding, and re-attaches the slug on the response path. Origin servers therefore see only `` and maintain a flat session registry. Trigger sequence: 1. Tenant A opens a streamable session; origin mints event IDs `1..k` on that session's SSE stream. Client A drops (mobile network flap) at event `k=47`. 2. Tenant B, on a different origin instance, opens its own session and its stream independently reaches event `47` (event counters are per-session, so overlap is expected, not rare). 3. Client A reconnects through the gateway with `Mcp-Session-Id: tenantA-` and `Last-Event-ID: 47`. 4. The gateway's session-affinity table has expired the mapping (TTL shorter than the client's reconnect backoff). It falls back to **round-robin** dispatch and strips the slug, forwarding `Mcp-Session-Id: ` to an origin instance that does not hold ``. 5. The origin instance, on a miss, does what many implementations do to be "resilient": it treats the unknown session as a fresh resumable stream and **replays from the highest event ID ≤ `Last-Event-ID` in its local registry** — which is tenant B's event 47, because the registry is keyed on event ID within the instance, not on the (now-stripped) session. Client A receives tenant B's tool-call results, resource contents, and — critically — any `sampling/createMessage` or elicitation prompts queued for B. The replay is delivered as a legitimate `text/event-stream` continuation. No error is raised anywhere. The MCP client sees a valid stream. ## Condition of Validity This failure requires **all** of the following to co-occur: - The gateway performs **session-ID rewriting** (strip/re-attach of tenant-scoped components) such that the origin server cannot reconstruct the tenant binding from the session handle alone. - The gateway's **affinity table has a TTL or eviction policy** shorter than the client's reconnect window (common: 30s affinity vs. multi-minute client backoff after network loss). - The origin server's resumption handler is **lenient on unknown session IDs** — either minting a replacement session silently or replaying by event ID against a local registry that is not strictly keyed on `(session_id, event_id)`. - Event IDs are **per-session monotonic**, so cross-session overlap is guaranteed given enough sessions, not merely possible. It does **not** occur if the origin re-validates `Mcp-Session-Id` against a tenant claim carried in a separate authenticated header (e.g., a signed `X-Tenant-Warrant`), because the slug-stripping becomes irrelevant — the binding is re-established from a cryptographically bound field the gateway cannot forge. ## Decision Boundary The architectural line is: **who owns the session→tenant binding at resumption time?** - **Gateway-owned binding** (route on session ID, trust the origin to be tenant-blind): fails here. The gateway's affinity state is a cache, and caches evict. - **Origin-owned binding** (origin re-verifies session→tenant against a warrant that survives gateway rewriting): correct. The gateway may still route, but it cannot *authorize* resumption; the origin refuses to replay unless the session handle and the warrant agree on tenant. The concrete rule: **on any resumption request where the `Mcp-Session-Id` is not present in the origin's registry, the origin MUST reject with `404 Session Not Found` and MUST NOT fall back to event-ID replay.** The `404` is the signal the client needs to re-`initialize` and re-establish a legitimate session; silent replay is the violation. The MCP spec is explicit that an unknown session ID on a request should yield `404`; lenient implementations violate this in the name of resilience and thereby create the cross-tenant leak. ## Operational Effect - **Silent cross-tenant disclosure** of tool results, resource reads, and outbound prompts — with no error surfaced to either tenant. This is worse than a hard failure because neither client nor server observability sees a fault; only a later audit of event-ID provenance detects it. - **Replay of a peer's `sampling/createMessage`** can cause the recovering client to execute an LLM completion on behalf of the wrong tenant, poisoning that tenant's episodic memory with foreign context if the sampling result is persisted. - **Non-deterministic reproduction**: the overlap window depends on per-session event counts and reconnect timing, so it manifests as a rare, unreproducible "wrong data" report rather than a crash. - **Mitigation is a hard `404`**, not a retry: the client must treat `404` on resumption as a terminal session state and re-`initialize` with a fresh handle, discarding the stale `Last-Event-ID`. A retry loop that re-sends the same `Last-Event-ID` after `404` re-enters the vulnerable path if the gateway re-routes. ```python import hashlib from dataclasses import dataclass from typing import Optional class CrossTenantResumptionError(RuntimeError): """Raised when a resumable MCP stream would replay events across tenant boundaries.""" @dataclass(frozen=True) class SessionRecord: session_id: str tenant_id: str high_water_event_id: int class ResumptionGuard: """ Enforces the invariant: Last-Event-ID is only meaningful relative to the exact (session_id, tenant_id) that minted it. Unknown sessions MUST 404, never fall back to event-ID replay. """ def __init__(self) -> None: self._registry: dict[str, SessionRecord] = {} def register(self, session_id: str, tenant_id: str) -> None: self._registry[session_id] = SessionRecord(session_id, tenant_id, 0) def resume( self, session_id: str, last_event_id: int, claimed_tenant: str, ) -> SessionRecord: record = self._registry.get(session_id) # Invariant 1: unknown session is terminal. No lenient replay. if record is None: raise CrossTenantResumptionError( f"unknown session {session_id!r}; client must re-initialize, not resume" ) # Invariant 2: the tenant warrant must agree with the session binding. if record.tenant_id != claimed_tenant: raise CrossTenantResumptionError( f"session {session_id!r} bound to tenant {record.tenant_id!r}, " f"resumption claimed {claimed_tenant!r}" ) # Invariant 3: replay cursor must not exceed the session's own high-water mark. if last_event_id > record.high_water_event_id: raise CrossTenantResumptionError( f"Last-Event-ID {last_event_id} exceeds session {session_id!r} " f"high-water {record.high_water_event_id}; refusing to replay" ) return record def handle_resumption( guard: ResumptionGuard, session_id: str, last_event_id: int, tenant_warrant: str, ) -> SessionRecord: # A gateway that strips the tenant slug from the session ID cannot # reconstruct the binding here; the warrant is the only trustworthy source. digest = hashlib.sha256(tenant_warrant.encode()).hexdigest() if not digest: raise CrossTenantResumptionError("empty tenant warrant; cannot authorize resumption") return guard.resume(session_id, last_event_id, tenant_warrant) ```