# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-an-mcp-tool-schema-mutates-between-tools-list-and-tools-call-the-silent-argument-coercion-trap.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-an-mcp-tool-schema-mutates-between-tools-list-and-tools-call-the-silent-argument-coercion-trap.warrant.json
# Markdown SHA-256:   148e78bec3a2f36f1ce48dd496dc5dfb96c10c14cc71c296bdf5769aef71c7ae
# Code AST SHA-256:   177e77fee0e53f38cee2eadede1b72ae07e2193a15a005e9f10ab754a479a058
# Verified Classes:   SchemaLeaseViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SchemaLeaseViolation(RuntimeError):
    """Raised when a tool call's result cannot be reconciled with the cached
    schema lease — either the schema mutated under us, or the result's
    semantics fall outside the scope the cached schema implied."""
    pass


def guarded_tool_call(client, tool_name, args, expected_scope, lease):
    """Invoke an MCP tool under a schema lease, asserting result scope.

    lease: {"schema_hash": str, "required": set[str], "scope_field": str | None}
    expected_scope: value the scope_field must match in every result row,
                    or None if the tool is not scope-sensitive.
    """
    # 1. If scope-sensitive and we cannot assert, we must re-negotiate first.
    if expected_scope is not None and lease.get("scope_field") is None:
        raise SchemaLeaseViolation(
            f"tool {tool_name!r} is scope-sensitive but lease carries no "
            f"scope_field; refusing to call on a stale schema"
        )

    result = client.call_tool(tool_name, args)

    # 2. Coercive-acceptance detection: the server may have accepted args that
    #    conformed to an old schema and reinterpreted them. Check result scope.
    if expected_scope is not None:
        field = lease["scope_field"]
        for row in result.get("rows", []):
            if row.get(field) != expected_scope:
                # Schema diverged or server default-filled a widened scope.
                fresh = client.list_tools()
                fresh_hash = hash_schema(fresh[tool_name]["inputSchema"])
                if fresh_hash != lease["schema_hash"]:
                    raise SchemaLeaseViolation(
                        f"schema for {tool_name!r} mutated mid-session "
                        f"({lease['schema_hash']} -> {fresh_hash}); result "
                        f"scope {row.get(field)!r} != expected "
                        f"{expected_scope!r}. Re-plan required."
                    )
                raise SchemaLeaseViolation(
                    f"result for {tool_name!r} escaped scope {expected_scope!r} "
                    f"despite stable schema; server-side default-fill suspected"
                )

    return result


def hash_schema(input_schema):
    import hashlib, json
    return hashlib.sha256(
        json.dumps(input_schema, sort_keys=True).encode()
    ).hexdigest()
