# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-mcp-tool-registry-attestation-when-the-signing-key-rotates-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-mcp-tool-registry-attestation-when-the-signing-key-rotates-mid-session.warrant.json
# Markdown SHA-256:   404c7091a85432e801f1f4e98b2685fb97a7a4d4a635319cbfd2e850261dba2e
# Code AST SHA-256:   dbb8a5cc08da257d0b97df847048ead1b18e4bb0f18cfc31a7286bb44c27d8af
# Verified Classes:   StaleAttestationError, RevokedKeyError, ToolHandle, KeyStateSnapshot
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class StaleAttestationError(RuntimeError):
    """Raised when a cached MCP tool handle's attestation epoch cannot be
    confirmed against the agent's current registry key-state snapshot."""
    pass


class RevokedKeyError(RuntimeError):
    """Raised when a handle's signing key is revoked at the confirmed epoch."""
    pass


@dataclass
class ToolHandle:
    server_id: str
    tool_name: str
    schema_hash: str
    key_id: str
    attestation_epoch: int          # registry key-set version at resolution
    signature: bytes
    pinned_pubkey: bytes            # historical authenticity only, NOT trust


@dataclass
class KeyStateSnapshot:
    registry_epoch: int
    revoked_key_ids: set = field(default_factory=set)
    trusted_key_ids: set = field(default_factory=set)


def verify_signature(handle: ToolHandle) -> bool:
    # Historical authenticity check. True does NOT imply present trust.
    expected = hashlib.sha256(
        f"{handle.server_id}|{handle.tool_name}|{handle.schema_hash}|{handle.key_id}".encode()
    ).digest()
    return handle.signature == expected  # stand-in for real asymmetric verify


def authorize_invocation(handle: ToolHandle, snapshot: Optional[KeyStateSnapshot]) -> None:
    if snapshot is None:
        raise StaleAttestationError(
            f"no key-state snapshot available; cannot confirm epoch for "
            f"{handle.server_id}/{handle.tool_name} (attested at epoch {handle.attestation_epoch})"
        )

    # Epoch monotonicity: our view must be at least as new as the handle.
    if snapshot.registry_epoch < handle.attestation_epoch:
        raise StaleAttestationError(
            f"key-state snapshot epoch {snapshot.registry_epoch} is older than "
            f"handle attestation epoch {handle.attestation_epoch} for "
            f"{handle.server_id}/{handle.tool_name}"
        )

    if handle.key_id in snapshot.revoked_key_ids:
        raise RevokedKeyError(
            f"signing key {handle.key_id} is revoked at registry epoch "
            f"{snapshot.registry_epoch}; handle for {handle.tool_name} is stale"
        )

    if handle.key_id not in snapshot.trusted_key_ids:
        raise StaleAttestationError(
            f"signing key {handle.key_id} not present in trusted set at epoch "
            f"{snapshot.registry_epoch}"
        )

    # Signature check is necessary but subordinate to the trust check above.
    if not verify_signature(handle):
        raise StaleAttestationError(
            f"signature verification failed for {handle.server_id}/{handle.tool_name}"
        )


def dispatch_tool(handle: ToolHandle, snapshot: Optional[KeyStateSnapshot]) -> str:
    authorize_invocation(handle, snapshot)
    return f"dispatched {handle.tool_name} on {handle.server_id}"
