# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-descriptor-level-tool-poisoning-in-an-mcp-server-whose-tool-schemas-mutate-between-capability-negotiation-and-first-invo.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-descriptor-level-tool-poisoning-in-an-mcp-server-whose-tool-schemas-mutate-between-capability-negotiation-and-first-invo.warrant.json
# Markdown SHA-256:   f7e4e76fd8b4c42a436261820749d7844f186ac85b0a765d7a1d89155e0a028e
# Code AST SHA-256:   6e0f75fe45daec07a86dc8fe76ba603936a4484248efd53462c16c16ba606371
# Verified Classes:   DescriptorDriftError, ToolDescriptor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class DescriptorDriftError(RuntimeError):
    """Raised when a tool descriptor mutated between negotiation and dispatch."""


@dataclass(frozen=True)
class ToolDescriptor:
    name: str
    description: str
    input_schema: dict

    def digest(self) -> str:
        # Hash the full semantic surface: name, description, and schema.
        # Description-only changes are poisoning vectors and must be caught.
        payload = json.dumps(
            {
                "name": self.name,
                "description": self.description,
                "input_schema": self.input_schema,
            },
            sort_keys=True,
        ).encode("utf-8")
        return hashlib.sha256(payload).hexdigest()


def validate_dispatch_descriptor(
    negotiated: ToolDescriptor,
    live: ToolDescriptor,
    *,
    allow_metadata_only: bool = False,
) -> None:
    """
    Called immediately before tools/call. Compares the descriptor the planner
    reasoned over against the descriptor the server will actually execute.
    """
    if negotiated.digest() == live.digest():
        return

    contract_changed = (
        negotiated.input_schema != live.input_schema
        or negotiated.name != live.name
    )

    if contract_changed:
        raise DescriptorDriftError(
            f"Contract drift on tool {negotiated.name!r}: "
            f"negotiated={negotiated.digest()[:12]} live={live.digest()[:12]}. "
            "Planner justification is void; re-negotiate and re-plan."
        )

    if not allow_metadata_only:
        raise DescriptorDriftError(
            f"Description-only drift on tool {negotiated.name!r}; "
            "description is part of the instruction surface and must not be "
            "trusted silently."
        )
    # metadata-only drift explicitly permitted: log and continue
    return


def dispatch_tool_call(
    negotiated: ToolDescriptor,
    live: ToolDescriptor,
    arguments: dict,
    transport,
) -> dict:
    validate_dispatch_descriptor(negotiated, live)
    response = transport.call(live.name, arguments)
    # Post-call: the response must be attributable to the verified contract.
    if live.digest() != negotiated.digest():
        raise DescriptorDriftError(
            f"Descriptor changed mid-call for {live.name!r}; response is "
            "unattributable to a known contract."
        )
    return response
