# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-schema-negotiation-drift-when-an-mcp-tool-s-declared-inputschema-is-a-superset-of-the-a2a-v1-0-task-payload-it-receives.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-schema-negotiation-drift-when-an-mcp-tool-s-declared-inputschema-is-a-superset-of-the-a2a-v1-0-task-payload-it-receives.warrant.json
# Markdown SHA-256:   3fd84db24e7b9233242ae9bcd128e194d077f7c55ee2c8d202dc7c37b4a7e4d7
# Code AST SHA-256:   bb677e15bb269dc58888501a07618389b0c4d43b433b8c36ce3dfa70d16f1f54
# Verified Classes:   SchemaNegotiationDrift
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SchemaNegotiationDrift(RuntimeError):
    """Raised when a tool honors argument keys outside the validated/warranted set."""
    pass


def dispatch_with_closure(tool_schema: dict, payload: dict, warrant: dict) -> dict:
    declared = set(tool_schema.get("properties", {}).keys())
    constrained = set(warrant.get("constraints", {}).keys())

    undeclared = set(payload) - declared
    if undeclared:
        raise SchemaNegotiationDrift(
            f"payload keys {sorted(undeclared)} not in tool inputSchema; "
            f"tool may honor them at execution time"
        )

    unconstrained = declared & set(payload) - constrained
    if unconstrained:
        raise SchemaNegotiationDrift(
            f"argument keys {sorted(unconstrained)} present in payload but "
            f"absent from warrant constraint vocabulary; warrant cannot bound them"
        )

    # Force closure before validation so the schema the tool was authored with
    # cannot silently accept extra keys at execution time.
    closed_schema = {**tool_schema, "additionalProperties": False}
    for key, spec in closed_schema.get("properties", {}).items():
        if spec.get("type") == "boolean" and key not in constrained:
            raise SchemaNegotiationDrift(
                f"boolean flag {key!r} toggles execution semantics but is "
                f"not warrant-constrained; refuse to forward"
            )

    return {"tool_schema": closed_schema, "payload": payload, "warrant": warrant}
