# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-mcp-tool-level-consent-with-oauth-2-1-resource-indicator-scopes-when-a-single-token-spans-multiple-servers.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-mcp-tool-level-consent-with-oauth-2-1-resource-indicator-scopes-when-a-single-token-spans-multiple-servers.warrant.json
# Markdown SHA-256:   b4db52c4d93514db471edf692ffaaa2f338b514ae862df468e867ec8d2817bc9
# Code AST SHA-256:   82e95e6aeeacb4188ba3a05832d2087374ea75f2657d7ba2ba2aa3b93681005a
# Verified Classes:   ConsentResolutionError, RetryPolicy, ToolCapability, TokenGrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ConsentResolutionError(RuntimeError):
    """Raised when a tool call is attempted without resolved consent state."""


class RetryPolicy(Enum):
    NEVER = "never"
    ONCE = "once"
    SURFACE = "surface"


# MCP JSON-RPC error codes relevant to authorization/consent.
ERROR_POLICY = {
    -32001: RetryPolicy.SURFACE,   # consent_required: user must act
    -32002: RetryPolicy.ONCE,      # invalid_token: refresh, retry once
    -32003: RetryPolicy.SURFACE,   # insufficient_scope: re-plan without tool
    -32603: RetryPolicy.SURFACE,   # internal error: do not retry blindly
}


@dataclass(frozen=True)
class ToolCapability:
    resource: str          # canonical MCP server URI (RFC 8707 resource indicator)
    tool: str
    required_scopes: frozenset[str]
    consent_required: bool


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


def resolve_capability_set(
    token: TokenGrant,
    tools: list[ToolCapability],
    consented: set[tuple[str, str]],  # (resource, tool) pairs with recorded consent
) -> list[ToolCapability]:
    """Return the subset of tools the client may actually call.

    A tool is callable iff:
      - its resource matches the token's resource indicator exactly, AND
      - its required_scopes are a subset of the token's granted scopes, AND
      - if consent_required, consent is recorded for (resource, tool).
    """
    callable_tools: list[ToolCapability] = []
    for t in tools:
        if t.resource != token.resource:
            # Cross-resource token reuse: never silently proceed.
            continue
        if not t.required_scopes.issubset(token.scopes):
            continue
        if t.consent_required and (t.resource, t.tool) not in consented:
            # Scope-valid but consent-missing: NOT callable, must be surfaced.
            continue
        callable_tools.append(t)
    return callable_tools


def plan_and_call(
    token: TokenGrant,
    tools: list[ToolCapability],
    consented: set[tuple[str, str]],
    requested_tool: str,
    is_mutating_task: bool,
) -> None:
    """Attempt a tool call, enforcing the consent-before-plan invariant."""
    callable_set = resolve_capability_set(token, tools, consented)
    callable_names = {t.tool for t in callable_set}

    if requested_tool not in callable_names:
        match = next((t for t in tools if t.tool == requested_tool), None)
        if match is None:
            raise ConsentResolutionError(
                f"tool {requested_tool!r} not advertised by resource {token.resource!r}"
            )
        if match.resource != token.resource:
            raise ConsentResolutionError(
                f"tool {requested_tool!r} belongs to {match.resource!r}, "
                f"token bound to {token.resource!r} — resource indicator mismatch"
            )
        if not match.required_scopes.issubset(token.scopes):
            raise ConsentResolutionError(
                f"tool {requested_tool!r} requires {sorted(match.required_scopes)}, "
                f"token grants {sorted(token.scopes)}"
            )
        if match.consent_required and (match.resource, match.tool) not in consented:
            # This is the boundary case: scope-valid, consent-missing.
            # If the task is mutating, we must NOT fall back to a degraded plan.
            if is_mutating_task:
                raise ConsentResolutionError(
                    f"tool {requested_tool!r} requires interactive consent; "
                    f"mutating task cannot proceed on degraded plan"
                )
            raise ConsentResolutionError(
                f"tool {requested_tool!r} requires interactive consent"
            )

    # Proceed with the call (transport layer omitted).
    return None


def classify_error(code: int) -> RetryPolicy:
    return ERROR_POLICY.get(code, RetryPolicy.SURFACE)
