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 FlashMCP needs to generate a complete parameter schema for the MCP protocol, which isn’t possible with variable argument lists.Field
class with Annotated
. This approach is preferred as it’s more modern and keeps type hints separate from validation rules:
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 omittedType 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 |
query
parameter, while max_results
, sort_by
, and category
will use their default values if not explicitly provided.
@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.def
) and asynchronous (async def
) functions as tools.
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.
str
: Sent as TextContent
.dict
, list
, Pydantic BaseModel
: Serialized to a JSON string and sent as TextContent
.bytes
: Base64 encoded and sent as BlobResourceContents
(often within an EmbeddedResource
).FlashMCP.Image
: A helper class for easily returning image data. Sent as ImageContent
.None
: Results in an empty response (no content is sent back to the client).New in version: 2.3.4
If your tool encounters an error, you can raise a standard Python exception (ValueError
, TypeError
, FileNotFoundError
, custom exceptions, etc.) or a FlashMCP ToolError
.
In all cases, the exception is logged and converted into an MCP error response to be sent back to the client LLM. For security reasons, the error message is not included in the response by default. However, if you raise a ToolError
, the contents of the exception are included in the response. This allows you to provide informative error messages to the client LLM on an opt-in basis, which can help the LLM understand failures and react appropriately.
New in version: 2.2.7
FlashMCP 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 |
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
, FlashMCP will attempt to convert it to an integer. If the conversion is not possible, FlashMCP 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
, FlashMCP 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 FlashMCP 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 FlashMCP
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:
New in version: 2.2.10
FlashMCP 1.0 and < 2.2.10 relied on a crutch that attempted to work around LLM limitations by automatically parsing stringified JSON in tool arguments (e.g., converting "[1,2,3]"
to [1,2,3]
). As of FlashMCP 2.2.10, this behavior is disabled by default because it circumvents type validation and can lead to unexpected type coercion issues (e.g. parsing “true” as a bool and attempting to call a tool that expected a string, which would fail type validation).
Most modern LLMs correctly format JSON, but if working with models that unnecessarily stringify JSON (as was the case with Claude Desktop in late 2024), you can re-enable this behavior on your server by setting the environment variable FASTMCP_TOOL_ATTEMPT_PARSE_JSON_ARGS=1
.
We strongly recommend leaving this disabled unless necessary.