Let any module define a `ToolKind` with typed tool parts, and keep unknown kinds loadable

Merged
DO
1mo ago
+3259-472

tool_kind says what a tool is independent of its name, and its typed parts (ToolSearchCallPart, LoadCapabilityReturnPart, ...) let code recognize a tool with isinstance. Until now only core could add a kind: ToolPartKind was a closed Literal. A stored part whose kind the process didn't know also failed validation, so a whole history became unloadable.

This is step 2 of the plan on #9410: harness's FileSystem will register kinds for its tools, so capabilities can recognize read_file without matching its name. The design follows capability events.

Defining a kind. A ToolKind (new, exported from pydantic_ai and pydantic_ai.messages) is the one place a tool's typed identity is declared: its namespace, name, and optionally the shapes of its arguments and result. Typed parts register for it with the kind class argument, on a base parameterized with the kind's shape:

class LookupArgs(TypedDict):
    sku: str


class LookupResult(TypedDict):
    in_stock: bool


lookup = ToolKind('inventory', 'lookup', args=LookupArgs, content=LookupResult)


class LookupCallPart(ToolCallPart[LookupArgs], kind=lookup): ...         # typed_args: LookupArgs | None
class LookupReturnPart(ToolReturnPart[LookupResult], kind=lookup): ...  # typed_content: LookupResult | None


