# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-it-never-re-verified-manifest-drift-and-capability-spoofing-in-mcp-tool-injection.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-it-never-re-verified-manifest-drift-and-capability-spoofing-in-mcp-tool-injection.warrant.json
# Markdown SHA-256:   a6a84611bd4f01275efd83f2b5e0ba371144b8f83f5e3e32627b8505eeed4526
# Code AST SHA-256:   c76a842c3fe229353f7511548ba6af91ddf7997355235bc615fcbc03763b2e0b
# Verified Classes:   ManifestDriftError, ToolManifest, ToolCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestDriftError(RuntimeError):
    """Raised when a cached tool manifest no longer matches the live one
    at call time, in a way that changes the tool's effective capability."""
    pass


@dataclass(frozen=True)
class ToolManifest:
    name: str
    schema: dict
    server_identity: str

    def fingerprint(self) -> str:
        # Bind name + schema + server identity. Server identity is what
        # defeats the name-collision / impostor-server variant.
        blob = json.dumps(
            {"name": self.name, "schema": self.schema, "srv": self.server_identity},
            sort_keys=True,
        )
        return hashlib.sha256(blob.encode()).hexdigest()


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

    def approve(self, m: ToolManifest) -> None:
        # Approval is keyed on name but stores the full manifest so we can
        # detect drift; a name collision from a different server still
        # collides here and must be caught by the caller.
        existing = self._approved.get(m.name)
        if existing and existing.server_identity != m.server_identity:
            raise ManifestDriftError(
                f"tool '{m.name}' already approved from server "
                f"'{existing.server_identity}', refusing impostor "
                f"'{m.server_identity}'"
            )
        self._approved[m.name] = m

    def verify_before_call(self, live: ToolManifest) -> None:
        cached = self._approved.get(live.name)
        if cached is None:
            raise ManifestDriftError(
                f"tool '{live.name}' was never vetted; refusing unvetted call"
            )
        if cached.fingerprint() != live.fingerprint():
            # Any schema/identity change is a capability change. Widening an
            # input schema (e.g. adding an optional 'url') is an expansion and
            # must force re-vetting, not be treated as backward-compatible.
            raise ManifestDriftError(
                f"manifest drift for '{live.name}': cached "
                f"{cached.fingerprint()[:12]} != live "
                f"{live.fingerprint()[:12]}; re-vet required"
            )


def call_tool(cache: ToolCache, live_manifest: ToolManifest, args: dict) -> dict:
    # The gate: verify the live manifest against the approved one at call time.
    cache.verify_before_call(live_manifest)
    # ... transport dispatch to the MCP server with args ...
    return {"status": "dispatched", "tool": live_manifest.name}
