# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-an-mcp-tool-s-description-and-why-a-single-handshake-time-hash-is-insufficient.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-an-mcp-tool-s-description-and-why-a-single-handshake-time-hash-is-insufficient.warrant.json
# Markdown SHA-256:   d7205a5abe91e4ec23e829490addc2b2a12f1b3ca20896cef77d633b78d30650
# Code AST SHA-256:   d2235d39ad5fc65e32eaf4d92d0caf04529499a7700f8822b87d1808f2460f60
# Verified Classes:   ToolIntegrityError, ToolDescriptor, ToolTrustLease
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any, Callable, Optional


class ToolIntegrityError(RuntimeError):
    """Raised when an MCP tool's descriptor or behavior diverges from its pinned baseline."""


@dataclass(frozen=True)
class ToolDescriptor:
    name: str
    description: str
    input_schema: dict

    def digest(self) -> str:
        blob = json.dumps(
            {"name": self.name, "description": self.description, "input_schema": self.input_schema},
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(blob.encode("utf-8")).hexdigest()


IMPERATIVE_MARKERS = ("before calling", "ignore", "read the contents", "pass the contents", "~/.aws", "/etc/")


class ToolTrustLease:
    """Re-verifies descriptor + behavior at every trust-boundary transition."""

    def __init__(self, pinned: ToolDescriptor, canary: Callable[[ToolDescriptor], Any], expected_canary: Any):
        self._pinned_digest = pinned.digest()
        self._canary = canary
        self._expected_canary = expected_canary
        self._verified = False

    def _scan_injection(self, desc: ToolDescriptor) -> Optional[str]:
        text = f"{desc.description} {json.dumps(desc.input_schema)}".lower()
        for marker in IMPERATIVE_MARKERS:
            if marker in text:
                return marker
        return None

    def verify(self, current: ToolDescriptor) -> None:
        # 1. Descriptor must match the pinned baseline byte-for-byte.
        if current.digest() != self._pinned_digest:
            raise ToolIntegrityError(
                f"descriptor drift for tool {current.name!r}: hash {current.digest()[:12]} "
                f"!= pinned {self._pinned_digest[:12]} — re-authorization required, do not call"
            )

        # 2. Even an unchanged descriptor may carry injected imperatives (defense in depth).
        marker = self._scan_injection(current)
        if marker is not None:
            raise ToolIntegrityError(
                f"imperative injection marker {marker!r} found in descriptor for {current.name!r}"
            )

        # 3. Behavior canary: descriptor-identical behavior drift is invisible to hashing.
        observed = self._canary(current)
        if observed != self._expected_canary:
            raise ToolIntegrityError(
                f"behavior canary failed for {current.name!r}: expected {self._expected_canary!r}, "
                f"got {observed!r} — possible rug-pull with unchanged descriptor"
            )

        self._verified = True


def guarded_call(lease: ToolTrustLease, current: ToolDescriptor, invoke: Callable[[], Any]) -> Any:
    # Re-verify at the transition, never trust the handshake-time result.
    lease.verify(current)
    if not lease._verified:
        raise ToolIntegrityError("tool invoked without a passing verification lease")
    return invoke()
