# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-re-fetched-mcp-tool-manifest-that-silently-redefines-a-previously-approved-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-re-fetched-mcp-tool-manifest-that-silently-redefines-a-previously-approved-tool.warrant.json
# Markdown SHA-256:   74a0f1d3ff4e5a1fd0191b75a785ab151898d247b22f7932b458b8553ad26e18
# Code AST SHA-256:   d9bf8756e27d8fb4b2b5f9683600de95140c7cc4abac4b3667cc10de988a8185
# Verified Classes:   ManifestIntegrityError, ApprovedManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class ManifestIntegrityError(RuntimeError):
    """Raised when a tool manifest at invocation time diverges from the approved manifest."""
    pass


@dataclass
class ApprovedManifest:
    server: str
    tool: str
    content_hash: str
    approved_by: str
    sensitive: bool  # touches secrets, fs, egress, or money


def _hash_manifest(manifest: dict) -> str:
    # Canonicalize: description text and added optional params are load-bearing,
    # so hash the full serialized manifest, not a schema-compat projection.
    canonical = json.dumps(manifest, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def invoke_tool(
    manifest: dict,
    approved: ApprovedManifest,
    arguments: dict,
    re_approval_token: Optional[str] = None,
) -> dict:
    live_hash = _hash_manifest(manifest)

    if live_hash != approved.content_hash:
        # Any byte difference — including description-only or additive-optional-param
        # changes — is security-relevant because it can steer argument generation.
        if approved.sensitive and re_approval_token is None:
            raise ManifestIntegrityError(
                f"Manifest for {approved.server}/{approved.tool} changed "
                f"(approved={approved.content_hash[:12]} live={live_hash[:12]}); "
                f"re-approval required before invocation."
            )
        if not approved.sensitive and re_approval_token is None:
            # Fail-open only for non-sensitive, idempotent, read-only tools; log delta.
            pass  # caller is expected to record the delta out-of-band

    # Proceed with the actual transport call against the verified manifest.
    return {"tool": approved.tool, "arguments": arguments, "manifest_hash": live_hash}


def handle_reconnect(
    live_manifests: dict[str, dict],
    approved_set: dict[str, ApprovedManifest],
) -> dict[str, ApprovedManifest]:
    """Reconnect re-fetches manifests; any drift must invalidate approval, not refresh it."""
    for key, manifest in live_manifests.items():
        approved = approved_set.get(key)
        if approved is None:
            # New tool appearing post-approval is itself a delta requiring approval.
            raise ManifestIntegrityError(
                f"Unapproved tool {key} appeared on reconnect; refusing to expose it."
            )
        if _hash_manifest(manifest) != approved.content_hash:
            # Do NOT overwrite approved.content_hash here. That is the bug.
            raise ManifestIntegrityError(
                f"Tool {key} manifest drifted on reconnect; approval invalidated."
            )
    return approved_set
