# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-mcp-tool-call-despite-a-valid-capability-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-mcp-tool-call-despite-a-valid-capability-attestation.warrant.json
# Markdown SHA-256:   6f16a9dc801ef636b8059d2d500799313167309f986b50776c0989c2c161f45a
# Code AST SHA-256:   aa03e21472632c83479bfe14a390e622798ba922f37fb0f2629f6d16d9873b58
# Verified Classes:   UnattestedInvocationError, Attestation, RuntimeProbe
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class UnattestedInvocationError(RuntimeError):
    """Raised when a tool call would reach a runtime that does not match its attestation."""
    pass


@dataclass(frozen=True)
class Attestation:
    provider_id: str
    tool_name: str
    schema_hash: str
    declared_scopes: frozenset
    build_digest: str
    version: int
    not_after: float


@dataclass(frozen=True)
class RuntimeProbe:
    build_digest: str
    served_schema_hash: str
    effective_scopes: frozenset


def authorize_invocation(
    attestation: Attestation,
    probe: RuntimeProbe | None,
    current_version: int,
    now: float,
) -> None:
    if now >= attestation.not_after:
        raise UnattestedInvocationError(
            f"attestation for {attestation.provider_id}/{attestation.tool_name} expired"
        )
    if attestation.version != current_version:
        raise UnattestedInvocationError(
            f"stale attestation v{attestation.version} != current v{current_version}; refresh required"
        )
    if probe is None:
        raise UnattestedInvocationError(
            "no runtime challenge response; absence of proof is not proof"
        )
    if probe.build_digest != attestation.build_digest:
        raise UnattestedInvocationError(
            f"endpoint substitution: live build {probe.build_digest} != attested {attestation.build_digest}"
        )
    if probe.served_schema_hash != attestation.schema_hash:
        raise UnattestedInvocationError(
            "schema drift: served schema does not match attested schema_hash"
        )
    if not probe.effective_scopes.issubset(attestation.declared_scopes):
        over = probe.effective_scopes - attestation.declared_scopes
        raise UnattestedInvocationError(
            f"runtime scope over-grant beyond attestation: {sorted(over)}"
        )
    # All four conditions hold: attestation-valid coincides with invocation-safe.
