跳转至

API 参考

ToolRegistry 中所有类和方法的全面 API 文档,从源代码自动生成。

核心类

基础类和基本组件:

  • ToolRegistry — 工具管理的中央协调器
  • Tool — 包含元数据和执行逻辑的单个工具
  • Executor — 可插拔的执行后端(线程/进程)
  • 出站地址策略 — 拒绝主机非全球可达的 URL
  • Events — 变更事件类型和回调机制
  • Permissions — 基于规则的授权框架

参见 核心类概览 了解架构图。

集成模块

框架和协议兼容性,用于工具注册:

  • OpenAPI — 从 OpenAPI 规范生成 REST API 工具
  • MCP — 模型上下文协议服务器通信
  • LangChain — LangChain BaseTool 互操作性
  • Native — Python 类方法注册

参见 集成模块概览 了解通用模式。

工具包装器

不同工具类型的适配器类:

参见 工具包装器概览 了解执行模型。

辅助类

支持工具:

校验错误

工具在运行前会校验参数。相关异常可以直接从包根导入,调用方无需访问私有模块即可将它们映射到自己的错误格式:

from toolregistry import ErrorDetail, SchemaValidationError, ValidationError

try:
    tool.validate_parameters(arguments)
except ValidationError as exc:
    for detail in exc.errors:          # ErrorDetail(path, expected, actual, message)
        print(detail.path, detail.message)
  • ValidationError / ErrorDetail —— 由 Tool.validate_parameters() 抛出,用于按签名生成的工具对照其参数模型进行校验。
  • SchemaValidationError / SchemaErrorDetail —— 在按原始 JSON Schema 校验数据时抛出,代理工具(MCP / OpenAPI / LangChain)走这条路径。

两者捕获的就是库实际抛出的类;这些名字是再导出,而非包装。

类型定义

LLM API 格式兼容性类型:

  • 类型 — 通用、OpenAI、Anthropic 和 Gemini 类型定义

完整模块概览

toolregistry

ToolRegistry

ToolRegistry(name: str | None = None, *, default_max_result_size: int | None = DEFAULT_MAX_RESULT_SIZE, default_max_result_tokens: int | None = None, persist_large_results: bool = False, result_store: ResultStore | None = None, result_ttl_seconds: float = DEFAULT_RESULT_TTL_SECONDS, result_idle_ttl_seconds: float | None = DEFAULT_RESULT_IDLE_TTL_SECONDS, result_quota_bytes: int = DEFAULT_RESULT_QUOTA_BYTES, result_scope_policy: ResultScopePolicy = DEFAULT_RESULT_SCOPE_POLICY, result_scope_provider: Callable[[], ResultScope | None] | None = None, think_augment: bool = False, tool_discovery: bool = False, name_sep: Literal['-', '.'] = '-', derive_output_schemas: bool = False)

Bases: AdminMixin, ExecutionLoggingMixin, PermissionsMixin, RegistrationMixin, SkillsMixin, EnableDisableMixin, NamespaceMixin, ChangeCallbackMixin

Central registry for managing tools (functions) and their metadata.

This class provides functionality to register, manage, and execute tools, as well as to interface with MCP servers, OpenAPI endpoints, and generate tool schemas.

Attributes:

Name Type Description
name str

The name of the tool registry.

Notes

Private attributes are used internally to manage registered tools and sub-registries. These attributes are not intended for external use.

Initialize an empty ToolRegistry.

This method initializes an empty ToolRegistry with a name and internal structures for storing tools and sub-registries.

Parameters:

Name Type Description Default
name str | None

Name of the tool registry. Defaults to a random "reg_<4-char>" string. For instance, "reg_1a3c".

None
default_max_result_size int | None

Default maximum result size in characters for all tools. Individual tools can override this via ToolMetadata.max_result_size. Defaults to :data:~toolregistry.llm.truncation.DEFAULT_MAX_RESULT_SIZE (64,000 characters, about 16k tokens); pass None to disable the default cap, or 0 to truncate every result to the notice alone.

DEFAULT_MAX_RESULT_SIZE
default_max_result_tokens int | None

Default maximum result size in tokens for all tools, converted to characters with :data:toolregistry.llm.truncation.CHARS_PER_TOKEN (a fixed estimate of 4). Individual tools can override this via ToolMetadata.max_result_tokens. When both limits are set, the smaller effective one wins. None means no limit.

None
persist_large_results bool

Store each truncated full result in a private per-run directory and register a read_result tool that pages through it by opaque id. The truncation header then names an id (res_<32 hex>), never a filesystem path. Defaults to False: nothing is written to disk. Files are created with mode 0600, expire after 24 hours, and are evicted oldest-first beyond a 64 MiB quota.

