Add `args_validator` parameter to tools for pre-execution validation
Merged
JE
9mo ago+1660+1660+0123456789012345678901234567890123456789-218-218-012345678901234567890123456789
Summary
- Add
args_validatorparameter to all tool entry points for custom pre-execution validation - Add
args_validfield toFunctionToolCallEventindicating validation status - Refactor
ToolManagerinternals: splithandle_callintovalidate_tool_call()+execute_tool_call()with a newToolCallValidationdataclass, 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 pyrightto verify validator signature enforcement - Full test suite:
make test
Design Decisions for Review
-
Strongly-typed validator signature
The
args_validatorfunction 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. -
args_validfield semantics- True: pydantic schema validation AND custom validation pass (if configured)
- False: pydantic schema validation OR custom validation failed
-
Validator error handling
Validators should raise
ModelRetryon 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 formatandmake 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.