Tools
Expose functions as executable capabilities for your MCP client.
Tools are the core building blocks that allow your LLM to interact with external systems, execute code, and access data that isn’t in its training data. In FastMCP, tools are Python functions exposed to LLMs through the MCP protocol.
What Are Tools?
Tools in FastMCP transform regular Python functions into capabilities that LLMs can invoke during conversations. When an LLM decides to use a tool:
- It sends a request with parameters based on the tool’s schema.
- FastMCP validates these parameters against your function’s signature.
- Your function executes with the validated inputs.
- The result is returned to the LLM, which can use it in its response.
This allows LLMs to perform tasks like querying databases, calling APIs, making calculations, or accessing files—extending their capabilities beyond what’s in their training data.
Defining Tools
The @tool
Decorator
Creating a tool is as simple as decorating a Python function with @mcp.tool()
:
When this tool is registered, FastMCP automatically:
- Uses the function name (
add
) as the tool name. - Uses the function’s docstring (
Adds two integer numbers...
) as the tool description. - Generates an input schema based on the function’s parameters and type annotations.
- Handles parameter validation and error reporting.
The way you define your Python function dictates how the tool appears and behaves for the LLM client.
Type Annotations
Type annotations are crucial. They:
- Inform the LLM about the expected type for each parameter.
- Allow FastMCP to validate the data received from the client.
- Are used to generate the tool’s input schema for the MCP protocol.
FastMCP supports standard Python type annotations, including those from the typing
module and Pydantic.
Supported Type Annotation Examples:
Type Annotation | Example | Description |
---|---|---|
Basic types | int , float , str , bool | Simple scalar values |
Container types | list[str] , dict[str, int] | Collections of items |
Optional types | Optional[float] , float|None | Parameters that may be null/omitted |
Union types | str | int , Union[str, int] | Parameters accepting multiple types |
Literal types | Literal["A", "B"] | Parameters with specific allowed values |
Pydantic models | UserData | Complex structured data (see below) |
Automatic JSON Parsing: FastMCP intelligently handles arguments. If a client sends a string that looks like valid JSON (e.g., "['a', 'b']"
) for a parameter hinted as a structured type (like list[str]
or a Pydantic model), FastMCP will automatically attempt to parse the JSON string into the expected Python object before validation. This improves robustness when interacting with various clients.
Required vs. Optional Parameters
Parameters in your function signature are considered required unless they have a default value.
In this example, the LLM must provide a query
. If max_results
or sort_by
are omitted, their default values will be used.
Structured Inputs
For tools requiring complex, nested, or well-validated inputs, use Pydantic models. Define a BaseModel
and use it as a type hint for a parameter.
Using Pydantic models provides:
- Clear, self-documenting structure for complex inputs.
- Built-in data validation (e.g.,
gt=0
, date parsing). - Automatic generation of detailed JSON schemas for the LLM.
- Easy handling of optional fields and default values.
Metadata
While FastMCP infers the name and description from your function, you can override these and add tags using arguments to the @mcp.tool
decorator:
name
: Sets the explicit tool name exposed via MCP.description
: Provides the description exposed via MCP. If set, the function’s docstring is ignored for this purpose.tags
: A set of strings used to categorize the tool. Clients might use tags to filter or group available tools.
Async Tools
FastMCP seamlessly supports both standard (def
) and asynchronous (async def
) functions as tools.
Use async def
when your tool needs to perform operations that might wait for external systems (network requests, database queries, file access) to keep your server responsive.
Return Values
FastMCP automatically converts the value returned by your function into the appropriate MCP content format for the client:
str
: Sent asTextContent
.dict
,list
, PydanticBaseModel
: Serialized to a JSON string and sent asTextContent
.bytes
: Base64 encoded and sent asBlobResourceContents
(often within anEmbeddedResource
).fastmcp.utilities.types.Image
: A helper class to easily return image data. Sent asImageContent
.None
: Results in an empty response (no content is sent back to the client).
Error Handling
If your tool encounters an error, simply raise a standard Python exception (ValueError
, TypeError
, FileNotFoundError
, custom exceptions, etc.).
FastMCP automatically catches exceptions raised within your tool function:
- It converts the exception into an MCP error response, typically including the exception type and message.
- This error response is sent back to the client/LLM.
- The LLM can then inform the user or potentially try the tool again with different arguments.
Using informative exceptions helps the LLM understand failures and react appropriately.
Using Context in Tools
Tools can access MCP features like logging, reading resources, or reporting progress through the Context
object. To use it, add a parameter to your tool function with the type hint Context
.
The Context object provides access to:
- Logging:
ctx.debug()
,ctx.info()
,ctx.warning()
,ctx.error()
- Progress Reporting:
ctx.report_progress(progress, total)
- Resource Access:
ctx.read_resource(uri)
- LLM Sampling:
ctx.sample(...)
- Request Information:
ctx.request_id
,ctx.client_id
For full documentation on the Context object and all its capabilities, see the Context documentation.
Server Behavior
Duplicate Tools
You can control how the FastMCP server behaves if you try to register multiple tools with the same name. This is configured using the on_duplicate_tools
argument when creating the FastMCP
instance.
The duplicate behavior options are:
"warn"
(default): Logs a warning and the new tool replaces the old one."error"
: Raises aValueError
, preventing the duplicate registration."replace"
: Silently replaces the existing tool with the new one."ignore"
: Keeps the original tool and ignores the new registration attempt.