# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-tool-descriptor-rug-pull-poisoning-from-surviving-a-registry-re-attestation-cycle.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-tool-descriptor-rug-pull-poisoning-from-surviving-a-registry-re-attestation-cycle.warrant.json
# Markdown SHA-256:   484d292070b80aad1d79a83ec6360270e802cbf46421c141e9bbec9bab43c6d9
# Code AST SHA-256:   29f2e59a96615b197f5d755611f7701b2fa7cbcec05ab055a9e8b9cdfdb2d71d
# Verified Classes:   DescriptorDigestMismatch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json


class DescriptorDigestMismatch(RuntimeError):
    """Raised when the live MCP tool descriptor no longer matches the approved warrant."""


def canonical_descriptor_bytes(descriptor: dict) -> bytes:
    # Description and annotations are model-facing input; they are NOT stripped.
    return json.dumps(descriptor, sort_keys=True, separators=(",", ":")).encode("utf-8")


def descriptor_digest(descriptor: dict) -> str:
    return hashlib.sha256(canonical_descriptor_bytes(descriptor)).hexdigest()


def dispatch_tool_call(warrant: dict, live_descriptor: dict, arguments: dict) -> dict:
    """
    warrant: {"server", "name", "digest", "approved_at", "approver"}
    live_descriptor: the descriptor bytes served immediately before dispatch.
    """
    live_digest = descriptor_digest(live_descriptor)

    if (live_descriptor.get("server"), live_descriptor.get("name")) != (
        warrant["server"],
        warrant["name"],
    ):
        raise DescriptorDigestMismatch(
            f"identity drift: warrant={warrant['server']}/{warrant['name']} "
            f"live={live_descriptor.get('server')}/{live_descriptor.get('name')}"
        )

    if live_digest != warrant["digest"]:
        # Do not fall back to cached descriptor. Do not silently re-approve.
        raise DescriptorDigestMismatch(
            f"descriptor mutated under stable identity {warrant['server']}/{warrant['name']}: "
            f"approved={warrant['digest']} live={live_digest}; quarantine and re-attest"
        )

    # Policy predicates re-evaluated on live bytes, not cached projection.
    if live_descriptor.get("annotations", {}).get("readOnlyHint") is False and arguments.get(
        "_policy_requires_readonly"
    ):
        raise DescriptorDigestMismatch(
            "policy violation: call requires read-only tool but live descriptor is destructive"
        )

    return {"server": warrant["server"], "name": warrant["name"], "arguments": arguments}
