# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tool-description-poisoning-from-surviving-a-capability-re-negotiation-after-mcp-server-hot-swap.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tool-description-poisoning-from-surviving-a-capability-re-negotiation-after-mcp-server-hot-swap.warrant.json
# Markdown SHA-256:   16a1a4be11680175d7d4ddc69d3ad736aa5c4ea0d8e665f327ae6af9c0558494
# Code AST SHA-256:   fd8d53d45dbcb16c1a503d693f7da59f6a106768e8ced43a16b91f709c0ee674
# Verified Classes:   TrustRebindingError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
import unicodedata


class TrustRebindingError(RuntimeError):
    """Raised when a re-negotiated tool's content hash is absent from the trust store."""


def canonical_tool(name: str, description: str, input_schema: dict) -> str:
    norm_desc = unicodedata.normalize("NFKC", description).strip()
    payload = {
        "name": name,
        "description": norm_desc,
        "inputSchema": input_schema,
    }
    blob = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(blob.encode("utf-8")).hexdigest()


def register_after_reconnect(tool: dict, trust_store: dict, adjudicate) -> dict:
    """Re-validate a tool observed on a post-reconnect tools/list against the trust store."""
    h = canonical_tool(tool["name"], tool["description"], tool["inputSchema"])
    if h in trust_store and trust_store[h]["verdict"] == "PASS":
        return {"tool": tool, "status": "trusted", "hash": h}

    # Hash miss: content changed or never vetted. Never fall back to a name-keyed verdict.
    verdict = adjudicate(tool)
    if verdict != "PASS":
        raise TrustRebindingError(
            f"tool {tool['name']!r} failed re-adjudication after reconnect "
            f"(hash={h[:12]}, verdict={verdict})"
        )
    trust_store[h] = {"verdict": "PASS", "name": tool["name"]}
    return {"tool": tool, "status": "re-adjudicated", "hash": h}
