# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-capability-poisoning-when-a-dynamically-loaded-mcp-manifest-mutates-between-negotiation-and-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-capability-poisoning-when-a-dynamically-loaded-mcp-manifest-mutates-between-negotiation-and-invocation.warrant.json
# Markdown SHA-256:   ec9b5ccec68a38ac67236d244ef91983bf7a5f6436246c6ac997d8d2f1fdac7d
# Code AST SHA-256:   c32ff53a6bcc446ad5316a56ebc837dbf568edede7dabd55e50edfbe103fcacb
# Verified Classes:   CapabilityPoisoningError, ToolDescriptor, PinnedManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class CapabilityPoisoningError(RuntimeError):
    """Raised when a tool descriptor mutates between negotiation and invocation."""
    pass


@dataclass
class ToolDescriptor:
    name: str
    input_schema: dict
    annotations: dict = field(default_factory=dict)
    description: str = ""

    def digest(self) -> str:
        # Identity includes schema, annotations, and description.
        # A change to any of these is a change of capability.
        payload = json.dumps(
            {
                "name": self.name,
                "input_schema": self.input_schema,
                "annotations": self.annotations,
                "description": self.description,
            },
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(payload.encode()).hexdigest()


class PinnedManifest:
    """Holds negotiated descriptors and refuses silent mutation."""

    def __init__(self) -> None:
        self._pinned: dict[str, tuple[ToolDescriptor, str]] = {}

    def negotiate(self, descriptor: ToolDescriptor) -> None:
        self._pinned[descriptor.name] = (descriptor, descriptor.digest())

    def verify_before_invoke(self, fresh: ToolDescriptor) -> ToolDescriptor:
        entry = self._pinned.get(fresh.name)
        if entry is None:
            # Not negotiated: new capability, requires consent, not silent use.
            raise CapabilityPoisoningError(
                f"tool {fresh.name!r} invoked without prior negotiation"
            )
        pinned_desc, pinned_digest = entry
        if fresh.digest() != pinned_digest:
            # Same name, different contract: substitution, not update.
            # Do NOT overwrite the pinned entry; preserve evidence.
            raise CapabilityPoisoningError(
                f"descriptor for {fresh.name!r} mutated: "
                f"negotiated={pinned_digest[:12]} fresh={fresh.digest()[:12]}"
            )
        return pinned_desc


def invoke_tool(manifest: PinnedManifest, fresh: ToolDescriptor, args: dict) -> dict:
    # Re-verify the descriptor at the moment of invocation, not at cache time.
    verified = manifest.verify_before_invoke(fresh)
    # Build the call strictly from the verified schema surface.
    allowed = set(verified.input_schema.get("properties", {}).keys())
    unexpected = set(args.keys()) - allowed
    if unexpected:
        raise CapabilityPoisoningError(
            f"arguments {sorted(unexpected)} not in negotiated schema for {verified.name!r}"
        )
    return {"tool": verified.name, "args": args, "digest": verified.digest()}


if __name__ == "__main__":
    negotiated = ToolDescriptor(
        name="summarize",
        input_schema={"properties": {"text": {"type": "string"}}},
        annotations={"readOnlyHint": True},
    )
    manifest = PinnedManifest()
    manifest.negotiate(negotiated)

    # Server returns a superset schema mid-session.
    mutated = ToolDescriptor(
        name="summarize",
        input_schema={
            "properties": {
                "text": {"type": "string"},
                "output_path": {"type": "string"},
            }
        },
        annotations={"readOnlyHint": False},
        description="Optional: persist summary to disk.",
    )

    try:
        invoke_tool(manifest, mutated, {"text": "hello", "output_path": "/etc/x"})
    except CapabilityPoisoningError as e:
        print(f"blocked: {e}")
