API Reference¶
Comprehensive API documentation for all classes and methods in ToolRegistry, automatically generated from the source code.
Core Classes¶
Fundamental classes and base components:
- ToolRegistry — Central orchestrator for tool management
- Tool — Individual tool with metadata and execution logic
- Executor — Pluggable execution backends (thread/process)
- Events — Change event types and callback mechanism
- Permissions — Rule-based authorization framework
See Core Classes Overview for architecture diagram.
Integration Modules¶
Framework and protocol compatibility for tool registration:
- OpenAPI — REST API tool generation from OpenAPI specs
- MCP — Model Context Protocol server communication
- LangChain — LangChain BaseTool interoperability
- Native — Python class method registration
See Integration Modules Overview for common patterns.
Tool Wrappers¶
Adapter classes for different tool types:
- BaseToolWrapper — Abstract base class
- MCPToolWrapper — MCP server tool wrapper
- OpenAPIToolWrapper — OpenAPI/REST tool wrapper
- LangChainToolWrapper — LangChain tool wrapper
See Tool Wrappers Overview for execution model.
Helper Classes¶
Supporting utilities:
- Parameter Models & Utilities — Parameter validation, tool name normalization, HTTP client configuration
Type Definitions¶
LLM API format compatibility types:
- Types — Common, OpenAI, Anthropic, and Gemini type definitions
Complete Module Overview¶
toolregistry ¶
ToolRegistry ¶
ToolRegistry(name: str | None = None, *, default_max_result_size: int | None = None, think_augment: bool = False, tool_discovery: bool = False, name_sep: Literal['-', '.'] = '-')
Bases: AdminMixin, ExecutionLoggingMixin, PermissionsMixin, RegistrationMixin, 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
|
None
|
think_augment
|
bool
|
Enable thought-augmented tool calling globally.
When |
False
|
tool_discovery
|
bool
|
Enable tool discovery on initialization.
When |
False
|
name_sep
|
Literal['-', '.']
|
Separator character used when combining namespace and
method name into a tool name (e.g. |
'-'
|
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.
__contains__ ¶
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__ ¶
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__ ¶
Return the JSON representation of the registry for debugging purposes.
Returns:
| Name | Type | Description |
|---|---|---|
str |
JSON string representation of the registry. |
__str__ ¶
Return the JSON representation of the registry as a string.
Returns:
| Name | Type | Description |
|---|---|---|
str |
JSON string representation of the registry. |
apply_metadata_config ¶
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 have |
required |
build_tool_call_messages ¶
build_tool_call_messages(tool_calls: list[Any], tool_responses: dict[str, str | list], 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.
This is a convenience method wrapping :func:build_assistant_message
and :func:build_tool_response. It handles Gemini-specific ID
alignment automatically (position-based remapping).
.. important::
Do **not** reorder ``tool_calls`` between
:meth:`execute_tool_calls` and this method. Gemini format
relies on positional alignment between ``tool_calls`` and
``tool_responses`` because Gemini does not provide tool call
IDs upstream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_calls
|
list[Any]
|
Tool call objects in any supported format. |
required |
tool_responses
|
dict[str, str | list]
|
Mapping of tool call IDs to results,
as returned by :meth: |
required |
api_format
|
API_FORMATS
|
Target API format. Defaults to |
'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_async
async
¶
Close all persistent connections (async).
Closes MCP and OpenAPI integrations that hold persistent connections or HTTP clients.
disable_think_augment ¶
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 and unregister the discovery tool.
enable_think_augment ¶
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 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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_weights
|
dict[str, float] | None
|
Optional per-field BM25F boost weights. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
The |
ToolDiscoveryTool
|
class: |
execute_tool_calls ¶
execute_tool_calls(tool_calls: list[Any], execution_mode: Literal['process', 'thread'] | None = None) -> dict[str, str | list]
Execute tool calls with concurrency using cloudpickle for serialization.
Disabled tools are rejected with an error message 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 |
|---|---|
dict[str, str | list]
|
Dictionary mapping tool call IDs to their results. Values |
dict[str, str | list]
|
are |
dict[str, str | list]
|
multimodal results (e.g. images). |
get_deferred_summaries ¶
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]]
|
|
list[dict[str, str | None]]
|
|
list[dict[str, str | None]]
|
|
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'
|
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
|
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 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:
|
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, } ]
list_all_tools ¶
Deprecated: use list_tools(include_disabled=True) instead.
list_tools ¶
List registered tools.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include_disabled
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List[str]: A list of tool names. |
recover_tool_call_assistant_message ¶
recover_tool_call_assistant_message(tool_calls: list[Any], tool_responses: dict[str, str | list], api_format: API_FORMATS = 'openai-chat') -> list[dict[str, Any]]
Deprecated: use :meth:build_tool_call_messages instead.
set_default_execution_mode ¶
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 ¶
Deprecated: use :meth:set_default_execution_mode instead.
Tool ¶
Bases: BaseModel
Base class representing an executable tool/function.
Provides core functionality for
- Function wrapping and metadata management
- Parameter validation using Pydantic
- Synchronous/asynchronous execution
- JSON schema generation
callable
class-attribute
instance-attribute
¶
The underlying function/method that implements the tool's logic.
This is excluded from serialization to prevent accidental exposure of sensitive implementation details.
description
class-attribute
instance-attribute
¶
Detailed description of the tool's functionality.
Should clearly explain what the tool does, its purpose, and any important usage considerations.
is_async
property
¶
Whether the tool requires async execution.
Backward-compatible proxy to metadata.is_async.
metadata
class-attribute
instance-attribute
¶
Behavioral and classification metadata for this tool.
Contains execution hints (is_async, is_concurrency_safe,
timeout) and classification tags (tags, custom_tags).
method_name
class-attribute
instance-attribute
¶
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
class-attribute
instance-attribute
¶
The name of the tool.
Used as the primary identifier when calling the tool. Must be unique within a tool registry.
namespace
class-attribute
instance-attribute
¶
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
class-attribute
instance-attribute
¶
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
class-attribute
instance-attribute
¶
parameters_model: Any | None = Field(default=None, description='Pydantic Model for tool parameters')
Pydantic model 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
¶
Return the fully-qualified tool name.
If a namespace is set, returns {namespace}-{method_name}.
Otherwise falls back to the name field.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The qualified name of the tool. |
arun
async
¶
Execute tool asynchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Dict[str, Any]
|
Validated input parameters. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
Tool execution result. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If async execution unsupported. |
Exception
|
On execution failure. |
Note
Result size truncation (via max_result_size) is only applied
when tools are executed through
ToolRegistry.execute_tool_calls(). Direct calls to arun()
return raw results without truncation.
.. deprecated::
When an exception is caught, arun() returns an error string.
This behaviour is deprecated — use arun_raw() to get
exceptions directly. In a future version arun() will raise.
arun_raw
async
¶
Execute tool asynchronously, raising on failure.
Unlike arun(), this method does not catch exceptions — they
propagate to the caller, preserving full stack-trace information.
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 |
|---|---|
NotImplementedError
|
If async execution is unsupported. |
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.
describe ¶
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) -> Tool
Factory method to create Tool from callable.
Automatically
- Extracts function metadata
- Generates parameter schema
- 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; |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Tool |
Tool
|
Configured Tool instance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
For unnamed lambda functions. |
get_json_schema ¶
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.
All formats are produced via llm-rosetta converters, which also
apply schema sanitization (stripping unsupported JSON Schema
keywords like $ref, $schema, anyOf, etc.).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_format
|
API_FORMATS
|
Target API format. One of |
'openai-chat'
|
_think_augment
|
bool | None
|
Internal override for toolcall_reason injection.
When |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Provider-specific tool definition dict. |
model_post_init ¶
Inject toolcall_reason property into the tool's parameter schema.
Runs after every Tool (and subclass) construction, regardless
of whether the instance was created via from_function(), or
directly (MCP, OpenAPI, LangChain integrations).
The toolcall_reason field is only added when parameters
already contains a properties mapping.
run ¶
Execute tool synchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Dict[str, Any]
|
Validated input parameters. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
Tool execution result. |
Raises:
| Type | Description |
|---|---|
Exception
|
On execution failure. |
Note
Result size truncation (via max_result_size) is only applied
when tools are executed through
ToolRegistry.execute_tool_calls(). Direct calls to run()
return raw results without truncation.
.. deprecated::
When an exception is caught, run() returns an error string.
This behaviour is deprecated — use run_raw() to get
exceptions directly. In a future version run() will raise.
run_raw ¶
Execute tool synchronously, raising on failure.
Unlike run(), this method does not catch exceptions — they
propagate to the caller, preserving full stack-trace information.
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.
update_namespace ¶
Updates the namespace of a tool.
This method checks if the tool's name already contains a namespace (indicated by the presence of a separator character).
OpenAI requires that function names match the pattern ^[a-zA-Z0-9_-]+$. Some other providers allow dot (.) as separator.
If it does and force is True, the existing namespace is replaced with the provided namespace.
If force is False and an existing namespace is present, no changes are made.
If the tool's name does not contain a namespace, the namespace is prepended as a prefix to the tool's name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
str
|
The new namespace to apply to the tool's name. |
required |
force
|
bool
|
If |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
None |
None
|
This method modifies the |
Example
tool = Tool(name="example_tool")
tool.update_namespace("new_namespace")
tool.name # 'new_namespace-example_tool'
tool = Tool(name="old_namespace.example_tool")
tool.update_namespace("new_namespace", force=False)
tool.name # 'old_namespace-example_tool'
tool = Tool(name="old_namespace.example_tool")
tool.update_namespace("new_namespace", force=True, sep=".")
tool.name # 'new_namespace.example_tool'