# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-signed-mcp-tool-manifests-from-silently-mutating-between-attestation-and-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-signed-mcp-tool-manifests-from-silently-mutating-between-attestation-and-invocation.warrant.json
# Markdown SHA-256:   7da4d517373c1fe4c18a704cceea4d1411a2c1db02697eddb9f179e18c1693a8
# Code AST SHA-256:   e17b13c93746826af911d203ff3c579c5b43008d99411dd0a3dee525c6ebcd09
# Verified Classes:   ManifestDriftError, TrustStoreMismatchError, AttestedManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestDriftError(RuntimeError):
    """Raised when the live MCP tool surface diverges from the attested manifest."""


class TrustStoreMismatchError(RuntimeError):
    """Raised when the signing key id cannot be resolved in the current trust store."""


@dataclass(frozen=True)
class AttestedManifest:
    key_id: str
    surface_digest: str
    side_effect_classes: dict  # tool_name -> "read" | "write" | "destructive"


def compute_surface_digest(tools: list[dict]) -> str:
    canonical = sorted(
        (
            t["name"],
            t.get("schema_hash", ""),
            t.get("side_effect_class", ""),
            t.get("output_contract", ""),
        )
        for t in tools
    )
    return hashlib.sha256(json.dumps(canonical, sort_keys=True).encode()).hexdigest()


def attest_and_invoke(
    attested: AttestedManifest,
    live_tools: list[dict],
    trust_store: dict,
    planned_tool: str,
    planned_side_effect: str,
    invoke,
):
    # Invariant 1: signing key must resolve in the current trust store; no cache fallback.
    if attested.key_id not in trust_store:
        raise TrustStoreMismatchError(
            f"key_id {attested.key_id!r} not in trust store; refusing cached manifest"
        )

    # Invariant 2: signed surface must equal live surface at call time.
    live_digest = compute_surface_digest(live_tools)
    if live_digest != attested.surface_digest:
        raise ManifestDriftError(
            f"surface drift: attested={attested.surface_digest} live={live_digest}"
        )

    # Invariant 3: planner's assumed side-effect class must equal the signed class.
    signed_class = attested.side_effect_classes.get(planned_tool)
    if signed_class is None:
        raise ManifestDriftError(f"tool {planned_tool!r} absent from signed manifest")
    if signed_class != planned_side_effect:
        raise ManifestDriftError(
            f"side-effect mismatch for {planned_tool!r}: "
            f"planned={planned_side_effect} signed={signed_class}"
        )

    return invoke(planned_tool)
