How does an instance detect scope bleed when an HTTP-native MCP server multiplexes concurrent requests over a shared session

**Date of Record:** 2026 December 2 **Scope:** Applies to HTTP-native MCP servers that multiplex multiple tool-call requests over a single persistent transport (SSE stream, session-bound connection pool, or streamable-HTTP session) while carrying per-request authorization scopes. Does not apply to stdio MCP servers with one client per process, nor to stateless per-request HTTP where each call renegotiates its own auth context.

Core Distinction

There are two ways an HTTP-native MCP server can carry authorization: **transport-scoped** and **request-scoped**. Transport-scoped auth binds a scope to the session at handshake (`initialize` → `Mcp-Session-Id`), and every subsequent `tools/call` on that session inherits it. Request-scoped auth re-reads the bearer token, capability claim, or delegation warrant on each `tools/call` message and resolves scope per-call.

The failure mode lives in the seam: a server that *advertises* request-scoped authorization but *implements* scope resolution against the session object. When two logical principals (say, an orchestrator agent acting on behalf of user A, and an auditor agent acting on behalf of user B) multiplex over one session to amortize connection setup, the second principal's `tools/call` is authorized against the first principal's cached scope. The tool executes with A's privileges on B's behalf. Nothing in the JSON-RPC envelope looks wrong; the request ID is unique, the token is valid, and the tool returns `200 OK`. The bleed is invisible at the wire layer and only detectable by comparing the *effective* scope of the executed call against the *declared* scope of the request.

What Was Observed

A three-agent pipeline (planner, executor, auditor) shared one MCP session to a filesystem + database server. The server's `initialize` handler populated a `SessionContext` with the caller's scopes; the `tools/call` handler read `ctx.scope` off that session object rather than re-deriving it from the per-message `Authorization` header. The header *was* present and *was* validated — but the validated scope was written to the session, overwriting the previous value, and the tool handler read it after a race window.

Trace of the failing sequence:

  1. Planner opens session `S1`, sends `initialize` with token `T_planner` (scopes: `fs:read`, `db:read`). Server sets `S1.scope = {fs:read, db:read}`.
  2. Executor, sharing `S1`, sends `tools/call` `db.write` with token `T_executor` (scopes: `db:write`). Server validates `T_executor`, sets `S1.scope = {db:write}`, then dispatches. Handler reads `S1.scope` — correct by luck.
  3. Auditor concurrently sends `tools/call` `fs.read` with token `T_auditor` (scopes: `fs:read`, `audit:write`). Server validates `T_auditor`, sets `S1.scope = {fs:read, audit:write}`.
  4. Executor's handler — still mid-execution from step 2, having already passed its scope check but not yet committed — re-reads `S1.scope` inside a downstream guard for a second resource (`db.write` → `db.write` + `db.read`). It now sees `{fs:read, audit:write}`. The `db.read` guard fails and the transaction aborts *after* the write landed.
  5. Auditor's `fs.read` succeeds, but its subsequent `audit:write` (a separate `tools/call`) reads `S1.scope` after Executor's next call reset it to `{db:write}` and is rejected.

Net result: a committed database write with no corresponding audit record, and a spurious authorization failure on a legitimate call. Both errors are silent — one is a missing row, the other a `403` the client retries, and the retry succeeds against yet another scope state.

Condition of Validity

The invariant that must hold is: **for any `tools/call` message `m` on session `S`, the scope used to authorize every resource access within `m`'s execution is a pure function of `m`'s own credentials, not of `S`.**

This invariant is violated whenever three conditions co-occur:

If any one condition is absent, the bleed cannot occur: single-principal sessions are safe; immutable per-call scope arguments are safe; strictly serialized single-read handlers are safe. The dangerous case is the *combination*, which is exactly the configuration teams adopt for throughput.

Note the subtlety: a server can be fully compliant with the MCP spec's session semantics and still exhibit this. The spec requires session identity; it does not mandate that authorization state be immutable per-message. The gap is architectural, not protocol-level.

Decision Boundary

An instance must decide, per `tools/call`, whether to trust the session's cached scope or re-derive scope from the message. The correct decision boundary is:

The boundary is crossed the moment a handler authorizes a resource access against session state that was written by a *different* message. Detection requires tagging each scope resolution with the request ID that produced it and asserting, at every resource guard, that the tag matches the current request ID.

Operational Effect

Consequences of undetected bleed, in order of severity:

  1. **Privilege escalation across principals.** A low-privilege agent's call executes with a co-tenant's higher privileges. This is a security boundary failure, not a correctness bug, and it will not appear in functional tests because the tool *works*.
  2. **Orphaned side effects.** Writes that commit before the scope re-read fails leave state with no audit trail — the exact condition auditors exist to prevent.
  3. **Non-deterministic authorization.** The same call succeeds or fails depending on concurrent traffic. Retry logic masks the failure and amplifies it (each retry perturbs the shared scope again).
  4. **Replay divergence.** An auditor replaying the request log against a fresh server cannot reproduce outcomes, because the outcome depended on interleaving that the log doesn't capture. Verification replay discrepancies become unexplained.

Mitigation is architectural, not defensive: thread an immutable `CallScope` object from message parse through every handler frame; forbid handlers from reading session auth state; add a request-ID assertion at each resource guard; and expose a `scope_provenance` field in tool-call telemetry so post-hoc analysis can detect bleed after the fact. The guardrail must be a compile-time or dispatch-time constraint, because the failure is invisible at runtime from any single vantage point.

import threading
from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeBleedError(RuntimeError):
    """Raised when a resource access is authorized against a scope that was
    produced by a different request than the one currently executing."""


@dataclass(frozen=True)
class CallScope:
    request_id: str
    resources: FrozenSet[str]


class SessionContext:
    """Mutable session state. Authorization must NEVER read from here."""

    def __init__(self) -> None:
        self._lock = threading.Lock()
        self._cached_scope: CallScope | None = None

    def store_scope(self, scope: CallScope) -> None:
        with self._lock:
            self._cached_scope = scope

    def peek_scope(self) -> CallScope | None:
        with self._lock:
            return self._cached_scope


def authorize(
    scope: CallScope,
    current_request_id: str,
    resource: str,
) -> None:
    """Assert that `resource` is covered by `scope`, and that `scope` was
    derived from the currently executing request. Fails closed on mismatch."""
    if scope.request_id != current_request_id:
        raise ScopeBleedError(
            f"scope for request {scope.request_id!r} used while executing "
            f"request {current_request_id!r}"
        )
    if resource not in scope.resources:
        raise ScopeBleedError(
            f"request {current_request_id!r} lacks scope for resource {resource!r}; "
            f"has {sorted(scope.resources)}"
        )


def handle_tool_call(
    session: SessionContext,
    request_id: str,
    declared_scope: CallScope,
    resources: list[str],
) -> None:
    # Bind scope to this request; do not read session auth state.
    if declared_scope.request_id != request_id:
        raise ScopeBleedError(
            f"declared scope {declared_scope.request_id!r} does not match "
            f"request {request_id!r}"
        )
    # Detect if another principal has mutated the session mid-flight.
    cached = session.peek_scope()
    if cached is not None and cached.request_id != request_id:
        # Informational only: authorization below uses declared_scope.
        pass
    for resource in resources:
        authorize(declared_scope, request_id, resource)
    session.store_scope(declared_scope)