Skip to content

Tool

Represents an individual tool with metadata and execution logic within the ToolRegistry ecosystem.

Overview

The Tool class serves as a fundamental abstraction for all tools in the ToolRegistry system. It encapsulates both the executable logic and the metadata necessary for proper tool discovery, parameter validation, and execution within LLM applications.

Key Features

  • Metadata Management: Comprehensive tool description, parameters, and execution metadata
  • Parameter Validation: Built-in parameter schema validation and type checking
  • Execution Abstraction: Unified interface for both synchronous and asynchronous execution
  • Namespace Support: Integration with namespace organization for tool grouping
  • Callable Integration: Direct execution through callable interface

Architecture

The Tool class follows a data-transfer-object pattern with the following key components:

Core Attributes

  1. name: Unique identifier for the tool
  2. description: Human-readable description of tool functionality
  3. parameters: JSON schema defining expected parameters
  4. callable: The actual executable function or wrapper
  5. is_async: Flag indicating asynchronous execution capability
  6. namespace: Optional namespace for organization (stores the original namespace string after normalization)
  7. method_name: Optional original method/function name before namespace prefixing (preserved for unambiguous base name recovery)

Computed Properties

  • qualified_name: Returns the registered name. The name is authoritative and is rebuilt from namespace, method_name, and the registry's separator by namespace operations.

Design Philosophy

  • Immutability: Tool and ToolMetadata are frozen=True dataclasses — fields cannot be reassigned after construction. ToolMetadata copies its tags, custom_tags and extra containers when constructed, so dataclasses.replace() copies are independent; every extra value is deep-copied on its own, so nested containers are isolated too, and an uncopyable value (a lock, a generator, a module) is kept by reference with a UserWarning. Use dataclasses.replace() to create modified copies, or Tool.with_parameters() when replacing a parameter schema.
  • Schema-Driven: Parameter validation based on JSON Schema standards
  • Execution Flexibility: Support for both sync and async execution patterns
  • Metadata Preservation: Complete preservation of tool metadata for LLM consumption

API Reference

toolregistry.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.

Metadata Declaration

toolregistry.tool_metadata

tool_metadata(**fields: Any) -> Callable[[_F], _F]

Declare :class:ToolMetadata values on a tool function.

The declaration lives on the function (__tool_metadata__), so class registration picks it up without a separate scan: bound methods delegate attribute access to the underlying function. :meth:Tool.from_function applies it when it builds the tool.

Parameters:

Name Type Description Default
**fields Any

Any declarable :class:ToolMetadata field, for example tags={"read_only"}, defer=True, title="Web Search" or read_only_hint=True. is_async, source, source_detail, schema_hash and last_refreshed_at are owned by the registration pipeline and cannot be declared.

{}

Returns:

Type Description
Callable[[_F], _F]

A decorator that stores the declaration and returns the function

Callable[[_F], _F]

unchanged.

Raises:

Type Description
TypeError

If a field is not part of :class:ToolMetadata, is owned by the registration pipeline, or the decorated object does not accept attributes.

Example
from toolregistry import tool_metadata

class Search:
    @staticmethod
    @tool_metadata(defer=True, tags={"network"}, read_only_hint=True)
    def web_search(query: str) -> list[str]:
        ...
Note

Stacking decorators merges the declarations; the outer decorator wins on a conflict. An explicit metadata= argument passed to :meth:Tool.from_function wins over the declaration: the decorator fills only the fields that argument left at their dataclass default. A boolean field whose default is False therefore cannot be held at False against a decorator that declares True; do not declare that field in that case.

functools.wraps keeps the declaration, because it copies the wrapped function's __dict__ onto the wrapper. A helper that builds a new function object instead (for example types.FunctionType with a narrowed inspect.Signature, or a function that binds a literal argument) drops it. Such helpers must call :func:copy_tool_metadata on the function they return:

import functools

from toolregistry import copy_tool_metadata, tool_metadata

@tool_metadata(read_only_hint=True)
def convert(value: float, unit: str) -> float:
    ...

def bind_unit(func, unit):
    def bound(value: float) -> float:
        return func(value, unit)

    return copy_tool_metadata(func, bound)

to_meters = bind_unit(convert, "m")  # still read_only_hint=True

@functools.wraps(convert)  # keeps the declaration on its own
def logged(value: float, unit: str) -> float:
    return convert(value, unit)

toolregistry.copy_tool_metadata

copy_tool_metadata(source: Callable[..., Any], target: _F) -> _F

Copy the @tool_metadata declaration of source onto target.

Use this in any wrapper that returns a new function object rather than one produced by functools.wraps (which already keeps the declaration). See :func:tool_metadata for an example.

The declaration is merged into whatever target already declares, and source wins on a conflict, as if source's @tool_metadata were stacked on top of target. If source declares nothing, target is left unchanged.

Parameters:

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

The function whose declaration should be preserved.

required
target _F

The new function object, usually the wrapper being returned.

required

Returns:

Type Description
_F

target, so the call can be used as the wrapper's return value.

Raises:

Type Description
TypeError

