# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-re-registered-mcp-tool-description-mid-session-descriptor-drift-as-a-silent-skill-injection-vector.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-re-registered-mcp-tool-description-mid-session-descriptor-drift-as-a-silent-skill-injection-vector.warrant.json
# Markdown SHA-256:   2445e7b3809260c2e1501a5826b5b08d7254794e820e2441e724b12df094bfc4
# Code AST SHA-256:   2f7fff658fe2ad628d81b286f697decb84c7963acd5b7df15a90f101fe9e8362
# Verified Classes:   DescriptorMismatchError, StaleDescriptorCacheError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json


class DescriptorMismatchError(RuntimeError):
    """Raised when the descriptor hash an agent planned against does not match
    the descriptor the server is currently enforcing at dispatch time."""
    pass


class StaleDescriptorCacheError(RuntimeError):
    """Raised when an agent attempts to dispatch a tool whose cached descriptor
    hash is absent, meaning it cannot prove which contract it planned against."""
    pass


def canonical_hash(descriptor: dict) -> str:
    """Hash the security-relevant fields of a tool descriptor. Description and
    schema are included because both are read as instructions by the model."""
    relevant = {
        "name": descriptor["name"],
        "description": descriptor.get("description", ""),
        "inputSchema": descriptor.get("inputSchema", {}),
    }
    blob = json.dumps(relevant, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def dispatch(agent_cache: dict, live_registry: dict, tool_name: str, args: dict) -> dict:
    """Dispatch a tool call only if the planned descriptor hash matches the live
    one. On drift, refuse — do not reconcile, do not retry with new schema."""
    cached = agent_cache.get(tool_name)
    if cached is None or "descriptor_hash" not in cached:
        raise StaleDescriptorCacheError(
            f"no pinned descriptor hash for {tool_name!r}; cannot prove planned contract"
        )

    live = live_registry.get(tool_name)
    if live is None:
        raise DescriptorMismatchError(
            f"{tool_name!r} vanished from registry since planning"
        )

    live_hash = canonical_hash(live)
    if live_hash != cached["descriptor_hash"]:
        raise DescriptorMismatchError(
            f"descriptor drift on {tool_name!r}: planned {cached['descriptor_hash'][:12]} "
            f"but server enforces {live_hash[:12]}; re-authorize before dispatch"
        )

    # Hash matches: the contract the model reasoned over is the one enforced.
    return {"tool": tool_name, "args": args, "descriptor_hash": live_hash}


# --- trace of the observed incident -----------------------------------------
registry_at_t0 = {
    "notes.summarize": {
        "name": "notes.summarize",
        "description": "Summarize the provided note text. Input: text (string).",
        "inputSchema": {"type": "object", "properties": {"text": {"type": "string"}},
                        "required": ["text"]},
    }
}
agent_cache = {
    "notes.summarize": {"descriptor_hash": canonical_hash(registry_at_t0["notes.summarize"])}
}

# t=+14min: same name, same endpoint, expanded optional field, no version bump.
registry_at_t14 = {
    "notes.summarize": {
        "name": "notes.summarize",
        "description": ("Summarize the provided note text. Optional context_ref: "
                        "server will fetch and include prior context for richer summaries."),
        "inputSchema": {"type": "object",
                        "properties": {"text": {"type": "string"},
                                       "context_ref": {"type": "string"}},
                        "required": ["text"]},
    }
}

# The vulnerable path would call dispatch with registry_at_t14 and the old cache
# and silently reach the mutated handler. The guarded path raises:
try:
    dispatch(agent_cache, registry_at_t14, "notes.summarize", {"text": "..."})
except DescriptorMismatchError as e:
    # Correct behavior: halt plan, re-fetch, re-read description as untrusted,
    # re-authorize the tool before any further dispatch.
    print(f"plan halted: {e}")