False
result_store ResultStore | None

A prepared store to use instead of building one from the retention arguments. Supplying a store enables persistence even when persist_large_results is False. The per-store retention of the injected store wins; the result_* keyword arguments below are ignored.

None
result_ttl_seconds float

Hard lifetime of a persisted result, in seconds, measured from creation. Reads never extend it.

DEFAULT_RESULT_TTL_SECONDS
result_idle_ttl_seconds float | None

Sliding lifetime measured from the last successful read. None disables the sliding deadline.

DEFAULT_RESULT_IDLE_TTL_SECONDS
result_quota_bytes int

Total bytes the result directory may hold. Older results are evicted first, but the result being written is retained even when it alone is over quota.

DEFAULT_RESULT_QUOTA_BYTES
result_scope_policy ResultScopePolicy

"optional" (default) accepts unscoped library writes; "required" requires a :class:~toolregistry.llm.truncation.ResultScope; and "session_required" additionally requires a session id. A missing scope under a required policy raises instead of silently writing a readable result.

DEFAULT_RESULT_SCOPE_POLICY
result_scope_provider Callable[[], ResultScope | None] | None

Callable that returns the :class:~toolregistry.llm.truncation.ResultScope to attach to results written by this registry. When None the scope bound with :func:~toolregistry.llm.truncation.use_result_scope is used. Server adapters pass an explicit provider instead of relying on context variables, because executor backends do not carry them across threads or processes.

None
think_augment bool

Enable thought-augmented tool calling globally. When True, a toolcall_reason property is included in every tool's schema so LLMs can articulate their rationale when calling tools. Individual tools can override this via ToolMetadata.think_augment. Defaults to False.

False
tool_discovery bool

Enable tool discovery on initialization. When True, :meth:enable_tool_discovery is called automatically, registering a discover_tools tool that LLMs can use to discover other tools by exact name or natural language query. Defaults to False.

False
name_sep Literal['-', '.']

Separator character used when combining namespace and method name into a tool name (e.g. "calculator-evaluate" with "-" or "calculator.evaluate" with "."). OpenAI requires "-"; some providers allow ".". Defaults to "-".

'-'
derive_output_schemas bool

Derive each registered tool's output schema from its return annotation and store it in ToolMetadata.extra["output_schema"]. An explicit declaration on the tool always wins, and an annotation that cannot be resolved to a complete schema adds nothing. Only callables registered by the registry are derived; a pre-built Tool is registered or overridden as-is. Defaults to False: publishing an outputSchema changes what MCP clients see, so enabling it is a deployment choice.

False
Notes

This class uses private attributes _tools and _sub_registries internally to manage registered tools and sub-registries. These are not intended for external use.

name_sep property writable

name_sep: Literal['-', '.']

Separator used between a namespace and a tool name.

Registration paths use this to derive the key a tool will be stored under, without reaching into the private attribute.

ptc property

ptc: PtcController

PTC (Programmatic Tool Calling) controller.

Use registry.ptc.enable() to register a code_execution tool that lets LLMs write Python code with registered tools callable in the namespace.

Example::

registry.ptc.enable(timeout=30)
registry.ptc.disable()
registry.ptc.enabled           # bool
registry.ptc.last_invocation_id  # str | None

tool_discovery_enabled property

tool_discovery_enabled: bool

Whether tool discovery is enabled.

True once discover_tools and call_deferred are registered, until :meth:disable_tool_discovery removes them again.

tool_discovery_mode property

tool_discovery_mode: Literal['auto', 'on', 'off']

How tool discovery tracks the registry.

"auto" (the default) keeps discovery on exactly while at least one enabled tool is deferred, so a model can always retrieve a tool the schema hides. "on" and "off" are explicit choices that later registrations do not override; :meth:enable_tool_discovery and :meth:disable_tool_discovery set them.

__contains__

__contains__(name: str) -> bool

Check if a tool with the given name is registered.

Parameters:

Name Type Description Default
name str

Name of the tool to check.

required

Returns:

Name Type Description
bool bool

True if tool is registered, False otherwise.

__getitem__

__getitem__(key: str) -> Callable[..., Any] | None

Enable key-value access to retrieve callables.

Parameters:

Name Type Description Default
key str

Name of the function.

required

Returns:

Type Description
Callable[..., Any] | None

Optional[Callable[..., Any]]: The function to call, or None if not found.

__repr__

__repr__()

Return the JSON representation of the registry for debugging purposes.

Returns:

Name Type Description
str

JSON string representation of the registry.

__str__

__str__()

Return the JSON representation of the registry as a string.

Returns:

Name Type Description
str

JSON string representation of the registry.

aexecute_tool_calls async

