# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-that-mutates-between-discovery-and-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-that-mutates-between-discovery-and-invocation.warrant.json
# Markdown SHA-256:   1cabae6af7d31be93a0aca6d1adf5eb937092816b784aaa4ca14b8d0797e022a
# Code AST SHA-256:   3c852d21a91ac04b56717dbc1fe9e9408dcf1a810ce79ce2c90f8ab4d7727492
# Verified Classes:   ManifestMutationError, PlanScopeViolation, ManifestPin
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ManifestMutationError(RuntimeError):
    """Raised when a tool's manifest changes between discovery and invocation
    while the tool is referenced by the active plan."""
    pass


class PlanScopeViolation(RuntimeError):
    """Raised when a tool is invoked that the active plan never referenced."""
    pass


def _canonical_hash(tool: dict) -> str:
    payload = {
        "name": tool.get("name"),
        "description": tool.get("description", ""),
        "inputSchema": tool.get("inputSchema", {}),
    }
    blob = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


@dataclass
class ManifestPin:
    """Pins tool hashes at discovery time, scoped to a plan."""
    plan_id: str
    pinned: dict[str, str] = field(default_factory=dict)

    def record(self, tools: list[dict]) -> None:
        for t in tools:
            self.pinned[t["name"]] = _canonical_hash(t)

    def verify(self, tool_name: str, current_tools: list[dict]) -> None:
        if tool_name not in self.pinned:
            raise PlanScopeViolation(
                f"tool {tool_name!r} not referenced by plan {self.plan_id!r}"
            )
        current = next((t for t in current_tools if t["name"] == tool_name), None)
        if current is None:
            raise ManifestMutationError(
                f"tool {tool_name!r} disappeared from registry mid-plan "
                f"(plan={self.plan_id!r})"
            )
        current_hash = _canonical_hash(current)
        if current_hash != self.pinned[tool_name]:
            raise ManifestMutationError(
                f"manifest mutated for tool {tool_name!r}: "
                f"pinned={self.pinned[tool_name][:12]} "
                f"current={current_hash[:12]} (plan={self.plan_id!r})"
            )


def invoke_tool(pin: ManifestPin, tool_name: str, args: dict,
                fetch_manifest) -> dict:
    """Client-side gate. The model never calls the server directly; it calls this,
    which re-fetches, verifies the pin, and only then dispatches."""
    current_tools = fetch_manifest()
    pin.verify(tool_name, current_tools)  # raises ManifestMutationError on swap
    return _dispatch(tool_name, args)


def _dispatch(tool_name: str, args: dict) -> dict:
    # Real transport call to the MCP server.
    raise NotImplementedError
