# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-bind-an-mcp-oauth-access-token-s-resource-indicator-before-every-tool-call-and-what-breaks-when-it-doesn-t.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-bind-an-mcp-oauth-access-token-s-resource-indicator-before-every-tool-call-and-what-breaks-when-it-doesn-t.warrant.json
# Markdown SHA-256:   69ba5de198387ec48da5897341b554b4e59ca8ea9fdd25b2eeeffeb09ba38ea5
# Code AST SHA-256:   effc5c3aa209aa1a8487ea18f07a0611cf782ac51296cf36d608f382f4cffcb1
# Verified Classes:   ResourceIndicatorMismatch, ScopeInsufficient, Token, ToolSpec
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class ResourceIndicatorMismatch(RuntimeError):
    """Raised when a token's resource indicator does not cover the tool's resource."""


class ScopeInsufficient(RuntimeError):
    """Raised when the token lacks a scope required by the target tool."""


@dataclass(frozen=True)
class Token:
    resource: frozenset[str]
    scopes: frozenset[str]


@dataclass(frozen=True)
class ToolSpec:
    name: str
    resource: str
    required_scope: str
    external_side_effect: bool


def authorize_tool_call(token: Token, tool: ToolSpec, untrusted_content_seen: bool) -> None:
    # Audience check first: scope match alone is NOT authorization.
    if tool.resource not in token.resource:
        raise ResourceIndicatorMismatch(
            f"tool {tool.name!r} targets resource {tool.resource!r} "
            f"but token audience is {sorted(token.resource)!r}; "
            f"refusing to fall back to a broader token"
        )

    if tool.required_scope not in token.scopes:
        raise ScopeInsufficient(
            f"tool {tool.name!r} requires scope {tool.required_scope!r}; "
            f"token holds {sorted(token.scopes)!r}"
        )

    # Confused-deputy guard: a token that can act on untrusted content and
    # also perform an external side effect must be split across resources.
    if untrusted_content_seen and tool.external_side_effect:
        raise ResourceIndicatorMismatch(
            f"tool {tool.name!r} performs an external side effect after untrusted "
            f"content was read under the same token; re-bind a resource-scoped "
            f"token for {tool.resource!r} before proceeding"
        )


def run_plan(token: Token, tools: Iterable[ToolSpec], untrusted_content_seen: bool) -> None:
    for tool in tools:
        authorize_tool_call(token, tool, untrusted_content_seen)


if __name__ == "__main__":
    broad = Token(
        resource=frozenset({"https://mcp.example.com"}),
        scopes=frozenset({"calendar.read", "mail.send", "files.write"}),
    )
    calendar = ToolSpec("calendar.read", "https://mcp.example.com/calendar", "calendar.read", False)
    mail = ToolSpec("mail.send", "https://mcp.example.com/mail", "mail.send", True)

    # Read step passes; the side-effecting step is blocked because the token's
    # audience is the origin, not the mail resource.
    run_plan(broad, [calendar], untrusted_content_seen=False)
    run_plan(broad, [mail], untrusted_content_seen=True)  # raises ResourceIndicatorMismatch
