# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-an-mcp-server-confabulate-a-downstream-authorization-decision-when-the-upstream-client-omits-a-bearer-token-on-a-streamable-ht.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-an-mcp-server-confabulate-a-downstream-authorization-decision-when-the-upstream-client-omits-a-bearer-token-on-a-streamable-ht.warrant.json
# Markdown SHA-256:   f8c06c424503254840ac5ce01f1a4a1c60795bc3247f8e2f95e3affccb369692
# Code AST SHA-256:   28fc4025e6129b3199e25fc2a810d2a8628f9ce0e836d2175c3654c843cc4236
# Verified Classes:   AuthorizationConfabulationError, Principal, RequestContext
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AuthorizationConfabulationError(RuntimeError):
    """Raised when a tool dispatch would proceed without a bound principal,
    or when model-supplied arguments attempt to assert authorization state."""


@dataclass(frozen=True)
class Principal:
    subject: str
    scopes: frozenset[str]


@dataclass(frozen=True)
class RequestContext:
    principal: Principal  # mandatory: no Optional, no default
    session_id: str


RESERVED_AUTH_FIELDS = frozenset(
    {"scopes", "roles", "permissions", "acting_as", "on_behalf_of"}
)


def dispatch_tool_call(
    session: Optional[dict],
    tool_name: str,
    arguments: dict,
    tool_scope_map: dict[str, frozenset[str]],
) -> dict:
    if session is None:
        raise AuthorizationConfabulationError(
            f"no session for tool={tool_name}: refusing anonymous dispatch"
        )
    if not session.get("authenticated") or session.get("principal") is None:
        # Distinguish expired from absent at the middleware layer; here we
        # refuse both, because an unbound principal must never reach a handler.
        raise AuthorizationConfabulationError(
            f"session {session.get('session_id')!r} has no bound principal; "
            f"tool={tool_name} dispatch refused"
        )

    injected = RESERVED_AUTH_FIELDS.intersection(arguments.keys())
    if injected:
        raise AuthorizationConfabulationError(
            f"tool={tool_name} arguments attempt to assert reserved "
            f"authorization fields {sorted(injected)}; these are server-derived"
        )

    principal: Principal = session["principal"]
    required = tool_scope_map.get(tool_name)
    if required is None:
        raise AuthorizationConfabulationError(
            f"tool={tool_name} is not registered with a scope requirement"
        )
    if not required.issubset(principal.scopes):
        raise AuthorizationConfabulationError(
            f"principal {principal.subject!r} lacks scopes "
            f"{sorted(required - principal.scopes)} for tool={tool_name}"
        )

    # Downstream call MUST be constructed with the principal for OBO exchange.
    return {"tool": tool_name, "on_behalf_of": principal.subject, "args": arguments}