If target does not accept attributes.

Usage Examples

Basic Tool Creation

from toolregistry import Tool

def calculate_area(length: float, width: float) -> float:
    """Calculate the area of a rectangle."""
    return length * width

# Create a Tool instance
area_tool = Tool(
    name="calculate_area",
    description="Calculate the area of a rectangle",
    parameters={
        "type": "object",
        "properties": {
            "length": {"type": "number", "description": "Length of rectangle"},
            "width": {"type": "number", "description": "Width of rectangle"}
        },
        "required": ["length", "width"]
    },
    callable=calculate_area,
    is_async=False
)

Tool with Namespace

from toolregistry import Tool

# Create a tool with namespace and method_name fields
math_tool = Tool(
    name="math_ops-multiply",
    description="Multiply two numbers",
    parameters={
        "type": "object",
        "properties": {
            "a": {"type": "number"},
            "b": {"type": "number"}
        },
        "required": ["a", "b"]
    },
    callable=lambda a, b: a * b,
    is_async=False,
    namespace="math_ops",
    method_name="multiply",
)

# Access the qualified name
print(math_tool.qualified_name)  # Output: "math_ops-multiply"
print(math_tool.namespace)       # Output: "math_ops"
print(math_tool.method_name)     # Output: "multiply"

Tool from Function with Namespace

from toolregistry import Tool

def multiply(a: float, b: float) -> float:
    """Multiply two numbers."""
    return a * b

# Create a tool with namespace using from_function()
tool = Tool.from_function(multiply, namespace="math_ops")
print(tool.name)            # Output: "math_ops-multiply"
print(tool.namespace)       # Output: "math_ops"
print(tool.method_name)     # Output: "multiply"
print(tool.qualified_name)  # Output: "math_ops-multiply"

# You can also provide a custom method_name
tool2 = Tool.from_function(multiply, namespace="math_ops", method_name="mul")
print(tool2.name)            # Output: "math_ops-mul"
print(tool2.method_name)     # Output: "mul"

# Use the registry's separator when constructing directly
tool3 = Tool.from_function(multiply, namespace="math_ops", sep=".")
print(tool3.name)            # Output: "math_ops.multiply"

When the registry uses ToolRegistry(name_sep="."), pass the same separator to Tool.from_function(..., sep=".") so the constructed name matches the registry key.

Updating Namespace

from toolregistry import Tool

# Create a tool without namespace
math_tool = Tool.from_function(lambda a, b: a * b, name="multiply")

# Update with namespace
math_tool = math_tool.update_namespace("math_operations")
print(math_tool.name)           # Output: "math_operations-multiply"
print(math_tool.namespace)      # Output: "math_operations"
print(math_tool.method_name)    # Output: "multiply"
print(math_tool.qualified_name) # Output: "math_operations-multiply"

Refreshing Metadata

from toolregistry import Tool

tool = Tool.from_function(lambda x: x, name="echo")

# Update last_refreshed_at timestamp (returns a new frozen Tool)
updated = tool.with_refreshed_at("2026-09-15T08:00:00Z")
print(updated.metadata.last_refreshed_at)  # "2026-09-15T08:00:00Z"

Execution Hints

Tool.execution_hints resolves hints for every tool, deriving read_only_hint / destructive_hint from ToolTag.READ_ONLY / ToolTag.DESTRUCTIVE. Those tags also drive the built-in permission rules, so the resolved mapping is not automatically safe to publish: a tag chosen for local policy would become a client-facing auto-approve claim.

Tool.declared_execution_hints returns only what the tool declared explicitly, plus the destructive_hint=False complement implied by an explicit read_only_hint=True. Transports should publish this mapping and treat an empty result as "no claim" (absent annotations), which is what an MCP client interprets as write-capable.

from toolregistry import Tool
from toolregistry.tool import ToolMetadata, ToolTag

tagged = Tool.from_function(
    lambda: "state",
    name="reader",
    metadata=ToolMetadata(tags={ToolTag.READ_ONLY}),
)
print(tagged.execution_hints)          # {'read_only_hint': True, 'destructive_hint': False}
print(tagged.declared_execution_hints) # {}

explicit = Tool.from_function(
    lambda: "state",
    name="reader2",
    metadata=ToolMetadata(read_only_hint=True),
)
print(explicit.declared_execution_hints)  # {'read_only_hint': True, 'destructive_hint': False}

Declaring Metadata at Definition Time

@tool_metadata stores the declaration on the function itself, and Tool.from_function applies it. Every registration path therefore carries it, including class registration, which passes no metadata to the constructor.

from toolregistry import ToolRegistry, tool_metadata

class Search:
    @staticmethod
    @tool_metadata(defer=True, tags={"network"}, title="Web Search")
    def web_search(query: str) -> list[str]:
        """Search the web."""
        return [query]

registry = ToolRegistry()
registry.register(Search)
tool = registry.get_tool("web_search")
print(tool.metadata.defer)          # True
print(tool.metadata.tags)           # {"network"}

An explicit metadata= argument to Tool.from_function wins: the decorator only fills the fields that argument left at their dataclass default. A field that defaults to False (defer, for example) cannot be held at False against a decorator that declares True; pass the explicit value and do not declare that field. is_async is always detected from the function, and the pipeline-owned fields (is_async, source, source_detail, schema_hash, last_refreshed_at) cannot be declared — decoration raises TypeError.

Stacking decorators merges the declarations, and the outer one wins on a conflict. Bound methods delegate attribute access to the underlying function, so no extra class scan is needed. @tool_metadata must sit below @staticmethod, because the outer staticmethod object does not accept the attribute.

Copying a Declaration onto a Rebuilt Function

functools.wraps keeps the declaration because it copies the wrapped function's __dict__. A wrapper that builds a new function object instead — to bind a literal, drop a parameter, or wrap a bound method — loses it. copy_tool_metadata(source, target) applies the source's declaration to the new function:

from toolregistry import copy_tool_metadata, tool_metadata

@tool_metadata(tags={"network"}, title="Web Search")
def search(query: str) -> list[str]:
    """Search the web."""
    return [query]

def search_site(site: str):
    def wrapped(query: str) -> list[str]:
        """Search one site."""
        return search(f"site:{site} {query}")

    return copy_tool_metadata(search, wrapped)

print(getattr(search_site("example.com"), "__tool_metadata__"))
# {'tags': {'network'}, 'title': 'Web Search'}

The declaration is merged into whatever target already declares, and source wins on a conflict — the same result as stacking source's decorator on top of target's. A source that declares nothing leaves target unchanged and adds no attribute. A target that rejects attributes raises TypeError. Values are copied by reference, so a mutable declaration value (a tags set) is shared with the source; do not mutate it after copying.

Replacing a Parameter Schema

dataclasses.replace(tool, parameters=...) reuses the existing metadata, so the fingerprint would still describe the old schema. It now warns when that happens; a hash supplied at construction is stored verbatim, even when it disagrees, so the reported fingerprint is the supplied one. Use Tool.with_parameters() to replace the schema and recompute the hash in one step:

from toolregistry.utils import compute_schema_hash

updated = tool.with_parameters(
    {"type": "object", "properties": {"q": {"type": "string"}}}
)
assert updated.metadata.schema_hash == compute_schema_hash(updated.parameters)

The old validation model is dropped by default, because it describes the old schema, and a UserWarning names the tool when that happens; pass parameters_model= when the new schema is equivalent. Without a model, validate_parameters() is a pass-through: it does not check types, required fields, or unknown keys, so payloads that violate the published schema are accepted.

Async Tool

import asyncio
from toolregistry import Tool

async def fetch_data(url: str) -> dict:
    """Fetch data from a URL asynchronously."""
    # Async implementation
    return {"url": url, "data": "sample"}

# Create async tool
async_tool = Tool(
    name="fetch_data",
    description="Fetch data from URL",
    parameters={
        "type": "object",
        "properties": {
            "url": {"type": "string", "description": "URL to fetch from"}
        },
        "required": ["url"]
    },
    callable=fetch_data,
    is_async=True
)

Executing Tools

The Tool class provides sync and async execution:

  • run(parameters) — Execute synchronously. Raises exceptions on failure.
  • arun(parameters) — Execute asynchronously. Raises exceptions on failure.

Both methods handle sync/async callable transparency automatically. A sync tool can be called via arun() (dispatched via asyncio.to_thread()), and an async tool can be called via run() (dispatched via asyncio.run()).

from toolregistry import Tool

def divide(a: float, b: float) -> float:
    """Divide a by b."""
    return a / b

tool = Tool.from_function(divide)

# Sync execution
try:
    result = tool.run({"a": 10, "b": 0})
except ZeroDivisionError:
    print("Cannot divide by zero!")

# Async execution
result = await tool.arun({"a": 10, "b": 2})  # returns 5.0

run_raw() / arun_raw() are deprecated

These methods are now aliases for run() / arun() and emit DeprecationWarning. Use run() / arun() directly.

Accessing the Underlying Function

Use the tool.fn property to get the original unwrapped function:

tool = Tool.from_function(my_func)
tool.fn          # → my_func (the original function)
tool.callable    # → _FunctionToolWrapper (the wrapper, for internal use)

Parameter Schema Format

The Tool class uses JSON Schema format for parameter validation:

{
  "type": "object",
  "properties": {
    "param_name": {
      "type": "string|number|boolean|array|object",
      "description": "Parameter description",
      "default": "default_value"
    }
  },
  "required": ["param1", "param2"]
}

Integration with ToolRegistry

Tools are primarily used through the ToolRegistry:

from toolregistry import ToolRegistry, Tool

registry = ToolRegistry()

# Register tool with registry
registry.register(tool_instance)

# Execute tool through registry
result = registry.invoke("tool_name", {"param1": "value1", "param2": "value2"})
print(result.result)  # result.message when the call failed

The Tool class provides the foundation for all tool operations within the ToolRegistry ecosystem, ensuring consistent behavior across different tool sources and execution environments.