# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-mcp-tool-manifest-has-silently-mutated-an-agent-s-capability-surface-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-mcp-tool-manifest-has-silently-mutated-an-agent-s-capability-surface-mid-session.warrant.json
# Markdown SHA-256:   613130fece001d2082bfdb4cb212e90a14821665ec9e997b5d0f03591c114597
# Code AST SHA-256:   749e94822f4a81aabcfe566c42c304d4d2901414eebee620002ed5f95326e7a8
# Verified Classes:   CapabilitySurfaceMutationError, PrimedManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class CapabilitySurfaceMutationError(RuntimeError):
    """Raised when the dispatch-time tool manifest diverges from the primed snapshot."""
    pass


@dataclass
class PrimedManifest:
    """Immutable snapshot of the tool surface the model reasoned against."""
    entries: dict[str, str] = field(default_factory=dict)  # name -> sha256(schema)

    @classmethod
    def from_tools(cls, tools: list[dict]) -> "PrimedManifest":
        snap = {}
        for t in tools:
            name = t["name"]
            canonical = json.dumps(t.get("inputSchema", {}), sort_keys=True)
            snap[name] = hashlib.sha256(canonical.encode()).hexdigest()
        return cls(entries=snap)


def verify_dispatch_manifest(
    primed: PrimedManifest,
    live_tools: list[dict],
    allow_strict_narrowing: bool = True,
) -> None:
    """
    Enforce the continuity invariant: the dispatch surface must equal the primed
    surface, or every delta must be a proven-strict narrowing. Otherwise halt.
    """
    live = PrimedManifest.from_tools(live_tools)

    added = set(live.entries) - set(primed.entries)
    removed = set(primed.entries) - set(live.entries)
    if added or removed:
        raise CapabilitySurfaceMutationError(
            f"capability-surface mutation: added={sorted(added)} removed={sorted(removed)}; "
            f"session must re-prime, not merge"
        )

    for name, live_hash in live.entries.items():
        if live_hash == primed.entries[name]:
            continue
        if not allow_strict_narrowing:
            raise CapabilitySurfaceMutationError(
                f"schema drift on {name!r}: hash mismatch, narrowing not permitted"
            )
        # Narrowing check: new schema must be a strict subset of primed schema.
        if not _is_strict_narrowing(primed, name, live_tools):
            raise CapabilitySurfaceMutationError(
                f"schema drift on {name!r}: not a strict narrowing (widening or "
                f"additionalProperties escalation detected)"
            )


def _is_strict_narrowing(primed: PrimedManifest, name: str, live_tools: list[dict]) -> bool:
    live = next(t for t in live_tools if t["name"] == name)
    schema = live.get("inputSchema", {})
    # A widening schema (e.g. additionalProperties: true, or new optional params
    # that expand the accepted domain) is never a valid narrowing.
    if schema.get("additionalProperties") is True:
        return False
    # Conservative default: any schema hash change is treated as non-narrowing
    # unless an explicit, audited narrowing proof is supplied by the caller.
    return False


def dispatch(primed: PrimedManifest, live_tools: list[dict], call: dict) -> dict:
    verify_dispatch_manifest(primed, live_tools)
    name = call["tool"]
    if name not in primed.entries:
        raise CapabilitySurfaceMutationError(
            f"dispatch to unprimed tool {name!r} refused"
        )
    # ... route to MCP transport with exact-match semantics only ...
    return {"status": "dispatched", "tool": name}
