> ## Documentation Index
> Fetch the complete documentation index at: https://docs.swarms.world/llms.txt
> Use this file to discover all available pages before exploring further.

# Tools & Utilities

> Comprehensive reference for Swarms tools, function calling, and schema conversion utilities

## Overview

The `swarms.tools` module provides a comprehensive toolkit for function calling, schema conversion, and tool management. It enables seamless integration with OpenAI-style function calling, MCP (Model Context Protocol) tools, and Pydantic-based schema validation.

## BaseTool

A comprehensive tool management system for function calling, schema conversion, and execution.

```python theme={null}
from swarms.tools import BaseTool

tool_manager = BaseTool(
    verbose=True,
    tools=[my_function],
    base_models=[MyModel]
)
```

### Constructor

<ParamField path="verbose" type="bool" default="None">
  Enable detailed logging output
</ParamField>

<ParamField path="base_models" type="List[type[BaseModel]]" default="None">
  List of Pydantic models to manage
</ParamField>

<ParamField path="autocheck" type="bool" default="None">
  Enable automatic validation checks
</ParamField>

<ParamField path="auto_execute_tool" type="bool" default="None">
  Enable automatic tool execution
</ParamField>

<ParamField path="tools" type="List[Callable]" default="None">
  List of callable functions to manage
</ParamField>

<ParamField path="tool_system_prompt" type="str" default="None">
  System prompt for tool operations
</ParamField>

<ParamField path="function_map" type="Dict[str, Callable]" default="None">
  Mapping of function names to callables
</ParamField>

<ParamField path="list_of_dicts" type="List[Dict[str, Any]]" default="None">
  List of dictionary representations of tool schemas
</ParamField>

### Methods

#### func\_to\_dict

Convert a callable function to OpenAI function calling schema dictionary.

```python theme={null}
schema = tool.func_to_dict(my_function)
```

<ParamField path="function" type="Callable" required>
  The function to convert
</ParamField>

<ResponseField name="return" type="Dict[str, Any]">
  OpenAI function calling schema dictionary
</ResponseField>

**Raises:**

* `FunctionSchemaError`: If function schema conversion fails
* `ToolValidationError`: If function validation fails

#### base\_model\_to\_dict

Convert a Pydantic BaseModel to OpenAI function calling schema.

```python theme={null}
schema = tool.base_model_to_dict(MyModel, output_str=False)
```

<ParamField path="pydantic_type" type="type[BaseModel]" required>
  The Pydantic model class to convert
</ParamField>

<ParamField path="output_str" type="bool" default="False">
  Whether to return string output format
</ParamField>

<ResponseField name="return" type="Union[dict[str, Any], str]">
  OpenAI function calling schema dictionary or JSON string
</ResponseField>

#### execute\_tool

Execute a tool based on a response string.

```python theme={null}
result = tool.execute_tool('{"name": "my_function", "parameters": {...}}')
```

<ParamField path="response" type="str" required>
  JSON response string containing tool execution details
</ParamField>

<ResponseField name="return" type="Callable">
  Result of the tool execution
</ResponseField>

**Raises:**

* `ToolValidationError`: If response validation fails
* `ToolExecutionError`: If tool execution fails
* `ToolNotFoundError`: If specified tool is not found

#### convert\_funcs\_into\_tools

Convert all functions in the tools list into OpenAI function calling format.

```python theme={null}
tool.convert_funcs_into_tools()
```

This method processes all functions in the tools list, validates them for proper documentation and type hints, and converts them to OpenAI schemas.

**Raises:**

* `ToolValidationError`: If tools are not properly configured
* `ToolDocumentationError`: If functions lack required documentation
* `ToolTypeHintError`: If functions lack required type hints

#### execute\_tool\_by\_name

Search for a tool by name and execute it with the provided response.

```python theme={null}
result = tool.execute_tool_by_name("add", '{"a": 1, "b": 2}')
```

<ParamField path="tool_name" type="str" required>
  The name of the tool to execute
</ParamField>

<ParamField path="response" type="str" required>
  JSON response string containing execution parameters
</ParamField>

<ResponseField name="return" type="Any">
  The result of executing the tool
</ResponseField>

## Tool Registry

`swarms.tools` exports a small registry pair: the `ToolStorage` class, which holds named tool callables, and the `tool_registry` decorator, which registers a function into a `ToolStorage` instance at import time.

```python theme={null}
from swarms.tools import ToolStorage, tool_registry

storage = ToolStorage(
    name="Math Tools",
    description="Arithmetic helpers for the agent",
)

@tool_registry(storage)
def add(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b

# Look the tool back up by name and call it
add_fn = storage.get_tool("add")
print(add_fn(2, 3))  # 5
```

<Note>
  There is no `tool` decorator in `swarms.tools`. To hand a plain Python function to an agent, pass it directly via `Agent(tools=[my_function])` — the framework generates the OpenAI schema from the function's type hints and docstring. Use `tool_registry` only when you also want name-based lookup through a `ToolStorage`.
</Note>

### ToolStorage

<ParamField path="name" type="str" default="None">
  Name of the registry
</ParamField>

<ParamField path="description" type="str" default="None">
  Description of the registry
</ParamField>

<ParamField path="verbose" type="bool" default="None">
  Enable detailed logging output
</ParamField>

<ParamField path="tools" type="List[Callable]" default="None">
  Initial list of tool functions
</ParamField>

#### Methods

| Method                    | Description                                                                                           |
| ------------------------- | ----------------------------------------------------------------------------------------------------- |
| `add_tool(func)`          | Add a single tool. Raises `ValueError` if a tool with the same name already exists                    |
| `add_many_tools(funcs)`   | Add a list of tools concurrently                                                                      |
| `get_tool(name)`          | Return the callable registered under `name`. Raises `ValueError` if not found                         |
| `list_tools()`            | Return the registry contents as a formatted JSON string (name, documentation, creation time per tool) |
| `set_setting(key, value)` | Store an arbitrary setting on the registry                                                            |
| `get_setting(key)`        | Read a setting back. Raises `KeyError` if not set                                                     |

<Warning>
  `list_tools()` returns a JSON **string** built from the registry's metadata schema, not a list of tool names.
</Warning>

### tool\_registry

<ParamField path="storage" type="ToolStorage" default="None">
  The storage instance to register the decorated function in
</ParamField>

<ResponseField name="return" type="Callable">
  A decorator that registers the function and returns a logging wrapper around it
</ResponseField>

## Utility Functions

### get\_openai\_function\_schema\_from\_func

Convert a Python function to OpenAI function calling schema.

```python theme={null}
from swarms.tools import get_openai_function_schema_from_func

def add(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b

schema = get_openai_function_schema_from_func(
    add,
    name="add_numbers",
    description="Add two integers"
)
```

### base\_model\_to\_openai\_function

Convert a Pydantic BaseModel to OpenAI function schema.

```python theme={null}
from swarms.tools import base_model_to_openai_function
from pydantic import BaseModel

class UserInput(BaseModel):
    name: str
    age: int

schema = base_model_to_openai_function(UserInput)
```

### scrape\_tool\_func\_docs

Extract documentation from a tool function.

```python theme={null}
from swarms.tools import scrape_tool_func_docs

docs = scrape_tool_func_docs(my_function)
```

### tool\_find\_by\_name

Find a tool by name in a list of tools.

```python theme={null}
from swarms.tools import tool_find_by_name

tool = tool_find_by_name("calculator", tools_list)
```

## MCP Tools Integration

MCP integration is handled by a single class, [`MCPManager`](/api/mcp-manager). Point it at one or more servers and it manages transport, authentication, tool discovery, caching, and routing each call to the server that owns the tool.

```python theme={null}
from swarms.tools.mcp_manager import MCPManager

manager = MCPManager(mcp_url="http://localhost:8000/mcp")

manager.list_tool_names()                                  # discover
manager.get_tools()                                        # OpenAI schemas for an LLM
manager.call_tool("get_crypto_price", {"coin_id": "btc"})  # call one directly
manager.execute_tool_calls(llm_response)                   # run what a model asked for
```

`MCPManager` and `MCPFileTokenStorage` are exported from `swarms.tools`. See the [MCPManager reference](/api/mcp-manager) for the full API, and the [MCP integration guide](/integrations/mcp) for using it from an agent.