aexecute_tool_calls(tool_calls: list[Any], execution_mode: Literal['process', 'thread'] | None = None) -> ResultList

Async counterpart to :meth:execute_tool_calls.

Runs concurrency-safe calls concurrently via asyncio.gather over the per-tool async pipeline: inline tools (MCP/OpenAPI and async natives) overlap on the caller's loop, while pool-backed tools run off-loop and are awaited via result_async. If any tool is not concurrency-safe, all calls run sequentially.

Parameters:

Name Type Description Default
tool_calls list[Any]

Tool calls in any supported format.

required
execution_mode Literal['process', 'thread'] | None

Optional backend override.

None

Returns:

Name Type Description
A ResultList

class:ResultList in the same order as tool_calls.

ainvoke async

ainvoke(tool_name: str, kwargs: dict[str, Any], *, invocation_id: str | None = None, execution_mode: Literal['thread', 'process'] | None = None) -> ToolCallResult | ErrorResult

Async counterpart to :meth:invoke.

For inline-resolved tools (the default, including MCP/OpenAPI), awaits tool.arun() directly on the caller's loop — the tool's async transport stays on the running loop without blocking it. For thread/process backends, submits and awaits handle.result_async().

Returns a :class:ToolCallResult on success or an :class:ErrorResult on any failure. Never raises for access-control failures.

Parameters:

Name Type Description Default
tool_name str

Name of the registered tool.

required
kwargs dict[str, Any]

Keyword arguments to pass to the tool.

required
invocation_id str | None

Optional grouping ID; auto-generated (tr_sig_) when None and used as the result id.

None
execution_mode Literal['thread', 'process'] | None

Optional backend override.

None

Returns:

Type Description
ToolCallResult | ErrorResult

ToolCallResult on success, ErrorResult on failure.

apply_metadata_config

apply_metadata_config(overrides: dict[str, Any]) -> None

Apply tool_metadata overrides from a loaded ToolConfig.

Accepts dict[str, ToolMetadataOverride] (as returned by ToolConfig.tool_metadata) or plain dict[str, dict]. Silently skips tool names not present in the registry.

Parameters:

Name Type Description Default
overrides dict[str, Any]

Mapping of exact tool name → metadata override. Each value must provide search_hint (str), defer (bool | None), title (str | None), and the execution hints read_only_hint, destructive_hint, idempotent_hint and open_world_hint (each bool | None) as attributes or dict keys. None leaves the registered value untouched; an explicit False is applied.

required
Note

None here means "skip this field" — the already-registered value is kept. That differs from the config loader, where None means "no override was declared", and from :meth:update_tool_metadata, where title=None clears the field. An explicit False is always applied, never treated as "unset".

build_tool_call_messages

build_tool_call_messages(tool_calls: list[Any], results: list[Any], api_format: API_FORMATS = 'openai-chat') -> list[dict[str, Any]]

Build conversation messages for a tool-calling round-trip.

Combines the assistant message (tool call requests) and the tool result messages into the format required by the next LLM turn.

Parameters:

Name Type Description Default
tool_calls list[Any]

Tool call objects in any supported format (as received from the LLM).

required
results list[Any]

Structured results from :meth:execute_tool_calls.

required
api_format API_FORMATS

Target API format. Defaults to "openai-chat".

'openai-chat'

Returns:

Type Description
list[dict[str, Any]]

Conversation messages ready to extend the message history.

list[dict[str, Any]]

When multimodal content is present, an additional user

list[dict[str, Any]]

message is appended containing the expanded content.

close

close(wait: bool = False) -> None

Close all persistent connections and execution resources (sync).

Closes MCP and OpenAPI integrations, then shuts down the thread and process execution backends. With wait=False (the default) shutdown is non-blocking and work already running or queued is abandoned; with wait=True it drains that work before returning. The backends recreate their pools lazily, so the registry remains usable; calling this repeatedly is safe.

Parameters:

Name Type Description Default
wait bool

Drain in-flight and queued execution before returning.

False

close_async async

close_async(wait: bool = False) -> None

Close all persistent connections and execution resources (async).

Closes MCP and OpenAPI integrations that hold persistent connections or HTTP clients, then shuts down the thread and process execution backends. With wait=False (the default) shutdown is non-blocking and work already running or queued is abandoned; with wait=True it drains that work before returning. The backends recreate their pools lazily, so the registry remains usable; calling this repeatedly is safe.

Parameters:

Name Type Description Default
wait bool

Drain in-flight and queued execution before returning.

False

disable_think_augment

disable_think_augment() -> None

Disable thought-augmented tool calling globally.

