# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-skill-injected-mcp-tool-s-declared-schema-over-its-observed-behavior.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-skill-injected-mcp-tool-s-declared-schema-over-its-observed-behavior.warrant.json
# Markdown SHA-256:   d5551067970b48094de46c3b202e85dfff45f51eb0c3ae0658ed09560d0df086
# Code AST SHA-256:   44100060b6dcc826d638e8818cfe1b001bd53b751b03d6e7a4ed410b99857bf9
# Verified Classes:   SchemaBehaviorDivergence
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SchemaBehaviorDivergence(RuntimeError):
    """Raised when a tool result is not derivable from the arguments of the call that produced it."""
    pass


def verified_call(tool, args, session, prior_results):
    """
    Dispatch a tools/call and enforce the result-argument correspondence invariant.
    prior_results: dict of call_index -> (args, result) for this session, used to detect
    stateful divergence where the server returns a result keyed on call count, not args.
    """
    call_index = len(prior_results)
    result = tool.call(args, session=session)

    # Shape check: the result must conform to the declared output schema.
    if not tool.output_schema_conforms(result):
        raise SchemaBehaviorDivergence(
            f"tool {tool.name!r} call #{call_index}: result does not conform to declared output schema"
        )

    # Correspondence check: the result must be derivable from *these* arguments.
    # For a read_file tool, that means the returned bytes must correspond to args["path"],
    # not to any path used in a prior call in this session.
    for prior_index, (prior_args, prior_result) in prior_results.items():
        if prior_args == args:
            continue
        if tool.results_equivalent_for_distinct_args(prior_args, prior_result, args, result):
            raise SchemaBehaviorDivergence(
                f"tool {tool.name!r} call #{call_index} with args {args!r} returned a payload "
                f"equivalent to call #{prior_index} with args {prior_args!r}; "
                f"result is a function of call count, not arguments"
            )

    prior_results[call_index] = (args, result)
    return result


def bind_and_execute(server, requested_tool, args, session):
    listing = server.list_tools()
    tool = next((t for t in listing if t.name == requested_tool), None)
    if tool is None:
        raise SchemaBehaviorDivergence(f"tool {requested_tool!r} absent from tools/list")

    # Re-list invalidation: if the schema changed mid-session, prior results are untrusted.
    if session.cached_schema.get(tool.name) not in (None, tool.schema):
        session.prior_results.clear()
    session.cached_schema[tool.name] = tool.schema

    return verified_call(tool, args, session, session.prior_results)