@agent.tool_plain(tool_kind=lookup)
def check_stock(args: LookupArgs) -> LookupResult: ...  # the model still sees a `sku` parameter
  • The kind's id is 'inventory.lookup'. A namespace is required, so kinds from different packages can't collide. Ids are stored in every history, so the scheme can't change later. Defining the same id again with different shapes raises UserError; the same shapes (a re-run module, Temporal's sandbox) are fine.
  • ToolCallPart, ToolReturnPart, NativeToolCallPart and NativeToolReturnPart (and their bases) are now generic in the shape of typed_args / typed_content, with an Any default, so bare classes are unchanged. The type parameter is covariant, so a typed part stays assignable to ToolCallPart.
  • __init_subclass__(kind: ToolKind[ArgsT, Any]) is typed against the specialized base, so pyright rejects class X(ToolCallPart[Other], kind=lookup). Defining such a class also raises UserError, through __orig_bases__.
  • The class needs no @dataclass decorator (one on top is harmless). Its tool_kind default is injected, as with capability events' kind.
  • part.typed_args is the arguments validated against the kind's args (a cached TypeAdapter), or None while they stream in or if they don't fit. typed_content does the same for return parts, and is None for a non-success outcome. args / content keep their base types. On a base part (or a kind without that shape), typed_args is the arguments dict and typed_content the content.
  • A typed subclass may only add properties. Adding a field raises UserError when the class is defined.
  • Redefinitions follow the event families:
    • The same class defined again replaces its registration.
    • Two different classes claiming one kind for the same base raise UserError.
    • While the replay-isolation guard is active (Temporal's workflow sandbox), the host's class and kind stay registered.
  • Core's 'tool-search' and 'capability-load' are ToolKinds too, and stay un-namespaced. Their parts get typed_args / typed_content from the kind instead of hand-written parsers. Their existing static field types and accessors are unchanged.

Declaring and checking a tool's kind.

  • tool_kind takes the ToolKind or its id (the ToolKindLike alias in pydantic_ai.messages). It is accepted by:

    • Tool;
    • @agent.tool / @agent.tool_plain;
    • FunctionToolset.tool / tool_plain / add_function;
    • Capability.tool / tool_plain;
    • ToolDefinition, where replace(tool_def, tool_kind=lookup) works in prepare. ToolDefinition.tool_kind always reads back as the id.
  • A tool function can take the kind's args shape as its one parameter (the model sees its fields as the tool's parameters, as for any single model-like parameter), or the fields as separate parameters.

  • Given a ToolKind, the decorators' overloads (KindedToolDecorator / KindedToolPlainDecorator in pydantic_ai.tools) make type checkers check the function's return type against the kind's content (also through ToolReturn[...] and awaitables). A single parameter of the wrong shape can't be told apart statically from the separate-parameters form, so it's caught when tools are collected; tests/typed_tool_kinds.py pins both.

  • Core's search_tools and load_capability, and CodeMode's run_code, declare their kinds.

  • When a run collects its tools, it raises UserError in three cases:

    • A kind that isn't defined. A stored ToolDefinition with one still loads.
    • A tool whose parameters JSON schema doesn't fit the kind's args.
    • A tool whose return schema doesn't fit the kind's content. A return type that can't be compared field by field (a union, say) is accepted.

    Every field the shape requires must be a required field of the tool's, and where both give a field a JSON type, the types must overlap. This is a sanity check, not JSON Schema subsumption, and is cached per (shape, schema).

  • ToolManager.validate_tool_call / handle_call fill in a call's tool_kind from its tool's definition and promote it before any hook runs, so a call a dispatcher builds itself (like CodeMode's sandboxed and speculative calls) reaches validation and execution hooks and deferred-call handlers as the same typed part a direct call does.

Promotion is the same however a message is built.

  • ModelRequest / ModelResponse promote every base tool part whose kind is registered when they are built:

    • by a model;
    • by loading a stored history;
    • by hand.

    That includes core's kinds, which previously were only promoted on load.

  • Already-typed parts pass through untouched.

  • A parts list is updated in place.

  • The check is one C-level isdisjoint(map(type, parts)) pass shared with the existing SpeechPart speaker check. A message with no speech or base tool part is never looped over in Python.

  • Promotion keeps args exactly as the model sent them, rather than replacing them with validated copies that drop unknown keys.

History survives a kind going away.

  • A part whose kind isn't registered in this process loads as a plain ToolCallPart / ToolReturnPart that keeps its tool_kind. That happens when the defining module isn't imported, or was removed. It round-trips, and is promoted again wherever the kind is registered.
  • Because a typed subclass adds no fields, falling back to the base part never loses data.
  • When data doesn't fit a kind's shape:
    • A core kind is stripped, as its union entry would otherwise fail to reload. This now also happens on direct construction.
    • Any other kind keeps its tool_kind on the base part.

Non-success returns are never promoted. A failed / denied / interrupted return's content is an error, not the typed result. Today such a return from search_tools failed narrowing and lost its tool_kind. Now it stays a base ToolReturnPart that keeps it, both in narrowing and in the deserialization discriminator. This also covers #8094's outcome='retried' returns.

First registered harness kind: CodeMode's run_code.

  • Harness's CodeMode defines the 'code_mode.run_code' kind with RunCodeCallPart(ToolCallPart[RunCodeArgs], kind=...) (plus a code accessor), exported from pydantic_ai_harness.code_mode, and declares it on the run_code tool.
  • A capability's wrap_tool_execute can now recognize run_code with isinstance(call, RunCodeCallPart) instead of matching its name.
  • Tools with a non-core kind can now be called from inside the sandbox. Their nested call and return parts recorded in run_code's metadata carry the kind too.
  • There is no typed return part: run_code's content has no stable shape.
  • The tool schema sent to the model is unchanged.
  • Histories recorded before this have plain run_code parts, which still load.

Performance. Measured locally on Python 3.14 with the CodSpeed walltime benchmark:

BenchmarkBefore this pushAfter
test_agent_run_with_synthetic_history[5000-fragments]~285 ms~130 ms
test_agent_run_with_synthetic_history[1000-fragments]14.8 ms8.7 ms

The speech check moved from a Python loop to the C-level pass. Building a message that does contain a base tool part costs about 0.7 µs more for 21 parts. Loading a 2,000-message history with a tool part in every message goes from 8.4 ms to 9.0 ms.

Docs:

  • A "Typed Tool Parts" section in docs/tools-advanced.md, with a runnable example.
  • The harness code-mode page, its README, and the core and harness skills.

[!WARNING]
Compatibility impact:

  • ToolPartKind is now str rather than Literal['tool-search', 'capability-load'].
  • ToolDefinition(tool_kind=...) with an undefined kind now raises UserError when a run collects its tools. Previously the Literal type only rejected it under a type checker.
  • A run now also raises UserError for a tool whose parameters or return type don't fit its kind's declared shapes. Core's own tools fit.
  • pydantic_ai.tools.ToolKind (the ToolDefinition.kind literal) is renamed to ToolDefinitionKind, so the new ToolKind class can take the name. pydantic_ai.tools.ToolKind keeps working with a PydanticAIDeprecationWarning until v3; it was never exported from pydantic_ai.
  • ToolCallPart, ToolReturnPart, NativeToolCallPart, NativeToolReturnPart and their bases are now generic, with an Any default, so existing annotations are unchanged.
  • A search_tools / load_capability return with a non-success outcome now keeps its tool_kind instead of having it stripped.
  • Loading a part with an unknown tool_kind now succeeds instead of raising ValidationError.
  • Building a ModelResponse / ModelRequest by hand with a core-kind part now promotes it to its typed subclass. For example, ToolCallPart(..., tool_kind='tool-search') becomes ToolSearchCallPart. If its data doesn't fit, its tool_kind is stripped, as loading it would.
  • ToolSearchCallPart.typed_args / LoadCapabilityCallPart.typed_args now validate. They return None for arguments that don't fit, and a validated copy otherwise, where previously they returned any parsed dict.
  • ToolDefinition(tool_kind=...) (and replace()) also accepts a ToolKind. A new ToolDefinition.__post_init__ normalizes it to the id. The field stays a plain ToolPartKind | None; type checkers see the wider constructor type through a TYPE_CHECKING-only descriptor declaration.

Why this can ship in a minor release:

  • Most of these only widen what is accepted, or keep information that was dropped.
  • The new errors only concern kinds, which core never sets wrongly.
  • Promotion on construction only applies to parts that explicitly claim a core kind. It gives them the subclass that loading the same message already gives.

Migration: Import ToolDefinitionKind instead of pydantic_ai.tools.ToolKind. Nothing else: code comparing tool_kind to a string still works; prefer isinstance on the typed parts.

Checklist

  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver.
  • PR title is fit for the release changelog.

🤖 Generated with Claude Code