When disabled, the toolcall_reason property is stripped from tool schemas produced by :meth:get_schemas, unless a tool explicitly opts in via ToolMetadata.think_augment = True.

disable_tool_discovery

disable_tool_discovery() -> None

Disable tool discovery and unregister the discovery tools.

The mode is pinned to "off", so registering a deferred tool does not bring discovery back. One UNREGISTER change event is emitted per removed tool: transports listen for it to refresh what they advertise (an MCP client receives tools/list_changed).

enable_think_augment

enable_think_augment() -> None

Enable thought-augmented tool calling globally.

When enabled, a toolcall_reason property is included in every tool's schema (via :meth:get_schemas) so that LLMs can articulate their rationale when calling tools. Individual tools can still override this via ToolMetadata.think_augment.

Reference: https://arxiv.org/abs/2601.18282

enable_tool_discovery

enable_tool_discovery(field_weights: dict[str, float] | None = None, min_score_ratio: float | None = None, max_df_ratio: float | None = None) -> ToolDiscoveryTool

Enable tool discovery and register a discovery tool.

Creates a :class:ToolDiscoveryTool, registers its :meth:~ToolDiscoveryTool.discover method as a callable tool named discover_tools, and subscribes to registry change events for automatic index rebuilds.

The discovery tool itself is never deferred (defer=False) so that LLMs always see it in the initial schema.

Discovery is enabled once per registry. A repeated call returns the existing :class:~toolregistry.llm.discovery.ToolDiscoveryTool unchanged; options that differ from its live configuration are reported with a :class:UserWarning. Call :meth:disable_tool_discovery first to reconfigure.

The call also pins :attr:tool_discovery_mode to "on": an operator who asked for discovery keeps it even when the last deferred tool goes away. Use :meth:set_tool_discovery_mode with "auto" to follow the deferred set again.

Parameters:

Name Type Description Default
field_weights dict[str, float] | None

Optional per-field BM25F boost weights.

None
min_score_ratio float | None

Drop fuzzy hits scoring below this fraction of the best hit. None uses :data:~toolregistry.llm.discovery.DEFAULT_MIN_SCORE_RATIO; 0 disables the floor.

None
max_df_ratio float | None

Drop query tokens present in at least this fraction of indexed tools. None uses :data:~toolregistry.llm.discovery.DEFAULT_MAX_DF_RATIO; 0 disables the filter.

None

Returns:

Name Type Description
The ToolDiscoveryTool

class:ToolDiscoveryTool instance.

execute_tool_calls

execute_tool_calls(tool_calls: list[Any], execution_mode: Literal['process', 'thread'] | None = None) -> ResultList

Execute tool calls and return structured results.

Disabled tools are rejected with an :class:ErrorResult instead of being executed. If logging is enabled, execution details are recorded.

Parameters:

Name Type Description Default
tool_calls list[Any]

List of tool calls to be executed in any supported format.

required
execution_mode Literal['process', 'thread'] | None

Execution mode to use; defaults to the Executor's current mode.

None

Returns:

Type Description
ResultList

List of results in the same order as tool_calls. Each

ResultList

element is a :class:ToolCallResult (success) or

ResultList

class:ErrorResult (failure).

get_available_tools

get_available_tools() -> list[str]

Deprecated: use :meth:list_tools instead.

get_deferred_summaries

get_deferred_summaries() -> list[dict[str, str | None]]

Get name and first-sentence description for deferred tools.

Useful for injecting into system prompts so the LLM knows which additional tools are available via discover_tools.

Only enabled tools with ToolMetadata.defer=True are included.

Returns:

Type Description
list[dict[str, str | None]]

List of dicts with keys:

list[dict[str, str | None]]
  • name (str): Tool name.
list[dict[str, str | None]]
  • description (str): First sentence of the tool description.
list[dict[str, str | None]]
  • namespace (str | None): Tool namespace, if any.

get_schemas

get_schemas(tool_name: str | None = None, *, api_format: API_FORMATS = 'openai-chat', tags: set[str | ToolTag] | None = None, exclude_tags: set[str | ToolTag] | None = None, sort: bool = True, include_deferred: bool = True) -> list[dict[str, Any]]

Get tool definitions as JSON Schema dicts for a target API format.

When no specific tool_name is given, only enabled tools are returned. Tools can be filtered by tags and sorted for deterministic ordering.

Parameters:

Name Type Description Default
tool_name str | None

Optional name of specific tool to get schema for. When set, tag filtering and sorting are skipped.

None
api_format API_FORMATS

Target API format. Defaults to "openai-chat".

'openai-chat'
tags set[str | ToolTag] | None

If set, only include tools matching ANY of these tags.

None
exclude_tags set[str | ToolTag] | None

Exclude tools matching ANY of these tags.

