# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-mcp-tool-schema-renegotiates-mid-handoff-across-an-a2a-delegation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-mcp-tool-schema-renegotiates-mid-handoff-across-an-a2a-delegation-chain.warrant.json
# Markdown SHA-256:   69502fcd7ce5fe0022490ebeecb3f7b8e74da247e2e001a4a0d7078fb7b8de52
# Code AST SHA-256:   1eef078a661831e3dccecadd2e482313461a79deccb9b2a0beecda084b8ca387
# Verified Classes:   SchemaDriftError, A2ATask, MCPClient
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class SchemaDriftError(RuntimeError):
    """Raised when a child's live MCP tool schema diverges from the schema
    bound to the in-flight A2A task. Terminal: must not be retried or
    planner-repaired."""

    def __init__(self, tool: str, added_required: list[str], removed: list[str], digest_bound: str, digest_live: str):
        self.tool = tool
        self.added_required = added_required
        self.removed = removed
        self.digest_bound = digest_bound
        self.digest_live = digest_live
        super().__init__(
            f"schema drift on tool {tool!r}: added_required={added_required} "
            f"removed={removed} bound={digest_bound[:12]} live={digest_live[:12]}"
        )


@dataclass
class A2ATask:
    intent: str
    context_id: str
    capability_digest: str  # digest of the MCP tools/list the parent bound at delegation


@dataclass
class MCPClient:
    session_tools: dict[str, dict] = field(default_factory=dict)

    def digest(self) -> str:
        canonical = json.dumps(self.session_tools, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(canonical.encode()).hexdigest()

    def refresh(self) -> None:
        # In production: issue tools/list and replace session_tools.
        ...


def invoke_tool(client: MCPClient, task: A2ATask, tool: str, args: dict) -> dict:
    client.refresh()
    live_digest = client.digest()
    if live_digest != task.capability_digest:
        bound = json.loads(task.capability_digest)  # illustrative: real impl diffs schemas
        live = client.session_tools.get(tool, {})
        bound_tool = bound.get(tool, {}) if isinstance(bound, dict) else {}
        added = [k for k in live.get("required", []) if k not in bound_tool.get("required", [])]
        removed = [k for k in bound_tool.get("required", []) if k not in live.get("required", [])]
        raise SchemaDriftError(tool, added, removed, task.capability_digest, live_digest)
    # Digest matches: safe to call. Server still validates, but we are coherent.
    return {"ok": True, "tool": tool, "args": args}
