# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-re-fetched-mcp-tool-manifest-as-a-capability-escalation-event-rather-than-a-routine-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-re-fetched-mcp-tool-manifest-as-a-capability-escalation-event-rather-than-a-routine-refresh.warrant.json
# Markdown SHA-256:   38628bd48180cfa80858a6a7ca2837f30ea501ec4ef636b1c9d722137602f088
# Code AST SHA-256:   2e8d91659123a6a78c384983258a2742785c641f07c4fe3dac335843bb7fb17a
# Verified Classes:   CapabilityEscalationError, PinnedManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class CapabilityEscalationError(RuntimeError):
    """Raised when a re-fetched MCP manifest widens the pinned capability surface."""


@dataclass(frozen=True)
class PinnedManifest:
    raw: bytes
    digest: str
    tools: dict[str, dict[str, Any]]


def pin_manifest(raw: bytes) -> PinnedManifest:
    doc = json.loads(raw)
    tools = {t["name"]: t for t in doc.get("tools", [])}
    return PinnedManifest(raw=raw, digest=hashlib.sha256(raw).hexdigest(), tools=tools)


def _schema_widens(old: dict[str, Any], new: dict[str, Any]) -> bool:
    # A schema widens if it drops additionalProperties:false, drops a pattern,
    # drops a required field, or grows its enum/property set.
    if old.get("additionalProperties") is False and new.get("additionalProperties") is not False:
        return True
    if "pattern" in old and "pattern" not in new:
        return True
    old_req = set(old.get("required", []))
    if not old_req.issubset(set(new.get("required", []))):
        return True
    old_props = set(old.get("properties", {}))
    if not old_props.issubset(set(new.get("properties", {}))):
        return True
    return False


def verify_manifest(pinned: PinnedManifest, fresh_raw: bytes) -> None:
    fresh_doc = json.loads(fresh_raw)
    fresh_tools = {t["name"]: t for t in fresh_doc.get("tools", [])}

    added = set(fresh_tools) - set(pinned.tools)
    if added:
        raise CapabilityEscalationError(
            f"manifest added tools not present at pin: {sorted(added)}"
        )

    for name, old in pinned.tools.items():
        new = fresh_tools.get(name)
        if new is None:
            continue  # removal is a safe downgrade
        if new.get("description", "").strip() != old.get("description", "").strip():
            raise CapabilityEscalationError(
                f"tool {name!r} description changed; description is an injection channel"
            )
        if _schema_widens(old.get("inputSchema", {}), new.get("inputSchema", {})):
            raise CapabilityEscalationError(
                f"tool {name!r} inputSchema widened; argument surface expanded"
            )


def refresh_tools(pinned: PinnedManifest, fetch_manifest) -> PinnedManifest:
    fresh_raw = fetch_manifest()
    verify_manifest(pinned, fresh_raw)  # raises on any widening
    return pinned  # narrowing deltas are logged but the pin is retained