None
sort bool

If True (default), sort tools by name for deterministic ordering. Stable sorting improves prompt cache hit rates.

True
include_deferred bool

If False, exclude tools with metadata.defer == True. Defaults to True for backward compatibility. Set to False when tool search is enabled so that deferred tools are only discovered via search.

True

Returns:

Type Description
list[dict[str, Any]]

A list of tool definition dicts in the specified API format.

get_tools_json

get_tools_json(tool_name: str | None = None, *, api_format: API_FORMATS = 'openai-chat', tags: set[str | ToolTag] | None = None, exclude_tags: set[str | ToolTag] | None = None, sort: bool = True, include_deferred: bool = True) -> list[dict[str, Any]]

Deprecated: use :meth:get_schemas instead.

get_tools_status

get_tools_status() -> list[dict[str, Any]]

Get status information for all registered tools.

Returns a list of dictionaries containing status information for each tool, including enable/disable state, metadata summary, and tags.

Returns:

Type Description
list[dict[str, Any]]

list[dict[str, Any]]: List of tool status dictionaries, each containing:

  • name (str): Tool name (with namespace prefix if applicable)
  • enabled (bool): Whether the tool is currently enabled
  • reason (str | None): Reason for disabling, if disabled
  • namespace (str | None): Namespace the tool belongs to
  • tags (list[str]): Sorted union of predefined and custom tags
  • locality (str): "local", "remote", or "any"
  • is_async (bool): Whether the tool requires async execution
  • source (str): Origin of the tool (e.g. "native", "mcp", "openapi", "langchain")
  • source_detail (str): Extra detail about the tool's origin (e.g. transport URI, spec URL, class name)
  • think_augment (bool | None): Think-augmented calling setting
  • defer (bool): Whether the tool is deferred from initial prompt
  • title (str | None): Human-readable display title, if set
  • execution_hints (dict[str, bool]): Resolved boolean execution hints (the *_hint fields), including values derived from tags; unset hints are omitted. title is reported separately and is not part of this mapping.
Example

registry = ToolRegistry() registry.register(my_tool) registry.disable("my_tool", reason="Under maintenance") registry.get_tools_status() [ { "name": "my_tool", "enabled": False, "reason": "Under maintenance", "namespace": None, "tags": [], "locality": "any", "is_async": False, "think_augment": None, "defer": False, "title": None, "execution_hints": {}, } ]

invoke

invoke(tool_name: str, kwargs: dict[str, Any], *, invocation_id: str | None = None, execution_mode: Literal['thread', 'process'] | None = None) -> ToolCallResult | ErrorResult

Execute a single tool and return a structured result.

Canonical single-tool entry point. Runs the full pipeline (permissions, execution via the resolved backend, logging) and returns a :class:ToolCallResult on success or an :class:ErrorResult on any failure — including access-control failures (missing/disabled/denied). Never raises for those conditions, mirroring :meth:execute_tool_calls.

Parameters:

Name Type Description Default
tool_name str

Name of the registered tool.

required
kwargs dict[str, Any]

Keyword arguments to pass to the tool.

required
invocation_id str | None

Optional ID to group related calls. If None, a tr_sig_ ID is auto-generated and used as the result id.

None
execution_mode Literal['thread', 'process'] | None

Optional backend override ("thread"/"process"). Defaults to the tool's natural backend (inline for most single calls).

None

Returns:

Type Description
ToolCallResult | ErrorResult

ToolCallResult on success, ErrorResult on failure.

list_all_tools

list_all_tools() -> list[str]

Deprecated: use list_tools(include_disabled=True) instead.

list_tools

list_tools(include_disabled: bool = False) -> list[str]

List registered tools.

Parameters:

Name Type Description Default
include_disabled bool

If True, include disabled tools in the result. Defaults to False (only enabled tools).

False

Returns:

Type Description
list[str]

List[str]: A list of tool names.

read_result

read_result(id: str, offset: int = 0, limit: int = DEFAULT_READ_RESULT_LIMIT) -> str

Read a slice of a stored, truncated tool result.

Access is checked against the scope this registry resolves for the current caller. In library mode that scope is None and any valid id is readable, which preserves the old behavior. Server adapters bind either a scope provider on the registry or a per-request read_result handler, so one agent cannot read another agent's result.

When invoked through the tool machinery, the registry resolves the caller's scope on the dispatching thread and runs the read on the thread backend, even if a process backend was requested: the result directory is process-local and the registry cannot be pickled.

Parameters:

Name Type Description Default
id str

Opaque result id from a truncation header (res_<32 hex>).

required
offset int

Character offset to start at.

0
limit int

Maximum number of characters to return.

DEFAULT_READ_RESULT_LIMIT

