Support requesting approval or deferring a call from a tool's `args_validator`
Fixes a bug with no existing issue: an args_validator that raises ApprovalRequired or CallDeferred aborts the whole run instead of deferring the call.
The bug
from pydantic_ai import Agent, ApprovalRequired, DeferredToolRequests, RunContext
from pydantic_ai.messages import ModelMessage, ModelResponse, TextPart, ToolCallPart
from pydantic_ai.models.function import AgentInfo, FunctionModel
from pydantic_ai.toolsets import FunctionToolset
def validate_delete(ctx: RunContext[None], path: str) -> None:
if path.startswith('/etc') and not ctx.tool_call_approved:
raise ApprovalRequired()
toolset = FunctionToolset[None]()
@toolset.tool(args_validator=validate_delete)
def delete_file(ctx: RunContext[None], path: str) -> str:
return f'deleted {path}'
def call_tool(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
if len(messages) == 1:
return ModelResponse(parts=[ToolCallPart('delete_file', {'path': '/etc/passwd'})])
return ModelResponse(parts=[TextPart('done')])
agent = Agent(FunctionModel(call_tool), toolsets=[toolset], output_type=[str, DeferredToolRequests])
print(agent.run_sync('delete /etc/passwd').output)
Before this PR the run dies with a bare exception:
File "pydantic_ai/_tool_execution.py", line 458, in _validate_function_calls
validated = await self.tool_manager.validate_tool_call(call)
File "pydantic_ai/tool_manager.py", line 485, in validate_tool_call
validated_args = await self._run_validate_hooks(call, tool, ctx, allow_partial=False)
File "pydantic_ai/tool_manager.py", line 270, in _validate_tool_args
result = tool.args_validator_func(ctx, **args_dict)
File "repro.py", line 11, in validate_delete
raise ApprovalRequired()
pydantic_ai.exceptions.ApprovalRequired
After it, DeferredToolRequests(approvals=[ToolCallPart(tool_name='delete_file', ...)]).
tool_manager.py treats (SkipToolExecution, CallDeferred, ApprovalRequired, ToolRetryError, ToolFailedError) as "Control flow, not errors" around tool execution, but nothing gave the same treatment to the validation stage. ModelRetry and ToolFailed from a validator work correctly today; the deferral-shaped exceptions didn't.
Our own docs invite exactly this pattern:
docs/tools-advanced.md: "args_validator… is useful for … validating arguments before requesting human approval for deferred tools"- the agent skill reference
references/TOOLS-ADVANCED.md: "for conditional approval, raiseApprovalRequired(...)instead of marking the whole toolrequires_approval=True"
A user following either sentence from a validator got the traceback above.
Why support it rather than reject it
args_validator exists because of #3893 ("Tool args are not validated when tool is marked as approval_required"), whose complaint was: "with deferred tools or tools that require approval, we end up requesting approval first to potentially run into invalid input. It would be better to have all validation occur up-front before any logic is run." #4016 delivered that: "For deferred tools, validation now runs at deferral time — only tool calls with valid arguments are deferred."
So the feature exists precisely to make approval decisions happen after arguments are known good, which makes the validator arguably the better place to decide conditional approval. To be straight about what's being widened: #4016's design notes said "Validators should raise ModelRetry on failure. Other exceptions propagate as tool errors." Deferral-shaped exceptions were never considered there, so this extends a deliberately narrow decision rather than reversing a considered one.
How it works
The deferral is routed into the machinery that already exists for execution-stage deferrals, rather than a second collection path:
_validate_tool_argscatchesCallDeferred/ApprovalRequiredfromargs_validator_funcand re-raises it wrapped in a private_ValidationDeferralthat also carries the schema-validated args (so they aren't lost as the exception passes the hook boundary). It never escapesToolManager.validate_tool_callunwraps it intoValidatedToolCall(args_valid=True, validated_args=..., deferral=exc)— a new field.execute_tool_callre-raisesvalidated.deferralinstead of running the tool.
That last step is the whole trick: from there on the exception is indistinguishable from one raised by the tool function, so _tool_execution.py needed no changes at all. The existing except (CallDeferred, ApprovalRequired) handlers in _call_tools/run_one collect it into deferred_calls['unapproved']/['external'] with its metadata, _resolve_deferred_calls announces the batch (DeferredToolRequestsEvent), a HandleDeferredToolCalls handler can resolve it inline, and otherwise it surfaces in the run's DeferredToolRequests output. ToolManager.handle_call (used for sandboxed/code-mode dispatch) resolves it via _resolve_single_deferred for free.
Design decisions
args_validisTrue. Schema validation passed and the validator made a deliberate control-flow choice, so this is not a validation failure:FunctionToolCallEvent.args_validisTrueandvalidated_argscarries the schema-validated dict. This matches what arequires_approval=Truetool already reports when it's collected as deferred.- The retry budget is untouched, and
failed_toolsisn't marked — a deferral isn't a failure. Pinned by giving the toolretries=0in the tests: if the deferral were treated as a validation failure,_check_max_retrieswould raiseUnexpectedModelBehaviorimmediately instead of deferring. on_tool_validate_errordoes not fire._run_validate_hooksonly catches(ValidationError, ModelRetry), so the deferral already propagated past it; thewrap_tool_validatehandler chain inCombinedCapabilitypasses it through untouched too. Both are now pinned by a test, andAbstractCapability.on_tool_validate_error's docstring says so explicitly (mirroring whaton_tool_execute_erroralready documents).after_tool_validatedoesn't run either, mirroringafter_tool_executeon the execution side.- Partial/streaming validation needs no change, and the premise that it did turned out not to hold.
_validate_tool_argsthreads anallow_partialflag, but for function tools its only caller (validate_tool_call) hardcodesallow_partial=False; output tools take a different path (validate_output_tool_call→processor.hook_validate) and never have anargs_validator_funcat all (OutputToolset.get_toolssets only the schemaargs_validator). So a custom validator can never see partially-built args today and can't emit a deferral from one. A streaming regression test pins it: with tool-call args arriving in three fragments, the validator is consulted exactly once, withctx.partial_outputFalse, and exactly one deferral reaches the batch. I deliberately did not change the partial-validation code paths. SkipToolExecutionis deliberately not honoured from a validator. It's documented as a hook signal forbefore_tool_execute/wrap_tool_execute("skip execution, use this result"), no doc invites it from a validator, and nothing was reported. Honouring it would also require deciding validate-stage semantics forusage.tool_callsaccounting andsucceeded_toolsthat no user has asked for. It stays an ordinary exception that aborts the run, as before. If demand appears it's an additive follow-up, not a behavior change.
Known limitation: deferral metadata on tools that are already deferred by kind
For a tool that's already deferred by kind (requires_approval=True, or an ExternalToolset tool), _collect_deferred_calls collects the call by kind without executing it. Its args_validator's ApprovalRequired(metadata=...) therefore changes nothing about the outcome and its metadata does not reach DeferredToolRequests.metadata. Someone will eventually pass metadata there and wonder, so to be explicit:
- this is pre-existing behavior, not something this PR introduces: a tool body raising
ApprovalRequired(metadata=...)on arequires_approval=Truetool has always had its metadata dropped for the same reason (the body never runs before approval); - it's pinned by
test_args_validator_deferral_metadata_not_merged_for_already_deferred_kinds, which asserts the validator case and the tool-body case behave identically, so changing it later is a deliberate decision rather than an accident; - metadata does flow for the case this PR is about — a plain function tool deferred by the validator's exception (asserted in
test_args_validator_requests_approval); - wiring validator metadata into the kind-based collection path is orthogonal to this fix and out of scope.
Backward compatibility
Nothing changes for validators that don't raise these two exceptions: the only new behavior is on a path that previously crashed the run. ValidatedToolCall gains one optional field with a default.
Durable execution and cross-engine parity
No files under durable_exec/ are touched, and this change is inherently parity-clean across Temporal, DBOS, and Prefect. Evidence, by static analysis (the engines aren't installed in this environment, so I could not run their suites):
- Validation is engine-agnostic.
args_validator_funcis invoked in exactly one place,ToolManager._validate_tool_args(tool_manager.py), reached only viavalidate_tool_call, whose only callers are the graph's_tool_execution.py:458,:480and:801. That's workflow (Temporal), flow (Prefect), or inline workflow code (DBOS) on every engine.grep -rn "validate_tool_call\|ToolManager\|args_validator_func" pydantic_ai_slim/pydantic_ai/durable_exec/returns nothing, so no engine intercepts, replaces, or relocates the validation step. - The engines diverge only below
call_tool, which a deferring validator never reaches (execute_tool_callraises before_run_execute_hooks): Temporal runs it in an activity (temporal/_function_toolset.py:37-49), Prefect in a task (prefect/_function_toolset.py:33), and DBOS runs function tools inline with no wrapper at all (dbos/_agent.py:321). Each shareswrap_tool_call_result/unwrap_tool_call_result(durable_exec/_toolset.py:163,:179) for execution-stageApprovalRequired/CallDeferred. - The workflow-side tool object keeps the real validator for static function toolsets:
DurableFunctionToolsetoverrides onlycall_tool(durable_exec/_toolset.py:333-363) and inherits the wrapper's pass-throughget_tools, soargs_validator_funcis present and runs where it always did. - The one asymmetry vs. the non-durable path is dynamic toolsets, and it is identical on all three engines because it lives in shared code:
DurableDynamicToolset.get_toolshands the workflow a placeholderToolsetToolwithargs_validator=TOOL_SCHEMA_VALIDATORand noargs_validator_func(durable_exec/_toolset.py:411-423), andcall_dynamic_toolre-validates only the schema inside the durable unit before calling the tool (durable_exec/_toolset.py:100-101, Temporal's variant attemporal/_toolset.py:148-149). So a customargs_validatoron a dynamic toolset's tool is skipped under durable execution today — forModelRetryexactly as much as for a deferral. Pre-existing, engine-uniform, and out of scope here.
Note for the in-flight PR that moves argument validation into its own durable unit: the deferral will then have to cross that boundary, and it should be round-tripped as a value the way wrap_tool_call_result/unwrap_tool_call_result already do for execution-stage deferrals (feeding into the _validate_tool_args handling here rather than duplicating it), or a user's approval request will surface as an activity failure.
Tests
tests/test_tools.py::test_args_validator_requests_approval— validator'sApprovalRequireddefers the call intoapprovalswith its metadata, the tool doesn't run, the retry budget is untouched (retries=0), and approving it on a follow-up run re-runs the validator withctx.tool_call_approved=Trueand executes the tool.tests/test_tools.py::test_args_validator_defers_call—CallDeferredlands incalls; the external result supplied on the follow-up run is recorded without executing the tool.tests/test_tools.py::test_args_validator_deferral_metadata_not_merged_for_already_deferred_kinds— pins the known limitation above: on arequires_approval=Truetool, neither the validator's nor the tool body'sApprovalRequired(metadata=...)reachesDeferredToolRequests.metadata.tests/test_tools.py::test_args_validator_approval_resolved_inline_by_capability— aHandleDeferredToolCallshandler resolves the validator's approval request inline, in the same run.tests/test_streaming.py::test_args_validator_deferral_not_triggered_by_partial_args— fragmented streamed args; one validator call on the complete args,args_valid=Trueon theFunctionToolCallEvent, oneDeferredToolRequestsEvent, no result event.tests/test_capabilities.py::TestToolValidateErrorHooks::test_args_validator_deferral_is_not_a_validate_error— noon_tool_validate_error, noafter_tool_validate, no execute hooks.- Existing
ModelRetry/ToolFailed/ max-retries validator tests are unchanged and still pass.
Verified: uv run pytest (full suite, 6298 passed) and PYRIGHT_PYTHON_IGNORE_WARNINGS=1 uv run pyright pydantic_ai_slim/pydantic_ai/tool_manager.py (clean). Docs examples in this environment are skipped ("extras not installed"), so the new args_validator_conditional_approval.py example was verified by extracting and running it (prints {'amount': 500}, matching the #> line) and by ruff check/ruff format at the docs example settings; the skill example is covered by tests/test_skill_examples.py.
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.
- PR title is fit for the release changelog.