ToolRegistry¶
The central registry class that manages tool registration, execution, and metadata across the ToolRegistry ecosystem.
Overview¶
ToolRegistry serves as the core orchestrator for tool management in the ToolRegistry library. It provides a unified interface for registering, discovering, and executing tools from various sources including native Python functions, OpenAPI specifications, MCP servers, LangChain tools, and more.
Key Features¶
- Unified Tool Management: Central registry for all types of tools
- Async/Sync Support: Full compatibility with both synchronous and asynchronous execution
- Namespace Organization: Support for organizing tools under namespaces
- Multi-Source Integration: Seamless integration with various tool sources
- Metadata Preservation: Maintains tool descriptions, parameters, and execution metadata
- Flexible Execution: Multiple execution modes and concurrency options
- Change Callbacks: Subscribe to tool state changes via
on_change()/remove_on_change() - Post-Registration Hooks: Run custom logic after each tool is registered via
add_post_register_hook(), with optional auto-disable support - Tag-Based Bulk Disable: Disable multiple tools at once by their
ToolTagvalues viadisable_by_tags()
Architecture¶
The ToolRegistry follows a registry pattern with the following key responsibilities:
Core Responsibilities¶
- Tool Registration: Accept and register tools from various sources
- Tool Discovery: Provide mechanisms to discover available tools
- Tool Execution: Execute tools with proper parameter validation and error handling
- Metadata Management: Maintain and provide access to tool metadata
- Namespace Support: Organize tools under logical namespaces
Registration Methods¶
- Unified Registration:
register()/register_async()for all tool sources with auto-detection and explicitsource=hints - Class Integration:
register(Cls, source="class")for Python class method registration. By default, traverses the MRO (Method Resolution Order) to include inherited methods from parent classes. Passtraverse_mro=Falseto register only directly defined methods. - OpenAPI Integration:
register(client, source="openapi", openapi_spec=spec)for OpenAPI specifications - MCP Integration:
register(transport, source="mcp")for Model Context Protocol servers - LangChain Integration:
register(tool, source="langchain")for LangChain tools
Execution Models¶
invoke(tool_name, kwargs): Single-tool execution with full pipeline (permissions, logging, invocation tracking). Used by PTC for IPC callbacks.execute_tool_calls(tool_calls): Batch execution with concurrency via Thread/Process backends. Used for LLM tool_use responses.registry.ptc.enable(): Registers aprogrammatic_tool_calltool for Programmatic Tool Calling. LLMs can write Python code that orchestrates multiple tool calls.
Invocation Tracking¶
All tool executions are logged with an invocation_id prefix:
tr_sig_— singleinvoke()callstr_bat_— batchexecute_tool_calls()callstr_ptc_— PTC code execution tool calls
Query with log.get_entries(invocation_id="tr_ptc_...").
API Reference¶
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
|
DEFAULT_MAX_RESULT_SIZE
|
default_max_result_tokens
|
int | None
|
Default maximum result size in tokens
for all tools, converted to characters with
:data: |
None
|
persist_large_results
|
bool
|
Store each truncated full result in a
private per-run directory and register a |
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 |
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. |
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
|
|
DEFAULT_RESULT_SCOPE_POLICY
|
result_scope_provider
|
Callable[[], ResultScope | None] | None
|
Callable that returns the
:class: |
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. |
'-'
|
derive_output_schemas
|
bool
|
Derive each registered tool's output schema
from its return annotation and store it in
|
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
¶
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 (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
¶
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
¶
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__ ¶
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. |
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: |
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
( |
None
|
execution_mode
|
Literal['thread', 'process'] | None
|
Optional backend override. |
None
|
Returns:
| Type | Description |
|---|---|
ToolCallResult | ErrorResult
|
|
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 provide |
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: |
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 ¶
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 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 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 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 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
|
max_df_ratio
|
float | None
|
Drop query tokens present in at least this fraction
of indexed tools. |
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) -> 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: |
ResultList
|
class: |
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, "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
|
execution_mode
|
Literal['thread', 'process'] | None
|
Optional backend override
( |
None
|
Returns:
| Type | Description |
|---|---|
ToolCallResult | ErrorResult
|
|
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. |
read_result ¶
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 ( |
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 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.
set_tool_discovery_mode ¶
Choose how discovery is controlled and apply the choice at once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
Literal['auto', 'on', 'off']
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
The |
ToolDiscoveryTool | None
|
class: |
ToolDiscoveryTool | None
|
otherwise |
Raises:
| Type | Description |
|---|---|
ValueError
|
If mode is not |
Usage Examples¶
Basic Tool Registration¶
from toolregistry import ToolRegistry
registry = ToolRegistry()
# Register a simple function
def add_numbers(a: int, b: int) -> int:
return a + b
registry.register(add_numbers)
Class Integration¶
from toolregistry import ToolRegistry
registry = ToolRegistry()
class Calculator:
@staticmethod
def multiply(a: int, b: int) -> int:
return a * b
def divide(self, a: int, b: int) -> float:
return a / b
# Register all methods from the class
registry.register(Calculator, source="class")
Class Integration with MRO Traversal¶
from toolregistry import ToolRegistry
class BaseCalculator:
@staticmethod
def add(a: int, b: int) -> int:
return a + b
class AdvancedCalculator(BaseCalculator):
@staticmethod
def multiply(a: int, b: int) -> int:
return a * b
registry = ToolRegistry()
# Default behavior (traverse_mro=True): includes inherited methods from BaseCalculator
registry.register(AdvancedCalculator, source="class")
print(registry.list_tools())
# Output: ['advanced_calculator-add', 'advanced_calculator-multiply']
# With traverse_mro=False: only methods defined directly on AdvancedCalculator
registry2 = ToolRegistry()
registry2.register(AdvancedCalculator, source="class", traverse_mro=False)
print(registry2.list_tools())
# Output: ['advanced_calculator-multiply']
Namespace Organization¶
from toolregistry import ToolRegistry
registry = ToolRegistry()
# Register with custom namespace
registry.register(my_function, namespace="math_utils")
# Access tools with namespace — names carry the prefix
available_tools = [
name for name in registry.list_tools() if name.startswith("math_utils-")
]
Change Callbacks¶
from toolregistry import ToolRegistry, ChangeEvent, ChangeEventType
registry = ToolRegistry()
def my_callback(event: ChangeEvent) -> None:
"""Handle tool registry changes."""
print(f"[{event.event_type.value}] {event.tool_name}")
if event.reason:
print(f" Reason: {event.reason}")
# Register the callback
registry.on_change(my_callback)
# Changes will trigger the callback
def add(a: int, b: int) -> int:
return a + b
registry.register(add) # Triggers: [register] add
registry.disable("add", reason="Maintenance") # Triggers: [disable] add
registry.enable("add") # Triggers: [enable] add
# Remove callback when no longer needed
registry.remove_on_change(my_callback)
Observability API¶
from toolregistry import ToolRegistry
registry = ToolRegistry()
def add(a: int, b: int) -> int:
return a + b
def subtract(a: int, b: int) -> int:
return a - b
registry.register(add)
registry.register(subtract)
# Disable a tool with a reason
registry.disable("subtract", reason="Under maintenance")
# Get status of all tools
status = registry.get_tools_status()
print(status)
# Output:
# [
# {"name": "add", "enabled": True, "reason": None, "namespace": None},
# {"name": "subtract", "enabled": False, "reason": "Under maintenance", "namespace": None}
# ]
# Filter to find disabled tools
disabled_tools = [s for s in status if not s["enabled"]]
print(disabled_tools)
# Output: [{"name": "subtract", "enabled": False, "reason": "Under maintenance", "namespace": None}]
Tag-Based Bulk Disable¶
from toolregistry import Tool, ToolRegistry, ToolMetadata, ToolTag
registry = ToolRegistry()
def read_file(path: str) -> str:
"""Read a file from disk."""
...
def delete_file(path: str) -> None:
"""Delete a file from disk."""
...
def send_email(to: str, body: str) -> None:
"""Send an email."""
...
registry.register(
Tool.from_function(
read_file,
metadata=ToolMetadata(tags={ToolTag.FILE_SYSTEM, ToolTag.READ_ONLY}),
)
)
registry.register(
Tool.from_function(
delete_file,
metadata=ToolMetadata(tags={ToolTag.FILE_SYSTEM, ToolTag.DESTRUCTIVE}),
)
)
registry.register(
Tool.from_function(
send_email,
metadata=ToolMetadata(tags={ToolTag.NETWORK}),
)
)
# match="any" (default): disable tools that have AT LEAST ONE of the given tags
disabled = registry.disable_by_tags(
{ToolTag.DESTRUCTIVE, ToolTag.NETWORK},
match="any",
reason="Restricted in read-only mode",
)
print(disabled) # ['delete_file', 'send_email']
# match="all": disable only tools that carry EVERY specified tag
registry2 = ToolRegistry()
registry2.register(
Tool.from_function(
read_file,
metadata=ToolMetadata(tags={ToolTag.FILE_SYSTEM, ToolTag.READ_ONLY}),
)
)
registry2.register(
Tool.from_function(
delete_file,
metadata=ToolMetadata(tags={ToolTag.FILE_SYSTEM, ToolTag.DESTRUCTIVE}),
)
)
disabled2 = registry2.disable_by_tags(
{ToolTag.FILE_SYSTEM, ToolTag.DESTRUCTIVE},
match="all",
reason="No destructive filesystem ops allowed",
)
print(disabled2) # ['delete_file']
Post-Registration Hook¶
from toolregistry import PostRegisterHook, Tool, ToolRegistry, ToolMetadata, ToolTag
registry = ToolRegistry()
# Hook: auto-disable any privileged tool at registration time
def deny_privileged(tool_name: str, tool, registry) -> str | None:
tags = tool.metadata.tags if tool.metadata else set()
if ToolTag.PRIVILEGED in tags:
return f"Privileged tool '{tool_name}' is not allowed in this environment"
return None
registry.add_post_register_hook(deny_privileged)
def sudo_command(cmd: str) -> str:
"""Run a command with elevated privileges."""
...
registry.register(
Tool.from_function(sudo_command, metadata=ToolMetadata(tags={ToolTag.PRIVILEGED}))
)
print(registry.is_enabled("sudo_command")) # False
print(registry.get_disable_reason("sudo_command"))
# "Privileged tool 'sudo_command' is not allowed in this environment"
# Multiple hooks are invoked in registration order
def log_all(tool_name: str, tool, registry) -> None:
print(f"[hook] registered: {tool_name}")
registry.add_post_register_hook(log_all)
Agent Skills¶
SkillsMixin adds skill loading to the same registry. The store is created on first use, so a registry that never calls a skill method does not touch the filesystem.
registry.discover_skills() # standard roots, or explicit paths
registry.discover_skills("/opt/skills", recursive=True, exclude=["*-draft"])
registry.list_skills() # sorted Skill objects
registry.select_skills("summarize a PDF", top_k=3, available_tools=registry.list_tools())
registry.skills_catalog() # level 1 prompt
registry.activate_skill("pdf-processing") # level 2 prompt
registry.read_skill_resource("pdf-processing", "references/guide.md") # level 3
registry.reload_skills()
registry.validate_skills()
Expose skills as tools with register_skill_tools(). Modes are "catalog" (default), "per-skill", and "both"; see Agent Skills for the generated names and the config shape.
apply_skill_config() consumes a ToolConfig or an iterable of SkillSource objects, resolves relative paths against the config file, and registers the declared tool sets.
Integration Points¶
The ToolRegistry provides integration points for:
- OpenAPI Services: Automatic REST API tool generation
- MCP Servers: Model Context Protocol tool discovery
- LangChain Tools: LangChain ecosystem integration
- Native Python: Direct class and function registration
This makes it a central hub for managing tools from diverse sources within LLM applications.
See Also¶
- Events - Detailed documentation on
ChangeEvent,ChangeEventType, andChangeCallback