Returns:

Type Description
str

The requested slice of the full result.

Raises:

Type Description
ValueError

If the id is not a valid result id, is unknown, is not owned by the caller's scope, has expired, is corrupt, or offset/limit is not a non-negative integer.

RuntimeError

If result persistence is not enabled.

recover_tool_call_assistant_message

recover_tool_call_assistant_message(tool_calls: list[Any], results: list[Any], api_format: API_FORMATS = 'openai-chat') -> list[dict[str, Any]]

Deprecated: use :meth:build_tool_call_messages instead.

set_default_execution_mode

set_default_execution_mode(mode: Literal['thread', 'process']) -> None

Set the default execution mode for parallel tasks.

This sets the default mode used by :meth:execute_tool_calls when no per-call execution_mode override is provided.

Parameters:

Name Type Description Default
mode Literal['thread', 'process']

The desired execution mode.

required

Raises:

Type Description
ValueError

If an invalid mode is provided.

set_execution_mode

set_execution_mode(mode: Literal['thread', 'process']) -> None

Deprecated: use :meth:set_default_execution_mode instead.

set_tool_discovery_mode

set_tool_discovery_mode(mode: Literal['auto', 'on', 'off']) -> ToolDiscoveryTool | None

Choose how discovery is controlled and apply the choice at once.

Parameters:

Name Type Description Default
mode Literal['auto', 'on', 'off']

"auto" follows the deferred set, "on" keeps discovery enabled, "off" keeps it disabled.

required

Returns:

Name Type Description
The ToolDiscoveryTool | None

class:ToolDiscoveryTool when discovery is on afterwards,

ToolDiscoveryTool | None

otherwise None.

Raises:

Type Description
ValueError

If mode is not "auto", "on" or "off".

Example
registry.set_tool_discovery_mode("auto")

Tool dataclass

Tool(*, name: str, description: str, parameters: dict[str, Any], callable: Callable[..., Any], metadata: ToolMetadata | None = None, parameters_model: Any | None = None, namespace: str | None = None, method_name: str | None = None, is_async: bool | None = None)

Base class representing an executable tool/function.

Provides core functionality for
  • Function wrapping and metadata management
  • Parameter validation
  • Synchronous/asynchronous execution
  • JSON schema generation
Note

Frozen semantics are shallow — field reassignment is prevented but mutable containers (parameters dict, metadata.tags set) can still be modified in place. Mutation should only occur during __init__.

callable instance-attribute

callable: Callable[..., Any]

The tool's callable, always a :class:BaseToolWrapper at runtime.

Use call_sync() / call_async() for sync/async transparent execution.

declared_execution_hints property

declared_execution_hints: dict[str, bool]

Explicitly declared execution hints, excluding tag-derived values.

Convenience proxy to :attr:ToolMetadata.declared_execution_hints; transports should publish this mapping rather than the resolved one.

description instance-attribute

description: str

Detailed description of the tool's functionality.

Should clearly explain what the tool does, its purpose, and any important usage considerations.

execution_hints property

execution_hints: dict[str, bool]

Resolved execution hints from :attr:metadata.

Convenience proxy to metadata.execution_hints; see :attr:ToolMetadata.execution_hints for the tri-state contract and tag-derivation rule. title is not part of this mapping; read :attr:ToolMetadata.title for the display name.

fn property

fn: Callable[..., Any]

Return the underlying unwrapped function.

For native tools (registered via from_function), returns the original Python function. For integration tools (MCP, OpenAPI, LangChain), returns the wrapper itself.

is_async property

is_async: bool

Whether the tool requires async execution.

Backward-compatible proxy to metadata.is_async.

metadata instance-attribute

metadata: ToolMetadata

Behavioral and classification metadata for this tool.

Contains execution hints (is_async, is_concurrency_safe, timeout) and classification tags (tags, custom_tags).

method_name instance-attribute

method_name: str | None

The original method/function name before namespace prefixing.

Preserved so that the base name can be recovered without ambiguity even when the name field contains a namespace prefix joined by - (which normalize_tool_name would otherwise convert to _).

name instance-attribute

name: str

The name of the tool.

Used as the primary identifier when calling the tool. Must be unique within a tool registry.

namespace instance-attribute

namespace: str | None

The namespace this tool belongs to.

Used to group tools logically and avoid name collisions. When set, the tool's name is typically prefixed as {namespace}-{method_name}. This field stores the original namespace string (after normalization) so that downstream code can reliably determine group membership without parsing the name field.

parameters instance-attribute

parameters: dict[str, Any]

Parameter schema defining the tool's expected inputs.

Follows JSON Schema format. Automatically generated from the wrapped function's type hints when using from_function().

