# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-tool-manifest-it-just-negotiated-skill-injection-via-post-handshake-manifest-mutation-in-mcp-capability-exchange.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-tool-manifest-it-just-negotiated-skill-injection-via-post-handshake-manifest-mutation-in-mcp-capability-exchange.warrant.json
# Markdown SHA-256:   90418c99a1e95c0d0c6f83daad6bc18b113af2f775f39a49b0d1fa6bc6fc68a4
# Code AST SHA-256:   bb400f0713a70b9618aa57c242c558513aaa11f22de1883bbbd23624575fd163
# Verified Classes:   ManifestDivergenceError, PinnedManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ManifestDivergenceError(RuntimeError):
    """Raised when a tool call cannot be proven to match the live manifest."""
    pass


@dataclass(frozen=True)
class PinnedManifest:
    tool_name: str
    schema: dict          # must set additionalProperties: False
    version_hash: str


def pin_manifest(tool_name: str, schema: dict) -> PinnedManifest:
    if schema.get("additionalProperties") is not False:
        raise ManifestDivergenceError(
            f"schema for {tool_name!r} is permissive; divergence window is open"
        )
    h = hashlib.sha256(repr(sorted(schema.items())).encode()).hexdigest()
    return PinnedManifest(tool_name, schema, h)


def validate_call(pinned: PinnedManifest, args: dict, live_hash: str) -> None:
    if live_hash != pinned.version_hash:
        # Server manifest mutated since handshake (e.g. list_changed was dropped).
        raise ManifestDivergenceError(
            f"manifest hash mismatch for {pinned.tool_name!r}: "
            f"pinned={pinned.version_hash[:8]} live={live_hash[:8]}; "
            f"re-negotiate before proceeding"
        )
    allowed = set(pinned.schema.get("properties", {}).keys())
    injected = set(args) - allowed
    if injected:
        # Unknown key = planner hallucination or skill-injection field.
        raise ManifestDivergenceError(
            f"call to {pinned.tool_name!r} carries fields absent from pinned "
            f"schema: {sorted(injected)}; refusing to emit"
        )


def guarded_invoke(pinned, args, live_hash, server_exec):
    validate_call(pinned, args, live_hash)
    return server_exec(args)
