# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-skill-injection-attacks-from-surviving-capability-renegotiation-in-mcp-tool-manifests.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-skill-injection-attacks-from-surviving-capability-renegotiation-in-mcp-tool-manifests.warrant.json
# Markdown SHA-256:   7b1309718782b99df55afa43d626cd546e141f4ca835b35fdcd7f5e5c3381c80
# Code AST SHA-256:   28c5ff7dfd36bda288a77022ae5ea19aed0194ae567fdba8a38c65be0e014658
# Verified Classes:   CapabilityRenegotiationError, ManifestCanonicalizationError, Verdict, PolicyCache
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
import unicodedata
from dataclasses import dataclass, field
from typing import Any


class CapabilityRenegotiationError(RuntimeError):
    """Raised when a tool manifest diverges from its approved capability digest
    without a completed policy evaluation in the current trust epoch."""
    pass


class ManifestCanonicalizationError(ValueError):
    """Raised when a manifest cannot be canonicalized (malformed, non-NFC,
    zero-width characters, or unbounded description length)."""
    pass


@dataclass
class Verdict:
    digest: str
    epoch: int
    allowed: bool


@dataclass
class PolicyCache:
    # key: (server_id, digest) -> Verdict
    _store: dict[tuple[str, str], Verdict] = field(default_factory=dict)
    _epoch: dict[str, int] = field(default_factory=dict)

    def epoch_of(self, server_id: str) -> int:
        return self._epoch.get(server_id, 0)

    def bump_epoch(self, server_id: str) -> int:
        self._epoch[server_id] = self.epoch_of(server_id) + 1
        return self._epoch[server_id]

    def get(self, server_id: str, digest: str) -> Verdict | None:
        return self._store.get((server_id, digest))

    def put(self, server_id: str, verdict: Verdict) -> None:
        self._store[(server_id, verdict.digest)] = verdict


def _normalize_text(s: str, max_len: int = 8192) -> str:
    if len(s) > max_len:
        raise ManifestCanonicalizationError(f"description exceeds {max_len} chars")
    n = unicodedata.normalize("NFC", s)
    # Reject zero-width and bidi-control characters outright; they are never
    # semantically meaningful in a tool description and are a known payload channel.
    for ch in n:
        if unicodedata.category(ch) in ("Cf", "Cc") and ch not in ("\n", "\t"):
            raise ManifestCanonicalizationError(f"control char U+{ord(ch):04X} in description")
    return n


def _canonical_manifest(manifest: dict[str, Any]) -> str:
    """Canonicalize EVERY field the model will read. Omitting descriptions is
    the classic bug: it makes description-only injections invisible to the digest."""
    tools = manifest.get("tools", [])
    canon_tools = []
    for t in tools:
        canon_tools.append({
            "name": _normalize_text(t.get("name", "")),
            "description": _normalize_text(t.get("description", "")),
            "inputSchema": t.get("inputSchema", {}),
        })
    canon_tools.sort(key=lambda x: x["name"])
    payload = {
        "tools": canon_tools,
        "instructions": _normalize_text(manifest.get("instructions", "")),
    }
    return json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


def digest_manifest(manifest: dict[str, Any]) -> str:
    return hashlib.sha256(_canonical_manifest(manifest).encode("utf-8")).hexdigest()


def admit_manifest(
    server_id: str,
    manifest: dict[str, Any],
    cache: PolicyCache,
    policy_eval,  # callable(manifest) -> bool
) -> Verdict:
    """Admission gate. Fail-closed on unknown digest; re-evaluate on divergence
    or epoch advance; block on canonicalization failure."""
    try:
        digest = digest_manifest(manifest)
    except ManifestCanonicalizationError as e:
        raise CapabilityRenegotiationError(
            f"manifest for {server_id} failed canonicalization: {e}"
        ) from e

    prior = cache.get(server_id, digest)
    current_epoch = cache.epoch_of(server_id)

    # Cache hit is valid ONLY if the digest matches AND the epoch has not advanced.
    if prior is not None and prior.epoch == current_epoch:
        if not prior.allowed:
            raise CapabilityRenegotiationError(
                f"server {server_id} presents previously-denied digest {digest}"
            )
        return prior

    # Divergent digest, or epoch advance (revert detection). Re-evaluate.
    allowed = False
    try:
        allowed = bool(policy_eval(manifest))
    except Exception as e:
        # Policy engine failure is deny, not allow.
        raise CapabilityRenegotiationError(
            f"policy evaluation failed for {server_id}: {e}"
        ) from e

    verdict = Verdict(digest=digest, epoch=current_epoch, allowed=allowed)
    cache.put(server_id, verdict)

    if not allowed:
        raise CapabilityRenegotiationError(
            f"server {server_id} digest {digest} denied by policy at epoch {current_epoch}"
        )
    return verdict


def on_tools_list_changed(
    server_id: str,
    new_manifest: dict[str, Any],
    cache: PolicyCache,
    policy_eval,
) -> Verdict:
    """Renegotiation entry point. Bumps the epoch so that a revert to a
    previously-approved digest is still forced through re-evaluation."""
    cache.bump_epoch(server_id)
    return admit_manifest(server_id, new_manifest, cache, policy_eval)
