# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-re-listed-mcp-tool-s-changed-inputschema-as-a-new-capability-grant-rather-than-a-schema-update.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-re-listed-mcp-tool-s-changed-inputschema-as-a-new-capability-grant-rather-than-a-schema-update.warrant.json
# Markdown SHA-256:   6a01c5daa68a188b80df5b1152d39bec0fe4ccfca5fb20825caf2857652a69c5
# Code AST SHA-256:   f375636fc98592ab89fcb80bdd10bb5567ab94df766d312a95e90227629cb218
# Verified Classes:   CapabilityEscalationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Any


class CapabilityEscalationError(RuntimeError):
    """Raised when a re-listed tool widens its input surface under an existing approval."""
    pass


def canonical_schema_hash(schema: dict[str, Any]) -> str:
    # Sort keys, drop description-only churn from the hash, keep all structural constraints.
    structural = {
        "properties": schema.get("properties", {}),
        "required": sorted(schema.get("required", [])),
        "additionalProperties": schema.get("additionalProperties", True),
    }
    blob = json.dumps(structural, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(blob.encode()).hexdigest()


def widens(old: dict[str, Any], new: dict[str, Any]) -> list[str]:
    reasons: list[str] = []
    old_props = old.get("properties", {})
    new_props = new.get("properties", {})

    for name, old_spec in old_props.items():
        new_spec = new_props.get(name)
        if new_spec is None:
            reasons.append(f"property {name!r} removed (narrowing; not an escalation)")
            continue
        for constraint in ("pattern", "enum", "maximum", "maxLength", "format"):
            if constraint in old_spec and constraint not in new_spec:
                reasons.append(f"{name}.{constraint} constraint removed")

    for name in new_props:
        if name not in old_props:
            reasons.append(f"new property {name!r} admitted")

    if old.get("additionalProperties", True) is False and new.get("additionalProperties", True) is not False:
        reasons.append("additionalProperties loosened")

    return [r for r in reasons if "narrowing" not in r]


def reconcile_tool(
    approved: dict[str, Any],
    relisted: dict[str, Any],
) -> None:
    if relisted["name"] != approved["name"]:
        raise CapabilityEscalationError(
            f"identity mismatch: approved {approved['name']!r} vs relisted {relisted['name']!r}"
        )

    old_hash = canonical_schema_hash(approved["inputSchema"])
    new_hash = canonical_schema_hash(relisted["inputSchema"])

    if old_hash == new_hash:
        return  # no-op; safe to continue under existing approval

    escalation = widens(approved["inputSchema"], relisted["inputSchema"])
    if escalation:
        raise CapabilityEscalationError(
            f"tool {relisted['name']!r} widened its input surface under an existing approval: "
            + "; ".join(escalation)
            + f" (approved_hash={old_hash[:12]}, relisted_hash={new_hash[:12]}); "
            "treating as new capability grant, approval invalidated"
        )

    # Narrowing only: accept, but re-key the approval to the new hash.
    approved["inputSchema"] = relisted["inputSchema"]
