# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-reuses-an-mcp-oauth-access-token-across-tool-calls-whose-resource-bound-audience-was-never-re-validated.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-reuses-an-mcp-oauth-access-token-across-tool-calls-whose-resource-bound-audience-was-never-re-validated.warrant.json
# Markdown SHA-256:   bbf2a072883cdc977ed20dbd7ee44bda7dfd24dabd2c8cef70cde67c27653c8f
# Code AST SHA-256:   d0b9b087448621df9f1ffc960caba0beb06fb10e09a34921f0ed4bfa51275aac
# Verified Classes:   ResourceBindingError, ToolSpec, Token
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping


class ResourceBindingError(RuntimeError):
    """Raised when a tool call's token is not bound to the tool's resource."""


@dataclass(frozen=True)
class ToolSpec:
    tool_id: str
    resource: str | None          # R(t): declared resource identifier
    required_scope: frozenset[str]


@dataclass(frozen=True)
class Token:
    aud: frozenset[str]
    scope: frozenset[str]


def dispatch_gate(token: Token, tool: ToolSpec) -> None:
    # Fail closed on undeclared resource: unbound is not unrestricted.
    if tool.resource is None:
        raise ResourceBindingError(
            f"tool {tool.tool_id!r} has no declared resource; cannot verify audience binding"
        )

    # Per-call audience re-validation against the tool's resource, not the session base.
    if tool.resource not in token.aud:
        raise ResourceBindingError(
            f"audience mismatch for tool {tool.tool_id!r}: "
            f"token aud={sorted(token.aud)} does not contain {tool.resource!r}"
        )

    # Per-call scope check, resource-qualified by the audience check above.
    missing = tool.required_scope - token.scope
    if missing:
        raise ResourceBindingError(
            f"insufficient scope for tool {tool.tool_id!r}: missing {sorted(missing)}"
        )


def handle_tools_call(token: Token, tool: ToolSpec, registry: Mapping[str, ToolSpec]) -> str:
    spec = registry.get(tool.tool_id)
    if spec is None:
        raise ResourceBindingError(f"unknown tool {tool.tool_id!r}")
    dispatch_gate(token, spec)
    return f"executed {spec.tool_id} on {spec.resource}"
