# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-authorization-mid-session-when-mcp-oauth-2-1-resource-indicators-drift-from-the-token-s-aud-claim.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-authorization-mid-session-when-mcp-oauth-2-1-resource-indicators-drift-from-the-token-s-aud-claim.warrant.json
# Markdown SHA-256:   c3b946ba56187145d99dbb664c3e14980a15e9aef3ee55188ca8d2e0cdbd0fa5
# Code AST SHA-256:   505a26daeca38d40a5b018830b9911f245a2cbcc0dc55b65c543c7d1e61c7a5c
# Verified Classes:   ResourceIndicatorMismatch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ResourceIndicatorMismatch(RuntimeError):
    """Raised when the token's aud claim does not satisfy the MCP server's
    per-request resource check, indicating a canonicalization divergence
    between the authorization server and the MCP server's enforcement path."""


def preflight_capability_probe(
    token_aud: str,
    required_resource: str,
    accepted_forms: tuple[str, ...],
    probe_tool: str = "tools/list",
) -> None:
    """Verify aud binding before the agent's plan mutates state.

    accepted_forms is the server-published allowlist of audience strings;
    it must be taken verbatim from the protected-resource metadata document,
    never constructed client-side.
    """
    if token_aud == required_resource:
        return  # exact match, no divergence

    if token_aud in accepted_forms:
        # server explicitly tolerates this form; proceed but log the divergence
        return

    raise ResourceIndicatorMismatch(
        f"audience binding failed for probe tool {probe_tool!r}: "
        f"token aud={token_aud!r} is not byte-identical to required "
        f"resource={required_resource!r} and is not in the server's "
        f"accepted_forms allowlist {accepted_forms!r}. "
        f"Do NOT re-run the OAuth flow; the authorization server will "
        f"re-issue an identically-mismatched token. Re-derive the "
        f"resource= parameter from the server's protected-resource "
        f"metadata document and request a new token only if the "
        f"metadata itself has changed."
    )


def execute_tool_call(
    token_aud: str,
    required_resource: str,
    accepted_forms: tuple[str, ...],
    tool_name: str,
) -> None:
    try:
        preflight_capability_probe(token_aud, required_resource, accepted_forms)
    except ResourceIndicatorMismatch as exc:
        # surface to the reasoning loop; do not enter retry loop
        raise ResourceIndicatorMismatch(
            f"aborting tool call {tool_name!r} before state mutation: {exc}"
        ) from exc
    # ... proceed with the tool invocation
