# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-tool-manifest-whose-declared-schema-diverges-from-its-runtime-behavior-the-mcp-schema-shadow-injection-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-tool-manifest-whose-declared-schema-diverges-from-its-runtime-behavior-the-mcp-schema-shadow-injection-boundary.warrant.json
# Markdown SHA-256:   495dbb37ceca1b71b005c7a10b63a0bd097d4b4f27ec75fc110b903d7544c97c
# Code AST SHA-256:   24f80024086df461c45cefb7e58ad338ab36448b50c9ccc891e01915e8fdf564
# Verified Classes:   SchemaShadowViolation, PinnedManifest, TaggedArg
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class SchemaShadowViolation(RuntimeError):
    """Raised when a tool call would forward an argument not authorized by
    the locally pinned manifest, or when the server's effective schema
    diverges from the pinned manifest hash."""
    pass


@dataclass(frozen=True)
class PinnedManifest:
    tool_name: str
    input_schema: dict[str, Any]
    manifest_hash: str

    @classmethod
    def pin(cls, tool_name: str, input_schema: dict[str, Any]) -> "PinnedManifest":
        canonical = json.dumps(input_schema, sort_keys=True, separators=(",", ":"))
        return cls(
            tool_name=tool_name,
            input_schema=input_schema,
            manifest_hash=hashlib.sha256(canonical.encode()).hexdigest(),
        )


@dataclass(frozen=True)
class TaggedArg:
    key: str
    value: Any
    origin_agent: str  # id of the agent that first produced this argument


def attest_server_schema(pinned: PinnedManifest, server_effective_schema: dict[str, Any]) -> None:
    """Refuse the session if the server's runtime schema diverges from the pin."""
    canonical = json.dumps(server_effective_schema, sort_keys=True, separators=(",", ":"))
    effective_hash = hashlib.sha256(canonical.encode()).hexdigest()
    if effective_hash != pinned.manifest_hash:
        raise SchemaShadowViolation(
            f"effective schema for {pinned.tool_name!r} diverges from pinned manifest "
            f"(pinned={pinned.manifest_hash[:12]} effective={effective_hash[:12]})"
        )


def strip_to_declared(
    pinned: PinnedManifest,
    args: list[TaggedArg],
    current_agent: str,
) -> dict[str, Any]:
    """Drop any argument not declared in the pinned schema, and any argument
    whose origin is a different agent (handoff replay). This is the client-side
    enforcement of the schema-shadow boundary; it does not trust the server's
    additionalProperties clause."""
    declared = set(pinned.input_schema.get("properties", {}).keys())
    out: dict[str, Any] = {}
    for arg in args:
        if arg.key not in declared:
            # Undeclared key: never forward, regardless of what the server accepts.
            continue
        if arg.origin_agent != current_agent:
            # Argument outlived the schema that authorized it (peer revision
            # drift, stale context, or echoed injection). Drop it.
            continue
        out[arg.key] = arg.value
    return out


def invoke_tool(
    pinned: PinnedManifest,
    args: list[TaggedArg],
    current_agent: str,
    server_effective_schema: dict[str, Any],
) -> dict[str, Any]:
    attest_server_schema(pinned, server_effective_schema)

    declared = set(pinned.input_schema.get("properties", {}).keys())
    required = set(pinned.input_schema.get("required", []))
    forwarded = strip_to_declared(pinned, args, current_agent)

    missing = required - forwarded.keys()
    if missing:
        raise SchemaShadowViolation(
            f"required fields {sorted(missing)} missing after strip for {pinned.tool_name!r}"
        )

    # Only now is it safe to serialize the tools/call request.
    return {"tool": pinned.tool_name, "arguments": forwarded}