parameters_model instance-attribute

parameters_model: Any | None

Type used for parameter validation.

Automatically generated from the wrapped function's type hints when using from_function(). Can be None for tools without parameter validation.

qualified_name property

qualified_name: str

Return the fully-qualified tool name.

name is authoritative: registration and every namespace operation rebuild it from namespace, method_name and the registry separator (see :meth:requalify). The property therefore simply exposes name.

Returns:

Name Type Description
str str

The qualified name of the tool.

__getstate__

__getstate__() -> dict[str, Any]

Avoid pickling the dynamically created TypedDict on Python 3.11+.

__setstate__

__setstate__(state: dict[str, Any]) -> None

Restore native parameter validation after deserialization.

Regeneration can fail for annotations that no longer resolve in the loading process (local classes, optional dependencies). The tool is then restored without parameter validation and a UserWarning says so, matching Tool.from_function. With warnings escalated to errors (python -W error) that warning raises and the tool still fails to load.

arun async

arun(parameters: dict[str, Any]) -> Any

Execute tool asynchronously.

Delegates to callable.call_async() which handles sync/async callable transparency. Exceptions propagate directly.

Parameters:

Name Type Description Default
parameters dict[str, Any]

Input parameters for the tool.

required

Returns:

Type Description
Any

The tool execution result.

Raises:

Type Description
Exception

Any exception raised during validation or execution.

Note

Result size truncation (via max_result_size) is only applied when tools are executed through ToolRegistry.execute_tool_calls(). Direct calls return raw results without truncation.

arun_raw async

arun_raw(parameters: dict[str, Any]) -> Any

Deprecated alias for arun().

.. deprecated:: 0.12.0 Use arun() instead. arun_raw will be removed in a future version.

describe

describe(api_format: API_FORMATS = 'openai-chat') -> dict[str, Any]

Deprecated: use :meth:get_schema instead.

from_function classmethod

from_function(func: Callable[..., Any], name: str | None = None, description: str | None = None, namespace: str | None = None, method_name: str | None = None, metadata: ToolMetadata | None = None, sep: NameSeparator = '-', *, localns: Mapping[str, Any] | None = None, derive_output_schema: bool = False) -> Tool

Factory method to create Tool from callable.

Automatically
  • Extracts function metadata
  • Generates parameter schema
  • Optionally derives the output schema from the return annotation
  • Handles async/sync detection

Parameters:

Name Type Description Default
func Callable[..., Any]

Function to convert to tool.

required
name str | None

Override tool name (defaults to function name).

None
description str | None

Override description (defaults to docstring).

None
namespace str | None

Namespace the tool belongs to.

None
method_name str | None

Original method name of the tool.

None
metadata ToolMetadata | None

Optional ToolMetadata; is_async is always auto-detected and will override the value in metadata.

None
sep NameSeparator

Separator between namespace and the tool name. Pass the registry's name_sep so the resulting name matches the registry key.

'-'
localns Mapping[str, Any] | None

Names visible only to the function that defined the annotations, typically locals() from that function. An annotation that names a function-local type or Annotated/Field pair cannot be resolved through the function's globals; passing the namespace lets it resolve. None (default) resolves through the globals alone, and an annotation that still cannot resolve keeps the existing fallback warning and metadata.unresolved_parameters entry.

None
derive_output_schema bool

Derive a JSON Schema from the return annotation and store it in metadata.extra["output_schema"] when the tool does not already declare one. An annotation that cannot be resolved to a complete schema adds nothing, so it never publishes an empty contract. Defaults to False; the registry switch derive_output_schemas forwards its value here.

False

Returns:

Name Type Description
Tool Tool

Configured Tool instance.

Raises:

Type Description
ValueError

For unnamed lambda functions.

get_json_schema

get_json_schema(api_format: API_FORMATS = 'openai-chat') -> dict[str, Any]

Deprecated: use :meth:get_schema instead.

get_schema

get_schema(api_format: API_FORMATS = 'openai-chat', *, _think_augment: bool | None = None) -> dict[str, Any]

Generate schema representation of tool for a target API format.

Parameters are already flattened and sanitized at construction (see :meth:_normalize_parameters). This method wraps them in the target provider format and optionally injects a toolcall_reason property for think-augmented calling.

Parameters:

Name Type Description Default
api_format API_FORMATS

Target API format. One of "openai-chat", "openai-responses", "anthropic", "gemini".

'openai-chat'
_think_augment bool | None

Override for toolcall_reason injection. True → include, False/None → exclude. When None, falls back to self.metadata.think_augment. Used by :meth:ToolRegistry.get_schemas to pass the resolved effective value.

None

Returns:

Type Description
dict[str, Any]

