# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-has-already-executed-on-the-non-idempotence-of-mcp-capability-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-has-already-executed-on-the-non-idempotence-of-mcp-capability-negotiation.warrant.json
# Markdown SHA-256:   2b7899363961f5038770264db6fd7c4036732f669501e6cf055fc1c7c7f3e94f
# Code AST SHA-256:   f7b6cea3d29576d04b93e885c66146477374b4f85a4a30630d3e8f796b28fb0c
# Verified Classes:   SurfaceMutationError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json


class SurfaceMutationError(RuntimeError):
    """Raised when a tool surface changes in a way that expands the action space."""


def _hash_surface(surface: dict) -> str:
    canonical = json.dumps(surface, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def _is_strict_subset(new: dict, old: dict) -> bool:
    """A surface may shrink freely: tools removed, fields narrowed."""
    new_tools = {t["name"]: t for t in new.get("tools", [])}
    old_tools = {t["name"]: t for t in old.get("tools", [])}
    if not set(new_tools).issubset(old_tools):
        return False
    for name, new_tool in new_tools.items():
        old_tool = old_tools[name]
        if new_tool.get("description") != old_tool.get("description"):
            return False
        old_schema = old_tool.get("inputSchema", {})
        new_schema = new_tool.get("inputSchema", {})
        if new_schema.get("additionalProperties") is True and \
           old_schema.get("additionalProperties") is not True:
            return False
        if not set(new_schema.get("properties", {})).issubset(
                old_schema.get("properties", {})):
            return False
    return True


def verify_surface(pinned_surface: dict, pinned_hash: str, observed: dict) -> None:
    """
    Fail closed on any surface growth. Shrinking is permitted; growing or
    incomparable mutation requires a full re-validation gate upstream and
    raises here so the caller cannot silently merge.
    """
    if _hash_surface(observed) == pinned_hash:
        return

    if _is_strict_subset(observed, pinned_surface):
        return  # safe: action space only shrank

    # Superset, incomparable, or description-only mutation: the injection vector.
    raise SurfaceMutationError(
        "tool surface mutated under stable server identity: "
        f"pinned={pinned_hash[:12]} observed={_hash_surface(observed)[:12]}; "
        "refusing to merge, re-validation required"
    )


def call_tool(server, pinned_surface: dict, pinned_hash: str,
              tool_name: str, arguments: dict) -> dict:
    observed = server.list_tools()  # re-negotiate, do not trust cache
    verify_surface(pinned_surface, pinned_hash, observed)
    return server.call_tool(tool_name, arguments)
