Skip to main content

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. Every name in swarms.tools.__all__ is re-exported from the top-level package, so from swarms import BaseTool and from swarms.tools import BaseTool give you the same class.
You rarely need these classes to give an agent tools. Pass plain functions with Agent(tools=[...]) and the agent’s ToolManager builds the schemas, executes calls, and retries failures for you. For large tool sets loaded on demand, see DynamicToolLoader. Use BaseTool directly when you need schema conversion or tool execution outside an agent.

BaseTool

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

Constructor

bool
default:"None"
Enable detailed logging output
List[type[BaseModel]]
default:"None"
List of Pydantic models to manage
bool
default:"None"
Enable automatic validation checks
bool
default:"None"
Enable automatic tool execution
List[Callable]
default:"None"
List of callable functions to manage
str
default:"None"
System prompt for tool operations
Dict[str, Callable]
default:"None"
Mapping of function names to callables. convert_funcs_into_tools() fills it from tools
List[Dict[str, Any]]
default:"None"
List of dictionary representations of tool schemas

Methods

func_to_dict

Convert a callable function to OpenAI function calling schema dictionary.
Callable
required
The function to convert
Dict[str, Any]
OpenAI tool schema of the form {"type": "function", "function": {"name", "description", "parameters"}}
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.
type[BaseModel]
required
The Pydantic model class to convert
bool
default:"False"
Whether to return string output format
Union[dict[str, Any], str]
OpenAI function calling schema dictionary or JSON string

execute_tool

Execute one or more tool calls described by a JSON string, using the functions in tools.
str
required
JSON describing the call. Accepted shapes are {"name": ..., "parameters": {...}}, {"function": {"name": ..., "parameters": {...}}}, and {"functions": [...]} for several calls
str
A JSON string of the form {"results": {"add": "3"}, "summary": "add: 3"}. Each result is converted to a string. A call to an unknown function is reported in results as "Error: Function not found" rather than raised
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.
This method processes all functions in the tools list, validates them for proper documentation and type hints, and converts them to OpenAI schemas. It also sets function_map from the tools list, which execute_tool_by_name needs. Raises:
  • ToolValidationError: If tools are not properly configured, or if any function fails conversion. A missing docstring or type hint surfaces here as a ToolValidationError whose message names the function

execute_tool_by_name

Look up a tool in function_map and execute it with the provided call JSON.
str
required
The name of the tool to execute. It must be a key in function_map
str
required
Call JSON in the same shape execute_tool accepts. Its name must match tool_name; a bare arguments object such as {"a": 1, "b": 2} is skipped and returns empty results
str
A JSON string of the form {"results": {...}, "summary": "..."}, as returned by execute_tool
Raises:
  • ToolValidationError: If function_map is not set, or tool_name or response is empty
  • ToolNotFoundError: If tool_name is not in function_map
  • ToolExecutionError: If execution fails unexpectedly

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

ToolStorage

str
default:"None"
Name of the registry
str
default:"None"
Description of the registry
bool
default:"None"
Enable detailed logging output
List[Callable]
default:"None"
Initial list of tool functions

Methods

list_tools() returns a JSON string built from the registry’s metadata schema, not a list of tool names.

tool_registry

ToolStorage
default:"None"
The storage instance to register the decorated function in
Callable
A decorator that registers the function and returns a logging wrapper around it

Utility Functions

get_openai_function_schema_from_func

Convert a Python function to OpenAI function calling schema. name and description are keyword-only and override the function’s own name and docstring.

base_model_to_openai_function

Convert a Pydantic BaseModel to an OpenAI function schema.
type[BaseModel]
required
The Pydantic model class to convert
bool
default:"False"
Return a pretty-printed JSON string instead of a dict
dict
A dict of the form {"function_call": {"name": ...}, "functions": [{"name", "description", "parameters"}]}
The model’s docstring Args: section fills in each property’s description when the field does not already set one. Indented continuation lines belong to the parameter above them, so a wrapped description such as city above is kept whole.

scrape_tool_func_docs

Extract documentation from a tool function.

tool_find_by_name

Find a tool by name in a list of tool objects. It compares each object’s .name attribute and returns None when nothing matches, so it does not work on plain functions.

MCP Tools Integration

MCP integration is handled by a single class, MCPManager. 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.
MCPManager and MCPFileTokenStorage are exported from swarms.tools. See the MCPManager reference for the full API, and the MCP integration guide for using it from an agent.
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.Full migration notes, including the two behavioral differences, are in the MCPManager reference.

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 schema of the form {"function_call": "auto", "functions": [...]}.
  • 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 above.
  • MCPManager / MCPFileTokenStorage — MCP transport, auth, discovery, and routing; see the MCPManager reference.

Exceptions

BaseTool raises the exceptions below. They are defined in swarms.tools.base_tool and are not re-exported from swarms.tools or swarms, so import them from the module directly:
All of them subclass BaseToolError.
These are BaseTool’s own errors. Inside an agent, a tool call that still fails after tool_retry_attempts raises AgentToolExecutionError, which the agent catches and writes into the conversation so the model can react. It does not escape Agent.run(). That class and the other agent errors live in swarms.schemas; see Agent error schemas.

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. Enable verbose mode: During development, enable verbose logging to debug issues

Example: Complete Tool Setup