# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-manifest-poisoned-skill-injection-when-an-mcp-server-s-tool-descriptions-mutate-between-handshake-and-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-manifest-poisoned-skill-injection-when-an-mcp-server-s-tool-descriptions-mutate-between-handshake-and-invocation.warrant.json
# Markdown SHA-256:   269525343122ce21d9c1c3279a7ca5bdbacad6f866cda6ed174079ff1445d8c9
# Code AST SHA-256:   2450f8cd125bdbf29fea4f4d58697f7185517b5779129257c37bc89e14e67b7b
# Verified Classes:   ManifestMutationError, ToolManifest, ManifestGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ManifestMutationError(RuntimeError):
    """Raised when a tool manifest's description drifts between handshake and invocation."""
    pass


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

    def fingerprint(self) -> str:
        # The description is part of the identity, not cosmetic metadata.
        h = hashlib.sha256()
        h.update(self.name.encode())
        h.update(b"\x00")
        h.update(self.description.encode())
        h.update(b"\x00")
        h.update(repr(sorted(self.input_schema.items())).encode())
        return h.hexdigest()


class ManifestGuard:
    def __init__(self, checkpointed: dict[str, str]):
        # name -> fingerprint captured at handshake / last trusted checkpoint
        self._trusted = dict(checkpointed)

    def verify_refresh(self, manifests: list[ToolManifest]) -> None:
        for m in manifests:
            prior = self._trusted.get(m.name)
            current = m.fingerprint()
            if prior is None:
                # New tool appearing mid-session: also a mutation event.
                raise ManifestMutationError(
                    f"tool {m.name!r} appeared after handshake; re-authorize before use"
                )
            if prior != current:
                raise ManifestMutationError(
                    f"tool {m.name!r} manifest mutated since checkpoint "
                    f"(prior={prior[:12]} current={current[:12]}); "
                    f"description delta must be reviewed, not cached through"
                )

    def validate_arguments(self, manifest: ToolManifest, args: dict) -> None:
        allowed = set(manifest.input_schema.get("properties", {}).keys())
        unknown = set(args) - allowed
        if unknown:
            # A lenient server would silently drop these; we must not let it.
            raise ManifestMutationError(
                f"arguments {sorted(unknown)} not in {manifest.name!r} inputSchema; "
                f"possible description-injection steering"
            )
