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.
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.
Functions with *args
or **kwargs
are not supported as tools. This restriction exists because FastMCP needs to generate a complete parameter schema for the MCP protocol, which isn’t possible with variable argument lists.
Decorator Arguments
While FastMCP infers the name and description from your function, you can override these and add additional metadata using arguments to the @mcp.tool
decorator:
@tool Decorator Arguments
Sets the explicit tool name exposed via MCP. If not provided, uses the function name
Provides the description exposed via MCP. If set, the function’s docstring is ignored for this purpose
A set of strings to categorize the tool. Clients might use tags to filter or group available tools
A boolean to enable or disable the tool. See Disabling Tools for more information
A list of argument names to exclude from the tool schema shown to the LLM. See Excluding Arguments for more information
An optional ToolAnnotations
object or dictionary to add additional metadata about the tool.
Tool Parameters
Type Annotations
Type annotations for parameters are essential for proper tool functionality. They:
- Inform the LLM about the expected data types for each parameter
- Enable FastMCP to validate input data from clients
- Generate accurate JSON schemas for the MCP protocol
Use standard Python type annotations for parameters:
Parameter Metadata
You can provide additional metadata about parameters using Pydantic’s Field
class with Annotated
. This approach is preferred as it’s more modern and keeps type hints separate from validation rules:
You can also use the Field as a default value, though the Annotated approach is preferred:
Field provides several validation and documentation features:
description
: Human-readable explanation of the parameter (shown to LLMs)ge
/gt
/le
/lt
: Greater/less than (or equal) constraintsmin_length
/max_length
: String or collection length constraintspattern
: Regex pattern for string validationdefault
: Default value if parameter is omitted
Supported Types
FastMCP supports a wide range of type annotations, including all Pydantic types:
Type Annotation | Example | Description |
---|---|---|
Basic types | int , float , str , bool | Simple scalar values - see Built-in Types |
Binary data | bytes | Binary content - see Binary Data |
Date and Time | datetime , date , timedelta | Date and time objects - see Date and Time Types |
Collection types | list[str] , dict[str, int] , set[int] | Collections of items - see Collection Types |
Optional types | float | None , Optional[float] | Parameters that may be null/omitted - see Union and Optional Types |
Union types | str | int , Union[str, int] | Parameters accepting multiple types - see Union and Optional Types |
Constrained types | Literal["A", "B"] , Enum | Parameters with specific allowed values - see Constrained Types |
Paths | Path | File system paths - see Paths |
UUIDs | UUID | Universally unique identifiers - see UUIDs |
Pydantic models | UserData | Complex structured data - see Pydantic Models |
For additional type annotations not listed here, see the Parameter Types section below for more detailed information and examples.
Optional Arguments
FastMCP follows Python’s standard function parameter conventions. Parameters without default values are required, while those with default values are optional.
In this example, the LLM must provide a query
parameter, while max_results
, sort_by
, and category
will use their default values if not explicitly provided.
Excluding Arguments
New in version: 2.6.0
You can exclude certain arguments from the tool schema shown to the LLM. This is useful for arguments that are injected at runtime (such as state
, user_id
, or credentials) and should not be exposed to the LLM or client. Only arguments with default values can be excluded; attempting to exclude a required argument will raise an error.
Example:
With this configuration, user_id
will not appear in the tool’s parameter schema, but can still be set by the server or framework at runtime.
For more complex tool transformations, see Transforming Tools.
Disabling Tools
New in version: 2.8.0
You can control the visibility and availability of tools by enabling or disabling them. This is useful for feature flagging, maintenance, or dynamically changing the toolset available to a client. Disabled tools will not appear in the list of available tools returned by list_tools
, and attempting to call a disabled tool will result in an “Unknown tool” error, just as if the tool did not exist.
By default, all tools are enabled. You can disable a tool upon creation using the enabled
parameter in the decorator:
You can also toggle a tool’s state programmatically after it has been created:
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 tools can return data in two complementary formats: traditional content blocks (like text and images) and structured outputs (machine-readable JSON). When you add return type annotations, FastMCP automatically generates output schemas to validate the structured data and enables clients to deserialize results back to Python objects.
Understanding how these three concepts work together:
- Return Values: What your Python function returns (determines both content blocks and structured data)
- Structured Outputs: JSON data sent alongside traditional content for machine processing
- Output Schemas: JSON Schema declarations that describe and validate the structured output format
The following sections explain each concept in detail.
Content Blocks
FastMCP automatically converts tool return values into appropriate MCP content blocks:
str
: Sent asTextContent
bytes
: Base64 encoded and sent asBlobResourceContents
(within anEmbeddedResource
)fastmcp.utilities.types.Image
: Sent asImageContent
fastmcp.utilities.types.Audio
: Sent asAudioContent
fastmcp.utilities.types.File
: Sent as base64-encodedEmbeddedResource
- A list of any of the above: Converts each item appropriately
None
: Results in an empty response
Structured Output
New in version: 2.10.0
The 6/18/2025 MCP spec update introduced structured content, which is a new way to return data from tools. Structured content is a JSON object that is sent alongside traditional content. FastMCP automatically creates structured outputs alongside traditional content when your tool returns data that has a JSON object representation. This provides machine-readable JSON data that clients can deserialize back to Python objects.
Automatic Structured Content Rules:
- Object-like results (
dict
, Pydantic models, dataclasses) → Always become structured content (even without output schema) - Non-object results (
int
,str
,list
) → Only become structured content if there’s an output schema to validate/serialize them - All results → Always become traditional content blocks for backward compatibility
This automatic behavior enables clients to receive machine-readable data alongside human-readable content without requiring explicit output schemas for object-like returns.
Object-like Results (Automatic Structured Content)
Non-object Results (Schema Required)
Complex Type Example
Output Schemas
New in version: 2.10.0
The 6/18/2025 MCP spec update introduced output schemas, which are a new way to describe the expected output format of a tool. When an output schema is provided, the tool must return structured output that matches the schema.
When you add return type annotations to your functions, FastMCP automatically generates JSON schemas that describe the expected output format. These schemas help MCP clients understand and validate the structured data they receive.
Primitive Type Wrapping
For primitive return types (like int
, str
, bool
), FastMCP automatically wraps the result under a "result"
key to create valid structured output:
Manual Schema Control
You can override the automatically generated schema by providing a custom output_schema
:
Schema generation works for most common types including basic types, collections, union types, Pydantic models, TypedDict structures, and dataclasses.
Important Constraints:
- Output schemas must be object types (
"type": "object"
) - If you provide an output schema, your tool must return structured output that matches it
- However, you can provide structured output without an output schema (using
ToolResult
)
Full Control with ToolResult
For complete control over both traditional content and structured output, return a ToolResult
object:
When returning ToolResult
:
- You control exactly what content and structured data is sent
- Output schemas are optional - structured content can be provided without a schema
- Clients receive both traditional content blocks and structured data
If your return type annotation cannot be converted to a JSON schema (e.g., complex custom classes without Pydantic support), the output schema will be omitted but the tool will still function normally with traditional content.
Error Handling
New in version: 2.4.1
If your tool encounters an error, you can raise a standard Python exception (ValueError
, TypeError
, FileNotFoundError
, custom exceptions, etc.) or a FastMCP ToolError
.
By default, all exceptions (including their details) are logged and converted into an MCP error response to be sent back to the client LLM. This helps the LLM understand failures and react appropriately.
If you want to mask internal error details for security reasons, you can:
- Use the
mask_error_details=True
parameter when creating yourFastMCP
instance:
- Or use
ToolError
to explicitly control what error information is sent to clients:
When mask_error_details=True
, only error messages from ToolError
will include details, other exceptions will be converted to a generic message.
Annotations
New in version: 2.2.7
FastMCP allows you to add specialized metadata to your tools through annotations. These annotations communicate how tools behave to client applications without consuming token context in LLM prompts.
Annotations serve several purposes in client applications:
- Adding user-friendly titles for display purposes
- Indicating whether tools modify data or systems
- Describing the safety profile of tools (destructive vs. non-destructive)
- Signaling if tools interact with external systems
You can add annotations to a tool using the annotations
parameter in the @mcp.tool
decorator:
FastMCP supports these standard annotations:
Annotation | Type | Default | Purpose |
---|---|---|---|
title | string | - | Display name for user interfaces |
readOnlyHint | boolean | false | Indicates if the tool only reads without making changes |
destructiveHint | boolean | true | For non-readonly tools, signals if changes are destructive |
idempotentHint | boolean | false | Indicates if repeated identical calls have the same effect as a single call |
openWorldHint | boolean | true | Specifies if the tool interacts with external systems |
Remember that annotations help make better user experiences but should be treated as advisory hints. They help client applications present appropriate UI elements and safety controls, but won’t enforce security boundaries on their own. Always focus on making your annotations accurately represent what your tool actually does.
Notifications
New in version: 2.9.1
FastMCP automatically sends notifications/tools/list_changed
notifications to connected clients when tools are added, removed, enabled, or disabled. This allows clients to stay up-to-date with the current tool set without manually polling for changes.
Notifications are only sent when these operations occur within an active MCP request context (e.g., when called from within a tool or other MCP operation). Operations performed during server initialization do not trigger notifications.
Clients can handle these notifications using a message handler to automatically refresh their tool lists or update their interfaces.
MCP Context
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.
Parameter Types
FastMCP supports a wide variety of parameter types to give you flexibility when designing your tools.
FastMCP generally supports all types that Pydantic supports as fields, including all Pydantic custom types. This means you can use any type that can be validated and parsed by Pydantic in your tool parameters.
FastMCP supports type coercion when possible. This means that if a client sends data that doesn’t match the expected type, FastMCP will attempt to convert it to the appropriate type. For example, if a client sends a string for a parameter annotated as int
, FastMCP will attempt to convert it to an integer. If the conversion is not possible, FastMCP will return a validation error.
Built-in Types
The most common parameter types are Python’s built-in scalar types:
These types provide clear expectations to the LLM about what values are acceptable and allow FastMCP to validate inputs properly. Even if a client provides a string like “42”, it will be coerced to an integer for parameters annotated as int
.
Date and Time Types
FastMCP supports various date and time types from the datetime
module:
datetime
- Accepts ISO format strings (e.g., “2023-04-15T14:30:00”)date
- Accepts ISO format date strings (e.g., “2023-04-15”)timedelta
- Accepts integer seconds or timedelta objects
Collection Types
FastMCP supports all standard Python collection types:
All collection types can be used as parameter annotations:
list[T]
- Ordered sequence of itemsdict[K, V]
- Key-value mappingset[T]
- Unordered collection of unique itemstuple[T1, T2, ...]
- Fixed-length sequence with potentially different types
Collection types can be nested and combined to represent complex data structures. JSON strings that match the expected structure will be automatically parsed and converted to the appropriate Python collection type.
Union and Optional Types
For parameters that can accept multiple types or may be omitted:
Modern Python syntax (str | int
) is preferred over older Union[str, int]
forms. Similarly, str | None
is preferred over Optional[str]
.
Constrained Types
When a parameter must be one of a predefined set of values, you can use either Literal types or Enums:
Literals
Literals constrain parameters to a specific set of values:
Literal types:
- Specify exact allowable values directly in the type annotation
- Help LLMs understand exactly which values are acceptable
- Provide input validation (errors for invalid values)
- Create clear schemas for clients
Enums
For more structured sets of constrained values, use Python’s Enum class:
When using Enum types:
- Clients should provide the enum’s value (e.g., “red”), not the enum member name (e.g., “RED”)
- FastMCP automatically coerces the string value into the appropriate Enum object
- Your function receives the actual Enum member (e.g.,
Color.RED
) - Validation errors are raised for values not in the enum
Binary Data
There are two approaches to handling binary data in tool parameters:
Bytes
When you annotate a parameter as bytes
, FastMCP will:
- Convert raw strings directly to bytes
- Validate that the input can be properly represented as bytes
FastMCP does not automatically decode base64-encoded strings for bytes parameters. If you need to accept base64-encoded data, you should handle the decoding manually as shown below.
Base64-encoded strings
This approach is recommended when you expect to receive base64-encoded binary data from clients.
Paths
The Path
type from the pathlib
module can be used for file system paths:
When a client sends a string path, FastMCP automatically converts it to a Path
object.
UUIDs
The UUID
type from the uuid
module can be used for unique identifiers:
When a client sends a string UUID (e.g., “123e4567-e89b-12d3-a456-426614174000”), FastMCP automatically converts it to a UUID
object.
Pydantic Models
For complex, structured data with nested fields and validation, use Pydantic models:
Using Pydantic models provides:
- Clear, self-documenting structure for complex inputs
- Built-in data validation
- Automatic generation of detailed JSON schemas for the LLM
- Automatic conversion from dict/JSON input
Clients can provide data for Pydantic model parameters as either:
- A JSON object (string)
- A dictionary with the appropriate structure
- Nested parameters in the appropriate format
Pydantic Fields
FastMCP supports robust parameter validation through Pydantic’s Field
class. This is especially useful to ensure that input values meet specific requirements beyond just their type.
Note that fields can be used outside Pydantic models to provide metadata and validation constraints. The preferred approach is using Annotated
with Field
:
You can also use Field
as a default value, though the Annotated
approach is preferred:
Common validation options include:
Validation | Type | Description |
---|---|---|
ge , gt | Number | Greater than (or equal) constraint |
le , lt | Number | Less than (or equal) constraint |
multiple_of | Number | Value must be a multiple of this number |
min_length , max_length | String, List, etc. | Length constraints |
pattern | String | Regular expression pattern constraint |
description | Any | Human-readable description (appears in schema) |
When a client sends invalid data, FastMCP will return a validation error explaining why the parameter failed validation.
Server Behavior
Duplicate Tools
New in version: 2.1.0
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.
Removing Tools
New in version: 2.3.4
You can dynamically remove tools from a server using the remove_tool
method: