# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-capability-attestation-from-silently-diverging-from-runtime-tool-behavior.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-capability-attestation-from-silently-diverging-from-runtime-tool-behavior.warrant.json
# Markdown SHA-256:   b2efdda4f25d9262cbffc600164845c20f50c1876fa1dd9ff153e7783ed1bee4
# Code AST SHA-256:   13e5d28edec823fbc47e8a7cfc0f1774e9f5e9b375bb30b64de304c1dc705cf5
# Verified Classes:   AttestationDriftError, OutputContractViolation, CapabilityRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import hmac
from dataclasses import dataclass, field
from typing import Any


class AttestationDriftError(RuntimeError):
    """Raised when a tool response is bound to an implementation digest
    that differs from the attested capability record."""
    pass


class OutputContractViolation(RuntimeError):
    """Raised when a response violates the attested output schema."""
    pass


@dataclass(frozen=True)
class CapabilityRecord:
    tool_name: str
    input_schema: dict[str, Any]
    output_schema: dict[str, Any]
    implementation_digest: str  # H(implementation) at attestation time
    signing_key: bytes = field(repr=False)


def _digest(payload: bytes) -> str:
    return hashlib.sha256(payload).hexdigest()


def verify_call_response(
    record: CapabilityRecord,
    response: dict[str, Any],
    request_nonce: str,
) -> dict[str, Any]:
    """Validate a tools/call response against the attested capability record.

    Enforces, in order:
      1. attestation_ref present and signed over (tool, digest, nonce)
      2. implementation_digest matches the attested record
      3. payload conforms to the attested output schema

    Returns the payload only if all three hold. Fails closed otherwise.
    """
    ref = response.get("attestation_ref")
    if ref is None:
        # Provider does not support binding: fail open but downgrade trust.
        return {"payload": response.get("result"), "trust": "unverified"}

    signed = f"{record.tool_name}:{ref['implementation_digest']}:{request_nonce}".encode()
    expected_mac = hmac.new(record.signing_key, signed, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected_mac, ref.get("mac", "")):
        raise AttestationDriftError(
            f"attestation MAC invalid for tool {record.tool_name!r}; "
            f"possible key substitution or replay"
        )

    if ref["implementation_digest"] != record.implementation_digest:
        raise AttestationDriftError(
            f"tool {record.tool_name!r} answered with implementation "
            f"{ref['implementation_digest'][:12]} but was attested at "
            f"{record.implementation_digest[:12]}; refusing to surface result"
        )

    payload = response.get("result", {})
    _validate_output(record.output_schema, payload)
    return {"payload": payload, "trust": "verified"}


def _validate_output(schema: dict[str, Any], payload: dict[str, Any]) -> None:
    """Minimal output-contract check: reject unknown fields and bad cardinality."""
    allowed = set(schema.get("properties", {}))
    unknown = set(payload) - allowed
    if unknown:
        raise OutputContractViolation(
            f"response contains fields absent from attested output schema: {sorted(unknown)}"
        )
    limit = schema.get("properties", {}).get("limit", {}).get("maximum")
    results = payload.get("results")
    if limit is not None and isinstance(results, list) and len(results) > limit:
        raise OutputContractViolation(
            f"cardinality {len(results)} exceeds attested maximum {limit}"
        )
