Propagate lifecycle hooks to toolsets returned by `DynamicToolset`
Closes #11266
Why: Resolving a built-in PrefixTools capability dynamically can silently remove every tool contributed by its nested toolset factory. DynamicToolset now prepares factory-returned children for the run and forwards their step hooks while retaining the prepared instance across unchanged factory results and preserving its entered context for cleanup.
New public surface: none.
User-visible behavior: For a factory returning FunctionToolset([greet]), capabilities=[lambda ctx: PrefixTools(Toolset(factory), prefix='ns')] now offers ['ns_greet'] to the model; previously it offered []. The equivalent static capability continues to offer ['ns_greet'].
Verification: Public composition regression, stable factory lifecycle, and replacement/cleanup regressions. Scoped toolset, dynamic capability and durable/MCP checks pass, as do Ruff and focused Pyright.
Existing users: Factory-returned toolsets receive their documented run/step hooks; factory re-evaluation frequency and the behavior of plain toolsets using the default hooks are preserved.
Maintainer setup: Please apply pkg:core and request the fork review with douwebot; these labels require repository permissions.
Technical details, scoped verification and implementation decision
Reproduced behavior
The issue reproduces on released pydantic-ai-slim==2.61.0 and source commit 715651ef7fd3994395e85070ba3d6096c5b211c9, with Python 3.13.15 on Windows. It requires no provider API or durable engine. A TestModel inspecting its function-tool definitions sees:
Before After
static PrefixTools ['ns_greet'] ['ns_greet']
dynamic PrefixTools [] ['ns_greet']
DynamicCapability contributes an outer dynamic toolset. A PrefixTools wrapping a callable Toolset contributes a prefix wrapper around an inner dynamic toolset. Previously the outer dynamic toolset entered that wrapper without forwarding the returned toolset's for_run() or for_run_step(). The inner dynamic toolset therefore remained unresolved. This also skipped initialization and step updates on custom toolsets returned by factories.
Implementation
Only toolsets/_dynamic.py and the dedicated regression module change.
- Keep
_factory_toolset, the raw factory result, separate from_toolset, the active operational child, and_entered_toolset, the owner of the successfully entered context. - For a factory resolved once per run, invoke the child's
for_run(ctx)before the outer context enters it. - For a factory resolved per step, prepare and enter the child when the raw result changes.
- Compare future factory results with the raw result, so a fresh instance returned by
for_run()is retained while the factory keeps returning its original object. - Forward
for_run_step(ctx)to the active child on every step, including when the raw result is unchanged orper_run_step=False. - Detach the old child before exiting or preparing/entering a replacement. Failed preparation or entry leaves no unentered replacement registered for cleanup.
- Use the entered owner for factory-transition and final cleanup even when
for_run_step()returns a different operational toolset. ACombinedToolsetreplacement does not carry the entered container's exit stack. - Clear all three references on exit and retain identity/context ownership when visiting/replacing an initialized dynamic toolset.
The change adds no public parameter, type or configuration option. per_run_step continues to control factory re-evaluation, separately from the active child's per-step lifecycle. Existing custom-toolset responsibility for transitions performed inside its own for_run_step() remains unchanged.
Regression coverage
test_dynamic_capability_initializes_nested_toolset_factory, static and dynamic forms: the public built-in composition exposesns_greetin both cases.test_dynamic_toolset_prepares_stable_factory_result_once, bothper_run_stepsettings: across two runs, each prepared copy receives exactlyfor_run → enter → step:1 → step:2 → exit, without repeated entry of an unchanged factory result.test_dynamic_toolset_prepares_replacements_and_removes_tools: fresh replacements are prepared, the previous prepared instance exits before the next one enters, and a laterNoneremoves the tools.test_dynamic_toolset_preparation_failure_exits_only_active_copy: a preparation failure exits the previously active copy exactly once and never enters or exits the failing replacement.test_dynamic_toolset_exits_entered_combined_after_step_replacement, both completion and factory replacement: a resource-owning sibling inside a combined toolset exits exactly once after another child produces a per-step replacement; the returned operational tools still reach the model.- Existing adjacent tests exercise initial entry failure, replacement entry failure and old-child exit failure.
The six parametrized regression cases cover the affected public composition and lifecycle paths, with the static registration as a control. All six pass with the fix.
Passed scoped checks
The initial scoped checks below passed on 7fda6e58b9380048f5e6d5034b13f116192d8e86. The entered-context cleanup follow-up was then verified and committed as 2657431b774f15a2a570df4ae10f90947d44d987.
pytest tests/test_dynamic_toolset_lifecycle.py tests/test_toolsets.py -q --record-mode=none
120 passed; the two optional MCP cases were subsequently rerun successfully below.
pytest tests/test_capabilities.py -k dynamic_capability -q --record-mode=none
19 passed, 191 deselected.
A five-test follow-up passed with fastmcp==3.4.7 and mcp==1.30.0:
tests/durable_exec/test_durable_operation.py::test_run_resolved_dynamic_toolset_is_entered_once_per_run
tests/durable_exec/test_durable_operation.py::test_per_run_step_dynamic_toolset_still_resolves_per_unit
tests/durable_exec/test_durable_operation.py::test_dynamic_unit_resolves_its_own_toolset_when_the_run_context_cannot_carry_one
tests/test_toolsets.py::test_context_manager
tests/test_toolsets.py::test_context_manager_failed_initialization
5 passed.
The follow-up imported the optional MCP SDK in an ephemeral pytest_sessionstart hook before async fixtures began; the normal blocking-call detector and warning policy remained enabled. The two existing marked stdio tests used the same environment's Python. No project fixture or test-runner configuration changed.
The entered-context regression verifies that the resource-owning sibling receives both enter and exit, at completion and at a factory replacement. Scoped checks on the final commit 2657431b774f15a2a570df4ae10f90947d44d987 passed:
pytest tests/test_dynamic_toolset_lifecycle.py -q --record-mode=none
8 passed.
pytest tests/test_toolsets.py -k 'dynamic or visit_and_replace' -q --record-mode=none
17 passed, 99 deselected.
pytest tests/durable_exec/test_durable_operation.py -k 'dynamic or run_held_toolset' -q --record-mode=none
7 passed, 56 deselected.
The durable check used the same optional-SDK session-start preload described above.
Ruff checking and ruff format --check passed for the two changed files. Focused Pyright on those files reported zero errors and zero warnings. git diff --check passed. A direct Trio smoke of the changed toolset's async with, run preparation and two step updates also passed in both factory modes; this is not a claim of complete Trio agent coverage. Verification was scoped to these affected paths, not the repository-wide suite.
PR decisions
2026-10-26 · Keep factory identity separate from active toolset
- Decision: Track the raw factory result separately and prepare its per-run replacement before entry; forward step hooks even when the raw result is unchanged.
- Why: A
for_runhook can return a fresh instance, so comparing only the prepared child would reinitialize and reenter it every step. - Source: Existing public lifecycle contract.
2026-10-26 · Preserve ownership of the entered child context
- Decision: Keep the entered toolset separately from the per-step operational result and exit the entered owner on factory transitions and final cleanup.
- Why:
CombinedToolsetstep replacement does not retain its exit stack; a public regression confirmed a resource-owning sibling otherwise receives no exit. - Source: Combined toolset step replacement and context cleanup.
Checklist
- No breaking changes in accordance with the version policy.
- Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it. (Not applicable: no compatibility impact identified.)
- PR title is fit for the release changelog.