# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-validate-tool-arguments-after-schema-drift-at-the-mcp-server-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-validate-tool-arguments-after-schema-drift-at-the-mcp-server-boundary.warrant.json
# Markdown SHA-256:   fa6f1d78b7d23e57ddd6c3a4c74c24a8626565d1297042c15859f7944503ecf1
# Code AST SHA-256:   1d6ea174657e6f22d9b5a3bea532ec89f099702903db6ba844d2114080a94dd2
# Verified Classes:   SchemaDriftEgressError, Guard
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SchemaDriftEgressError(RuntimeError):
    """Raised when a tool call would dispatch under a guard whose field
    coverage no longer matches the server's currently effective inputSchema."""


@dataclass(frozen=True)
class Guard:
    schema_hash: str
    inspected_fields: frozenset
    additional_properties_closed: bool


def canonical_hash(schema: dict) -> str:
    return hashlib.sha256(
        json.dumps(schema, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()


def derive_guard(schema: dict, policy_rules: dict) -> Guard:
    props = set(schema.get("properties", {}).keys())
    # Every property must have an explicit egress rule; shape-match default-allow is forbidden.
    uncovered = props - set(policy_rules.keys())
    if uncovered:
        raise SchemaDriftEgressError(
            f"no egress policy rule for properties {sorted(uncovered)}; "
            "cannot derive a sound guard for drifted schema"
        )
    return Guard(
        schema_hash=canonical_hash(schema),
        inspected_fields=frozenset(props),
        additional_properties_closed=schema.get("additionalProperties") is False,
    )


def dispatch(tool_call: dict, cached_guard: Guard, live_schema: dict,
             policy_rules: dict) -> dict:
    live_hash = canonical_hash(live_schema)
    args = tool_call.get("arguments", {})

    if live_hash != cached_guard.schema_hash:
        # Drift detected: never dispatch on the stale guard, even if it would accept.
        new_guard = derive_guard(live_schema, policy_rules)  # may raise -> hard deny
        if not new_guard.additional_properties_closed:
            raise SchemaDriftEgressError(
                "server relaxed additionalProperties; unguarded egress channel possible"
            )
        if not set(args.keys()) <= new_guard.inspected_fields:
            raise SchemaDriftEgressError(
                f"arguments carry fields {sorted(set(args) - new_guard.inspected_fields)} "
                "not covered by re-derived guard"
            )
        return _apply_egress(args, policy_rules)

    if not cached_guard.additional_properties_closed:
        raise SchemaDriftEgressError("cached guard has open additionalProperties")
    if not set(args.keys()) <= cached_guard.inspected_fields:
        raise SchemaDriftEgressError(
            f"arguments carry fields {sorted(set(args) - cached_guard.inspected_fields)} "
            "outside cached guard coverage"
        )
    return _apply_egress(args, policy_rules)


def _apply_egress(args: dict, policy_rules: dict) -> dict:
    for key, value in args.items():
        rule = policy_rules[key]
        if not rule(value):
            raise SchemaDriftEgressError(f"egress denied for field {key!r}")
    return {"status": "dispatched", "args": args}
