# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-tool-schema-drift-that-weaponizes-mcp-manifest-rewrites-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-tool-schema-drift-that-weaponizes-mcp-manifest-rewrites-mid-session.warrant.json
# Markdown SHA-256:   b334d9e601193189054d7e57a940cd33edca9fcadc335fbd75e39c16bcb43ad4
# Code AST SHA-256:   ed8f243ccfecbd7ca14e6f3e10d2e5c6f896b60aac0d75830990657a94458025
# Verified Classes:   ManifestDriftError, NegotiatedTool
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class ManifestDriftError(RuntimeError):
    """Raised when a tool manifest mutates between negotiation and invocation."""
    pass


@dataclass
class NegotiatedTool:
    name: str
    manifest_hash: str
    required_fields: frozenset
    description: str
    schema_props: frozenset = field(default_factory=frozenset)


def _hash_manifest(tool: dict[str, Any]) -> str:
    canonical = json.dumps(tool, sort_keys=True, separators=(",", ":"))
    return "sha256:" + hashlib.sha256(canonical.encode()).hexdigest()


def negotiate(tool: dict[str, Any]) -> NegotiatedTool:
    schema = tool.get("inputSchema", {})
    return NegotiatedTool(
        name=tool["name"],
        manifest_hash=_hash_manifest(tool),
        required_fields=frozenset(schema.get("required", [])),
        description=tool.get("description", ""),
        schema_props=frozenset(schema.get("properties", {}).keys()),
    )


def verify_before_call(
    pinned: NegotiatedTool,
    live_tool: dict[str, Any],
    diff_surfaced: bool,
) -> NegotiatedTool:
    live_hash = _hash_manifest(live_tool)
    if live_hash == pinned.manifest_hash:
        return pinned

    # Hash drift detected. Only an explicitly surfaced diff permits continuation.
    if not diff_surfaced:
        raise ManifestDriftError(
            f"tool {pinned.name!r} manifest changed "
            f"({pinned.manifest_hash} -> {live_hash}) with no diff surfaced to the model; "
            "refusing to reason over rewritten description"
        )

    live_schema = live_tool.get("inputSchema", {})
    new_required = frozenset(live_schema.get("required", [])) - pinned.required_fields
    if new_required:
        # A new required field is a new instruction channel — treat as escalation.
        raise ManifestDriftError(
            f"tool {pinned.name!r} added required fields {sorted(new_required)} "
            "after negotiation; capability escalation requires re-consent"
        )

    # Additive optional fields are permitted but pinned to the original contract.
    return pinned


def invoke_tool(pinned: NegotiatedTool, live_tool: dict[str, Any], args: dict[str, Any]) -> dict[str, Any]:
    verified = verify_before_call(pinned, live_tool, diff_surfaced=False)
    undeclared = set(args.keys()) - verified.schema_props
    if undeclared:
        raise ManifestDriftError(
            f"tool {pinned.name!r} invoked with undeclared args {sorted(undeclared)} "
            "sourced from drifted description text"
        )
    # ... dispatch to transport with verified.required_fields enforcement ...
    return {"status": "ok", "tool": verified.name}
