Expose functions as executable capabilities for your MCP client.
@tool
Decorator@mcp.tool
:
add
) as the tool name.Adds two integer numbers...
) as the tool description.*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.@mcp.tool
decorator:
ToolAnnotations
object or dictionary to add additional metadata about the tool.New in version: 2.11.0
Optional meta information about the tool. This data is passed through to the MCP client as the _meta
field of the client-side tool object and can be used for custom metadata, versioning, or other application-specific purposes.async def
) and synchronous (def
) functions as tools. Async tools are preferred for I/O-bound operations to keep your server responsive.
While synchronous tools work seamlessly in FastMCP, they can block the event loop during execution. For CPU-intensive or potentially blocking synchronous operations, consider alternative strategies. One approach is to use anyio
(which FastMCP already uses internally) to wrap them as async functions, for example:
asyncio.get_event_loop().run_in_executor()
or other threading techniques to manage blocking operations without impacting server responsiveness. For example, here’s a recipe for using the asyncer
library (not included in FastMCP) to create a decorator that wraps synchronous functions, courtesy of @hsheth2:
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 |
New in version: 2.11.0
For basic parameter descriptions, you can use a convenient shorthand with Annotated
:
Field(description=...)
but more concise for simple descriptions.
Annotated
types with a single string description.Field
class with Annotated
:
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 omittedquery
parameter, while max_results
, sort_by
, and category
will use their default values if not explicitly provided.
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:
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.
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:
str
: Sent as TextContent
bytes
: Base64 encoded and sent as BlobResourceContents
(within an EmbeddedResource
)fastmcp.utilities.types.Image
: Sent as ImageContent
fastmcp.utilities.types.Audio
: Sent as AudioContent
fastmcp.utilities.types.File
: Sent as base64-encoded EmbeddedResource
None
: Results in an empty responseNew 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:
dict
, Pydantic models, dataclasses) → Always become structured content (even without output schema)int
, str
, list
) → Only become structured content if there’s an output schema to validate/serialize themNew 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.
int
, str
, bool
), FastMCP automatically wraps the result under a "result"
key to create valid structured output:
output_schema
:
"type": "object"
)ToolResult
)ToolResult
object:
ToolResult
:
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:
mask_error_details=True
parameter when creating your FastMCP
instance:ToolError
to explicitly control what error information is sent to clients:mask_error_details=True
, only error messages from ToolError
will include details, other exceptions will be converted to a generic message.
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:
annotations
parameter in the @mcp.tool
decorator:
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 |
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.
Context
object. To use it, add a parameter to your tool function with the type hint Context
.
ctx.debug()
, ctx.info()
, ctx.warning()
, ctx.error()
ctx.report_progress(progress, total)
ctx.read_resource(uri)
ctx.sample(...)
ctx.request_id
, ctx.client_id
int
, FastMCP will attempt to convert it to an integer. If the conversion is not possible, FastMCP will return a validation error.
int
.
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 objectslist[T]
- Ordered sequence of itemsdict[K, V]
- Key-value mappingset[T]
- Unordered collection of unique itemstuple[T1, T2, ...]
- Fixed-length sequence with potentially different typesstr | int
) is preferred over older Union[str, int]
forms. Similarly, str | None
is preferred over Optional[str]
.
Color.RED
)bytes
, FastMCP will:
Path
type from the pathlib
module can be used for file system paths:
Path
object.
UUID
type from the uuid
module can be used for unique identifiers:
UUID
object.
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
:
Field
as a default value, though the Annotated
approach is preferred:
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) |
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.
"warn"
(default): Logs a warning and the new tool replaces the old one."error"
: Raises a ValueError
, 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.New in version: 2.3.4
You can dynamically remove tools from a server using the remove_tool
method: