Add `args_validator` parameter to tools for pre-execution validation

Merged
JE
9mo ago
+1660-218

Closes #3992
Closes #3893

Summary

  • Add args_validator parameter to all tool entry points for custom pre-execution validation
  • Add args_valid field to FunctionToolCallEvent indicating validation status
  • Refactor ToolManager internals: split handle_call into validate_tool_call() + execute_tool_call() with a new ToolCallValidation dataclass, separating validation from execution
  • For deferred tools, validation now runs at deferral time — only tool calls with valid arguments are deferred, while failed validation triggers a retry like regular tools

Test plan

  • Run new args_validator tests in tools: uv run pytest tests/test_tools.py -k args_validator -v
  • Run new args_validator tests in streaming: uv run pytest tests/test_streaming.py -k args_validator -v
  • Run existing tool tests: uv run pytest tests/test_tools.py -v
  • Run existing agent tests: uv run pytest tests/test_agent.py -v
  • Run existing streaming tests: uv run pytest tests/test_streaming.py -v
  • Type checking: uv run pyright to verify validator signature enforcement
  • Full test suite: make test

Design Decisions for Review

  1. Strongly-typed validator signature

    The args_validator function has the exact same typed parameters as the tool function:

    def my_validator(ctx: RunContext[int], user_id: int) -> None:
        if user_id < 0:
            raise ModelRetry('user_id must be positive')
    
    
    @agent.tool(args_validator=my_validator)
    def get_user(ctx: RunContext[int], user_id: int) -> str:
        return f"User {user_id}"
    

    Trade-off: This provides IDE autocomplete and type safety, but requires the validator to duplicate the parameter list. An alternative would be Callable[[RunContext, dict[str, Any]], None] which is simpler but loses type safety.

  2. args_valid field semantics

    • True: pydantic schema validation AND custom validation pass (if configured)
    • False: pydantic schema validation OR custom validation failed
  3. Validator error handling

    Validators should raise ModelRetry on failure. Other exceptions propagate as tool errors. This matches the existing pattern for tool execution errors.

Pre-Review Checklist

  • Any AI generated code has been reviewed line-by-line by the human PR author, who stands by it.
  • No breaking changes in accordance with the version policy.
  • Linting and type checking pass per make format and make typecheck.
  • PR title is fit for the release changelog.

Pre-Merge Checklist

  • New tests for any fix or new behavior, maintaining 100% coverage.
  • Updated documentation for new features and behaviors, including docstrings for API docs.