<Warning>
  **Removed in favor of `MCPManager`.** The standalone functions previously documented here — `get_mcp_tools_sync`, `aget_mcp_tools`, `execute_tool_call_simple`, `get_tools_for_multiple_mcp_servers`, and `execute_multiple_tools_on_multiple_mcp_servers` — no longer exist, along with the `swarms.tools.mcp_client_tools` module.

  | Removed                                                 | Replacement                                              |
  | ------------------------------------------------------- | -------------------------------------------------------- |
  | `get_mcp_tools_sync(server_path=URL)`                   | `MCPManager(mcp_url=URL).get_tools()`                    |
  | `aget_mcp_tools(server_path=URL)`                       | `await MCPManager(mcp_url=URL).aget_tools()`             |
  | `get_tools_for_multiple_mcp_servers(urls=URLS)`         | `MCPManager(mcp_urls=URLS).get_tools()`                  |
  | `execute_tool_call_simple(response=R, server_path=URL)` | `await MCPManager(mcp_url=URL).aexecute_tool_calls(R)`   |
  | `execute_multiple_tools_on_multiple_mcp_servers(...)`   | `await MCPManager(mcp_urls=URLS).aexecute_tool_calls(R)` |

  Full migration notes, including the two behavioral differences, are in the [MCPManager reference](/api/mcp-manager#migration).
</Warning>

## Additional Utilities

A few other symbols are exported from `swarms.tools` for less common use cases:

* **`multi_base_model_to_openai_function`** — Convert several Pydantic `BaseModel` classes to a combined OpenAI function schema.
* **`Function`** / **`ToolFunction`** — Pydantic models describing an OpenAI function and a tool wrapping one.
* **`load_basemodels_if_needed`** / **`get_load_param_if_needed_function`** — Coerce raw dict arguments into the Pydantic models a tool's signature declares.
* **`get_parameters`** / **`get_required_params`** — Extract the JSON-schema parameter block and the list of required parameter names from a callable.
* **`ToolStorage`** / **`tool_registry`** — Register and look up tools by name; see [Tool Registry](#tool-registry) above.
* **`MCPManager`** / **`MCPFileTokenStorage`** — MCP transport, auth, discovery, and routing; see the [MCPManager reference](/api/mcp-manager).

## Exceptions

`BaseTool` raises the exceptions below. They are defined in `swarms.tools.base_tool` and are **not** re-exported from `swarms.tools`, so import them from the module directly:

```python theme={null}
from swarms.tools.base_tool import (
    BaseToolError,
    ToolValidationError,
    ToolExecutionError,
    ToolNotFoundError,
    FunctionSchemaError,
    ToolDocumentationError,
    ToolTypeHintError,
)
```

All of them subclass `BaseToolError`.

### BaseToolError

Base exception class for all BaseTool related errors.

### ToolValidationError

Raised when tool validation fails.

### ToolExecutionError

Raised when tool execution fails.

### ToolNotFoundError

Raised when a requested tool is not found.

### FunctionSchemaError

Raised when function schema conversion fails.

### ToolDocumentationError

Raised when tool documentation is missing or invalid.

### ToolTypeHintError

Raised when tool type hints are missing or invalid.

## Best Practices

1. **Always add type hints**: Functions must have type hints for reliable schema generation
2. **Include docstrings**: Comprehensive docstrings improve tool descriptions
3. **Validate inputs**: Use Pydantic models for complex input validation
4. **Handle errors**: Wrap tool execution in try-catch blocks
5. **Use caching**: BaseTool caches expensive operations for performance
6. **Enable verbose mode**: During development, enable verbose logging to debug issues

## Example: Complete Tool Setup

```python theme={null}
from swarms.tools import BaseTool
from pydantic import BaseModel

# Define a Pydantic model
class MathInput(BaseModel):
    a: int
    b: int
    operation: str

# Define a function with type hints and docstring
def calculate(a: int, b: int, operation: str) -> int:
    """Perform arithmetic operations on two numbers.
    
    Args:
        a: First number
        b: Second number
        operation: Operation to perform (add, subtract, multiply, divide)
    
    Returns:
        Result of the operation
    """
    if operation == "add":
        return a + b
    elif operation == "subtract":
        return a - b
    elif operation == "multiply":
        return a * b
    elif operation == "divide":
        return a // b
    else:
        raise ValueError(f"Unknown operation: {operation}")

# Create tool manager
tool_manager = BaseTool(
    verbose=True,
    tools=[calculate],
    base_models=[MathInput]
)

# Convert tools to OpenAI schema
tool_manager.convert_funcs_into_tools()

# Execute a tool
result = tool_manager.execute_tool_by_name(
    "calculate",
    '{"a": 10, "b": 5, "operation": "multiply"}'
)
print(result)  # 50
```