Provider-specific tool definition dict.

model_dump

model_dump() -> dict[str, Any]

Backward-compatible alias for :meth:to_dict.

requalify

requalify(namespace: str | None, sep: NameSeparator = '-') -> _ToolT

Return a copy whose name is rebuilt from namespace and method_name.

name is derived, never parsed: the unqualified name comes from :attr:method_name (falling back to the current name for tools built before that field existed), then it is recombined with namespace using sep. Passing namespace=None drops the namespace and keeps only the method name.

This is the primitive behind spinoff, reduce_namespace and separator conversion during merge.

Parameters:

Name Type Description Default
namespace str | None

Namespace to apply, or None to flatten.

required
sep NameSeparator

Separator between namespace and method name.

'-'

Returns:

Type Description
_ToolT

A copy with consistent name, namespace and method_name.

run

run(parameters: dict[str, Any]) -> Any

Execute tool synchronously.

Delegates to callable.call_sync() which handles sync/async callable transparency. Exceptions propagate directly.

Parameters:

Name Type Description Default
parameters dict[str, Any]

Input parameters for the tool.

required

Returns:

Type Description
Any

The tool execution result.

Raises:

Type Description
Exception

Any exception raised during validation or execution.

Note

Result size truncation (via max_result_size) is only applied when tools are executed through ToolRegistry.execute_tool_calls(). Direct calls return raw results without truncation.

run_raw

run_raw(parameters: dict[str, Any]) -> Any

Deprecated alias for run().

.. deprecated:: 0.12.0 Use run() instead. run_raw will be removed in a future version.

to_dict

to_dict() -> dict[str, Any]

Serialize to dict, excluding non-serializable fields.

update_namespace

update_namespace(namespace: str | None, force: bool = False, sep: NameSeparator = '-') -> _ToolT

Return a copy of the tool with an updated namespace.

Names are always derived from namespace, method_name and sep; the tool is never renamed by parsing its current name. OpenAI requires function names to match ^[a-zA-Z0-9_-]+$; some other providers allow dot (.) as separator.

If a namespace prefix already exists and force is True, the existing namespace is replaced. If force is False, a tool that is already qualified is returned unchanged (both name and namespace are preserved). A name containing either - or . counts as already qualified; registration normalizes separators away, so this heuristic only affects hand-built Tool instances. If no namespace exists, the new namespace is applied.

Parameters:

Name Type Description Default
namespace str | None

The new namespace to apply to the tool's name.

required
force bool

If True, forces the replacement of an existing namespace. Defaults to False.

False
sep NameSeparator

Separator character between namespace and method name.

'-'

Returns:

Type Description
_ToolT

A new Tool instance with the updated namespace. Returns

_ToolT

self unchanged when namespace is falsy or when force is

_ToolT

False and the tool is already qualified.

Example
tool = Tool(name="example_tool", ...)
tool = tool.update_namespace("new_namespace")
tool.name  # 'new_namespace-example_tool'

tool = Tool(name="old_namespace-example_tool", ...)
tool = tool.update_namespace("new_namespace", force=False)
tool.name  # 'old_namespace-example_tool'

tool = Tool(name="old_namespace.example_tool", ...)
tool = tool.update_namespace("new_namespace", force=True, sep=".")
tool.name  # 'new_namespace.example_tool'

validate_parameters

validate_parameters(parameters: dict[str, Any]) -> dict[str, Any]

Validate parameters against tool schema.

Parameters:

Name Type Description Default
parameters dict[str, Any]

Raw input parameters.

required

Returns:

Type Description
dict[str, Any]

Validated and normalized parameters.

with_parameters

with_parameters(parameters: dict[str, Any], *, parameters_model: Any | None = None) -> _ToolT

Return a copy with a new parameter schema and a recomputed hash.

dataclasses.replace(tool, parameters=...) reuses the existing metadata, so the fingerprint would keep describing the old schema. This is the supported replacement path.

The new copy validates its arguments only when a parameters_model is supplied. Without one, validate_parameters() is a pass-through: it neither checks types nor required nor unknown keys, so payloads that violate the published schema are accepted. Dropping the old model is still the safe default, because it describes the old schema.

Parameters:

Name Type Description Default
parameters dict[str, Any]

New JSON Schema, normally {"type": "object", "properties": {...}}.

required
parameters_model Any | None

Validation type for the new parameters. The default None drops native validation, because the old model describes the old schema. Pass self.parameters_model when the new schema is equivalent.

None

Returns:

Type Description
_ToolT

A copy of the tool with the new schema and its hash.

with_refreshed_at

with_refreshed_at(timestamp: str) -> _ToolT

Return a copy with last_refreshed_at updated.