Support requesting approval or deferring a call from a tool's `args_validator`

Merged
DO
4mo ago
+465-15

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, raise ApprovalRequired(...) instead of marking the whole tool requires_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_args catches CallDeferred/ApprovalRequired from args_validator_func and re-raises it wrapped in a private _ValidationDeferral that also carries the schema-validated args (so they aren't lost as the exception passes the hook boundary). It never escapes ToolManager.
  • validate_tool_call unwraps it into ValidatedToolCall(args_valid=True, validated_args=..., deferral=exc) — a new field.
  • execute_tool_call re-raises validated.deferral instead 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

  1. args_valid is True. Schema validation passed and the validator made a deliberate control-flow choice, so this is not a validation failure: FunctionToolCallEvent.args_valid is True and validated_args carries the schema-validated dict. This matches what a requires_approval=True tool already reports when it's collected as deferred.
  2. The retry budget is untouched, and failed_tools isn't marked — a deferral isn't a failure. Pinned by giving the tool retries=0 in the tests: if the deferral were treated as a validation failure, _check_max_retries would raise UnexpectedModelBehavior immediately instead of deferring.
  3. on_tool_validate_error does not fire. _run_validate_hooks only catches (ValidationError, ModelRetry), so the deferral already propagated past it; the wrap_tool_validate handler chain in CombinedCapability passes it through untouched too. Both are now pinned by a test, and AbstractCapability.on_tool_validate_error's docstring says so explicitly (mirroring what on_tool_execute_error already documents). after_tool_validate doesn't run either, mirroring after_tool_execute on the execution side.
  4. Partial/streaming validation needs no change, and the premise that it did turned out not to hold. _validate_tool_args threads an allow_partial flag, but for function tools its only caller (validate_tool_call) hardcodes allow_partial=False; output tools take a different path (validate_output_tool_call → processor.hook_validate) and never have an args_validator_func at all (OutputToolset.get_tools sets only the schema args_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, with ctx.partial_output False, and exactly one deferral reaches the batch. I deliberately did not change the partial-validation code paths.
  5. SkipToolExecution is deliberately not honoured from a validator. It's documented as a hook signal for before_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 for usage.tool_calls accounting and succeeded_tools that 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 a requires_approval=True tool 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_func is invoked in exactly one place, ToolManager._validate_tool_args (tool_manager.py), reached only via validate_tool_call, whose only callers are the graph's _tool_execution.py:458, :480 and :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_call raises 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 shares wrap_tool_call_result/unwrap_tool_call_result (durable_exec/_toolset.py:163, :179) for execution-stage ApprovalRequired/CallDeferred.
  • The workflow-side tool object keeps the real validator for static function toolsets: DurableFunctionToolset overrides only call_tool (durable_exec/_toolset.py:333-363) and inherits the wrapper's pass-through get_tools, so args_validator_func is 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_tools hands the workflow a placeholder ToolsetTool with args_validator=TOOL_SCHEMA_VALIDATOR and no args_validator_func (durable_exec/_toolset.py:411-423), and call_dynamic_tool re-validates only the schema inside the durable unit before calling the tool (durable_exec/_toolset.py:100-101, Temporal's variant at temporal/_toolset.py:148-149). So a custom args_validator on a dynamic toolset's tool is skipped under durable execution today — for ModelRetry exactly 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's ApprovalRequired defers the call into approvals with 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 with ctx.tool_call_approved=True and executes the tool.
  • tests/test_tools.py::test_args_validator_defers_call — CallDeferred lands in calls; 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 a requires_approval=True tool, neither the validator's nor the tool body's ApprovalRequired(metadata=...) reaches DeferredToolRequests.metadata.
  • tests/test_tools.py::test_args_validator_approval_resolved_inline_by_capability — a HandleDeferredToolCalls handler 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=True on the FunctionToolCallEvent, one DeferredToolRequestsEvent, no result event.
  • tests/test_capabilities.py::TestToolValidateErrorHooks::test_args_validator_deferral_is_not_a_validate_error — no on_tool_validate_error, no after_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.