# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-per-call-mcp-consent-grant-as-non-transferable-across-tool-call-retries-and-how-does-the-audit-trail-at.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-per-call-mcp-consent-grant-as-non-transferable-across-tool-call-retries-and-how-does-the-audit-trail-at.warrant.json
# Markdown SHA-256:   225a9b5b881c31c2e0240997aafaeba68c455a614f482c96a98f6a7c8d466423
# Code AST SHA-256:   aa34509b88683032f9cc15ae9786c0da588d1f2cdaed8c2ec2a6e8821c25326e
# Verified Classes:   ConsentBindingMismatch, ConsentExpired, ConsentGrant, ToolCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class ConsentBindingMismatch(RuntimeError):
    """Raised when a dispatched MCP tool call does not match the consent grant it claims."""


class ConsentExpired(ConsentBindingMismatch):
    """Raised when a consent nonce is past its expiry at dispatch time."""


def canonicalize(tool: str, args: dict[str, Any]) -> str:
    # Deterministic: sorted keys, no whitespace, UTF-8, no trailing normalization.
    # MUST be the identical function used on the consent path.
    payload = json.dumps(
        {"tool": tool, "args": args},
        sort_keys=True,
        separators=(",", ":"),
        ensure_ascii=False,
    )
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


@dataclass(frozen=True)
class ConsentGrant:
    nonce: str
    principal: str
    bound_hash: str      # hash of (tool, canonical_args) at consent time
    expires_at: float    # epoch seconds


@dataclass(frozen=True)
class ToolCall:
    call_id: str         # logical step id; NOT a consent key
    tool: str
    args: dict[str, Any]


def dispatch_with_consent(
    call: ToolCall,
    grant: ConsentGrant | None,
    now: float,
) -> str:
    """Dispatch an MCP tool call only if a grant is bound to its exact canonical args."""
    if grant is None:
        raise ConsentBindingMismatch(
            f"no consent grant for tool={call.tool!r} call_id={call.call_id!r}"
        )
    if now >= grant.expires_at:
        raise ConsentExpired(
            f"consent nonce={grant.nonce!r} expired at {grant.expires_at}; "
            f"call_id={call.call_id!r} requires re-consent"
        )

    executed_hash = canonicalize(call.tool, call.args)
    if executed_hash != grant.bound_hash:
        # This is the boundary. A retry, re-plan, path-resolution, or content
        # middleware changed the call identity. The cached grant does NOT cover it.
        raise ConsentBindingMismatch(
            f"consent nonce={grant.nonce!r} bound to {grant.bound_hash[:12]}… "
            f"but executed call hashes to {executed_hash[:12]}…; "
            f"call_id={call.call_id!r} tool={call.tool!r} must re-consent"
        )

    # Attestation and dispatch share this code path so the log cannot drift.
    attestation = {
        "call_id": call.call_id,
        "tool": call.tool,
        "executed_hash": executed_hash,
        "consent_nonce": grant.nonce,
        "principal": grant.principal,
        "verdict": "authorized",
    }
    _emit_audit(attestation)
    return _execute(call)


def _emit_audit(record: dict[str, Any]) -> None:
    # Real implementation writes to an append-only, hash-chained sink.
    ...


def _execute(call: ToolCall) -> str:
    ...
    return "ok"
