# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-post-handshake-manifest-mutation-in-an-mcp-tool-registry-before-executing-a-poisoned-skill.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-post-handshake-manifest-mutation-in-an-mcp-tool-registry-before-executing-a-poisoned-skill.warrant.json
# Markdown SHA-256:   4416d8b139a20043bc0d8a00b7798d210cb7d23303ea9f4fa0ac9ae4e9a22f16
# Code AST SHA-256:   4c680ddfd98ba0f03f5a383d3b4b9af87263a240f0172bff9e88a30e39dd7cae
# Verified Classes:   ManifestMutationError, ApprovedTool, CapabilityCache
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ManifestMutationError(RuntimeError):
    """Raised when a tool's served digest diverges from its approved digest."""
    pass


@dataclass
class ApprovedTool:
    name: str
    description: str
    input_schema: str
    digest: str = field(init=False)

    def __post_init__(self):
        self.digest = self._compute()

    def _compute(self) -> str:
        payload = f"{self.name}\x00{self.description}\x00{self.input_schema}"
        return hashlib.sha256(payload.encode("utf-8")).hexdigest()


class CapabilityCache:
    """Durable per-tool digest store; survives context-window eviction."""

    def __init__(self):
        self._approved: dict[str, ApprovedTool] = {}

    def approve(self, tool: ApprovedTool) -> None:
        self._approved[tool.name] = tool

    def verify_at_call(self, served: ApprovedTool) -> ApprovedTool:
        approved = self._approved.get(served.name)
        if approved is None:
            raise ManifestMutationError(
                f"tool {served.name!r} invoked without prior approval"
            )
        if approved.digest != served.digest:
            raise ManifestMutationError(
                f"post-handshake mutation on {served.name!r}: "
                f"approved={approved.digest[:12]} served={served.digest[:12]}; "
                f"delta={_diff(approved, served)}"
            )
        return approved


def _diff(a: ApprovedTool, b: ApprovedTool) -> str:
    parts = []
    if a.description != b.description:
        parts.append("description")
    if a.input_schema != b.input_schema:
        parts.append("input_schema")
    return ",".join(parts) or "none"


def execute_tool_call(cache: CapabilityCache, served: ApprovedTool, args: dict):
    # Freeze the model against the APPROVED text, never the served text.
    trusted = cache.verify_at_call(served)
    return {"tool": trusted.name, "description_used": trusted.description, "args": args}
