# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-re-negotiated-mcp-tool-schema-at-the-call-boundary-rather-than-at-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-re-negotiated-mcp-tool-schema-at-the-call-boundary-rather-than-at-handshake.warrant.json
# Markdown SHA-256:   44a7de72e609c1d342d8f9b0b24a893153b16e2e2b380f82f666658dcf4e6e1a
# Code AST SHA-256:   52e25bd870108017c9289144bc1e2a00d59443b9792c6cf3809070ab63596bdd
# Verified Classes:   SchemaDriftError, ToolSchemaMismatchError, ToolVersion, CachedTool
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Any

class SchemaDriftError(RuntimeError):
    """Raised when a pending tool call was derived from a stale schema."""
    pass

class ToolSchemaMismatchError(SchemaDriftError):
    """Arguments pass old schema but fail current schema at call boundary."""
    pass

@dataclass
class ToolVersion:
    schema_hash: str
    description_hash: str
    schema: dict
    description: str

@dataclass
class CachedTool:
    name: str
    version: ToolVersion
    dirty: bool = False

def _hash(obj: Any) -> str:
    return hashlib.sha256(repr(obj).encode()).hexdigest()

def make_version(schema: dict, description: str) -> ToolVersion:
    return ToolVersion(_hash(schema), _hash(description), schema, description)

def validate_against(schema: dict, args: dict) -> bool:
    # Minimal structural check: required fields present, enums respected.
    for req in schema.get("required", []):
        if req not in args:
            return False
    props = schema.get("properties", {})
    for key, val in args.items():
        spec = props.get(key)
        if spec is None:
            continue
        if "enum" in spec and val not in spec["enum"]:
            return False
        if "maxLength" in spec and isinstance(val, str) and len(val) > spec["maxLength"]:
            return False
    return True

def prepare_call(
    cached: CachedTool,
    current: ToolVersion,
    pending_args: dict,
) -> dict:
    """Gate a pending tool call behind schema-drift detection."""
    if not cached.dirty and current.schema_hash == cached.version.schema_hash:
        return pending_args

    if current.description_hash != cached.version.description_hash and \
       current.schema_hash == cached.version.schema_hash:
        # Semantics shifted without structural signal: force re-derivation.
        raise SchemaDriftError(
            f"description drift on {cached.name}: re-inject description before call"
        )

    if current.schema_hash != cached.version.schema_hash:
        passes_new = validate_against(current.schema, pending_args)
        passes_old = validate_against(cached.version.schema, pending_args)
        if not passes_new and passes_old:
            raise ToolSchemaMismatchError(
                f"pending args for {cached.name} valid under stale schema "
                f"{cached.version.schema_hash[:8]} but invalid under current "
                f"{current.schema_hash[:8]}; re-derive and retry"
            )
        # Widening or already-valid: accept, refresh, clear dirty.
        cached.version = current
        cached.dirty = False
        return pending_args

    cached.version = current
    cached.dirty = False
    return pending_args
