# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-tool-description-poisoning-from-surviving-a-mid-session-skill-reload.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-tool-description-poisoning-from-surviving-a-mid-session-skill-reload.warrant.json
# Markdown SHA-256:   e8562f78d1918d0a566eab09e52a7f52cedf562702c90ae36a2a0592544ed34f
# Code AST SHA-256:   2a22c3fcd2a179fc4c64958daaba28d20e27167e94609d2269a93d047a03a7ce
# Verified Classes:   StaleManifestCoexistenceError, UndeclaredParameterError, ToolManifest, SkillRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class StaleManifestCoexistenceError(RuntimeError):
    """Raised when a reload would leave two live descriptions for one tool identity."""
    pass


class UndeclaredParameterError(RuntimeError):
    """Raised when a dispatched argument is absent from the authoritative schema."""
    pass


@dataclass
class ToolManifest:
    name: str
    description: str
    schema: dict
    version: str

    def content_hash(self) -> str:
        payload = json.dumps(
            {
                "name": self.name,
                "description": self.description,
                "schema": self.schema,
                "version": self.version,
            },
            sort_keys=True,
        ).encode("utf-8")
        return hashlib.sha256(payload).hexdigest()


@dataclass
class SkillRegistry:
    live: dict = field(default_factory=dict)  # name -> (manifest, hash)

    def reload(self, incoming: ToolManifest) -> str:
        prior = self.live.get(incoming.name)
        new_hash = incoming.content_hash()
        if prior is not None and prior[1] != new_hash:
            # Evict the old description BEFORE inserting the new one.
            del self.live[incoming.name]
        elif prior is not None and prior[1] == new_hash:
            return "noop"
        self.live[incoming.name] = (incoming, new_hash)
        return "evicted-and-replaced"

    def assert_single_liveness(self, name: str) -> None:
        if name not in self.live:
            raise StaleManifestCoexistenceError(f"tool {name!r} has no live description")
        manifest, _ = self.live[name]
        # Invariant: exactly one description, and it must match the live hash.
        if manifest.content_hash() != self.live[name][1]:
            raise StaleManifestCoexistenceError(
                f"tool {name!r} live description diverged from pinned hash"
            )


def dispatch(registry: SkillRegistry, name: str, args: dict) -> dict:
    registry.assert_single_liveness(name)
    manifest, _ = registry.live[name]
    declared = set(manifest.schema.get("properties", {}).keys())
    undeclared = set(args.keys()) - declared
    if undeclared:
        raise UndeclaredParameterError(
            f"tool {name!r} received undeclared parameters {sorted(undeclared)}; "
            f"description prose cannot extend the schema"
        )
    return {"tool": name, "args": args, "version": manifest.version}
