# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-tool-manifest-s-declared-schema-and-its-behavioral-effect-when-an-mcp-server-is-silently-swap.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-tool-manifest-s-declared-schema-and-its-behavioral-effect-when-an-mcp-server-is-silently-swap.warrant.json
# Markdown SHA-256:   e8f9cc3de66c859521f5b8c22436ef6ee1e9b6a2f6b1f7754072968a2870a658
# Code AST SHA-256:   48258182d6fb804dfae7f65b9f9a65fcd7d5a88c3bf281363d3d3e5b2f9fc3c4
# Verified Classes:   CapabilityEscalationError, ManifestDriftError, ToolManifest, EffectProfile, ManifestGuard
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class CapabilityEscalationError(RuntimeError):
    """Raised when a tool's observed effect contradicts its declared manifest."""


class ManifestDriftError(RuntimeError):
    """Raised when the live manifest digest diverges from the pinned digest."""


@dataclass
class ToolManifest:
    name: str
    input_schema: dict
    description: str
    read_only_hint: bool = False

    def digest(self) -> str:
        payload = json.dumps(
            {
                "name": self.name,
                "input_schema": self.input_schema,
                "description": self.description,
                "read_only_hint": self.read_only_hint,
            },
            sort_keys=True,
        ).encode()
        return hashlib.sha256(payload).hexdigest()


@dataclass
class EffectProfile:
    egress_hosts: set[str] = field(default_factory=set)
    write_paths: set[str] = field(default_factory=set)
    spawned_binaries: set[str] = field(default_factory=set)


class ManifestGuard:
    def __init__(self, pinned: dict[str, ToolManifest]):
        # pinned: manifest captured at handshake, keyed by tool name
        self._pinned = {name: m.digest() for name, m in pinned.items()}
        self._manifests = dict(pinned)

    def verify_before_call(self, live: ToolManifest) -> None:
        expected = self._pinned.get(live.name)
        if expected is None:
            raise ManifestDriftError(
                f"tool {live.name!r} appeared after handshake; refusing call"
            )
        actual = live.digest()
        if actual != expected:
            # Identical schema + changed description is the swap signature.
            raise ManifestDriftError(
                f"manifest digest drift for {live.name!r}: "
                f"pinned={expected[:12]} live={actual[:12]}"
            )

    def check_effects(self, tool: ToolManifest, observed: EffectProfile) -> None:
        if tool.read_only_hint:
            if observed.egress_hosts:
                raise CapabilityEscalationError(
                    f"{tool.name!r} declared readOnly but egressed to "
                    f"{sorted(observed.egress_hosts)}"
                )
            if observed.write_paths:
                raise CapabilityEscalationError(
                    f"{tool.name!r} declared readOnly but wrote "
                    f"{sorted(observed.write_paths)}"
                )
            if observed.spawned_binaries:
                raise CapabilityEscalationError(
                    f"{tool.name!r} declared readOnly but spawned "
                    f"{sorted(observed.spawned_binaries)}"
                )


def invoke(guard: ManifestGuard, tool: ToolManifest, args: dict,
           sandbox) -> object:
    guard.verify_before_call(tool)
    result = sandbox.call(tool.name, args)
    guard.check_effects(tool, sandbox.effect_profile(tool.name))
    return result
