Resources & Templates
Expose data sources and dynamic content generators to your MCP client.
Resources represent data or files that an MCP client can read, and resource templates extend this concept by allowing clients to request dynamically generated resources based on parameters passed in the URI.
FastMCP simplifies defining both static and dynamic resources, primarily using the @mcp.resource
decorator.
What Are Resources?
Resources provide read-only access to data for the LLM or client application. When a client requests a resource URI:
- FastMCP finds the corresponding resource definition.
- If it’s dynamic (defined by a function), the function is executed.
- The content (text, JSON, binary data) is returned to the client.
This allows LLMs to access files, database content, configuration, or dynamically generated information relevant to the conversation.
Resources
The @resource
Decorator
The most common way to define a resource is by decorating a Python function. The decorator requires the resource’s unique URI.
Key Concepts:
- URI: The first argument to
@resource
is the unique URI (e.g.,"resource://greeting"
) clients use to request this data. - Lazy Loading: The decorated function (
get_greeting
,get_config
) is only executed when a client specifically requests that resource URI viaresources/read
. - Inferred Metadata: By default:
- Resource Name: Taken from the function name (
get_greeting
). - Resource Description: Taken from the function’s docstring.
- Resource Name: Taken from the function name (
Decorator Arguments
You can customize the resource’s properties using arguments in the @mcp.resource
decorator:
@resource Decorator Arguments
The unique identifier for the resource
A human-readable name. If not provided, defaults to function name
Explanation of the resource. If not provided, defaults to docstring
Specifies the content type. FastMCP often infers a default like text/plain
or application/json
, but explicit is better for non-text types
A set of strings for categorization, potentially used by clients for filtering
A boolean to enable or disable the resource. See Disabling Resources for more information
Return Values
FastMCP automatically converts your function’s return value into the appropriate MCP resource content:
str
: Sent asTextResourceContents
(withmime_type="text/plain"
by default).dict
,list
,pydantic.BaseModel
: Automatically serialized to a JSON string and sent asTextResourceContents
(withmime_type="application/json"
by default).bytes
: Base64 encoded and sent asBlobResourceContents
. You should specify an appropriatemime_type
(e.g.,"image/png"
,"application/octet-stream"
).None
: Results in an empty resource content list being returned.
Disabling Resources
New in version: 2.8.0
You can control the visibility and availability of resources and templates by enabling or disabling them. Disabled resources will not appear in the list of available resources or templates, and attempting to read a disabled resource will result in an “Unknown resource” error.
By default, all resources are enabled. You can disable a resource upon creation using the enabled
parameter in the decorator:
You can also toggle a resource’s state programmatically after it has been created:
Accessing MCP Context
New in version: 2.2.5
Resources and resource templates can access additional MCP information and features through the Context
object. To access it, add a parameter to your resource function with a type annotation of Context
:
For full documentation on the Context object and all its capabilities, see the Context documentation.
Async Resources
Use async def
for resource functions that perform I/O operations (e.g., reading from a database or network) to avoid blocking the server.
Resource Classes
While @mcp.resource
is ideal for dynamic content, you can directly register pre-defined resources (like static files or simple text) using mcp.add_resource()
and concrete Resource
subclasses.
Common Resource Classes:
TextResource
: For simple string content.BinaryResource
: For rawbytes
content.FileResource
: Reads content from a local file path. Handles text/binary modes and lazy reading.HttpResource
: Fetches content from an HTTP(S) URL (requireshttpx
).DirectoryResource
: Lists files in a local directory (returns JSON).- (
FunctionResource
: Internal class used by@mcp.resource
).
Use these when the content is static or sourced directly from a file/URL, bypassing the need for a dedicated Python function.
Custom Resource Keys
New in version: 2.2.0
When adding resources directly with mcp.add_resource()
, you can optionally provide a custom storage key:
Note that this parameter is only available when using add_resource()
directly and not through the @resource
decorator, as URIs are provided explicitly when using the decorator.
Notifications
New in version: 2.9.1
FastMCP automatically sends notifications/resources/list_changed
notifications to connected clients when resources or templates are added, enabled, or disabled. This allows clients to stay up-to-date with the current resource 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 resource lists or update their interfaces.
Resource Templates
Resource Templates allow clients to request resources whose content depends on parameters embedded in the URI. Define a template using the same @mcp.resource
decorator, but include {parameter_name}
placeholders in the URI string and add corresponding arguments to your function signature.
Resource templates share most configuration options with regular resources (name, description, mime_type, tags), but add the ability to define URI parameters that map to function parameters.
Resource templates generate a new resource for each unique set of parameters, which means that resources can be dynamically created on-demand. For example, if the resource template "user://profile/{name}"
is registered, MCP clients could request "user://profile/ford"
or "user://profile/marvin"
to retrieve either of those two user profiles as resources, without having to register each resource individually.
Functions with *args
are not supported as resource templates. However, unlike tools and prompts, resource templates do support **kwargs
because the URI template defines specific parameter names that will be collected and passed as keyword arguments.
Here is a complete example that shows how to define two resource templates:
With these two templates defined, clients can request a variety of resources:
weather://london/current
→ Returns weather for Londonweather://paris/current
→ Returns weather for Parisrepos://jlowin/fastmcp/info
→ Returns info about the jlowin/fastmcp repositoryrepos://prefecthq/prefect/info
→ Returns info about the prefecthq/prefect repository
Wildcard Parameters
New in version: 2.2.4
Please note: FastMCP’s support for wildcard parameters is an extension of the Model Context Protocol standard, which otherwise follows RFC 6570. Since all template processing happens in the FastMCP server, this should not cause any compatibility issues with other MCP implementations.
Resource templates support wildcard parameters that can match multiple path segments. While standard parameters ({param}
) only match a single path segment and don’t cross ”/” boundaries, wildcard parameters ({param*}
) can capture multiple segments including slashes. Wildcards capture all subsequent path segments up until the defined part of the URI template (whether literal or another parameter). This allows you to have multiple wildcard parameters in a single URI template.
Wildcard parameters are useful when:
- Working with file paths or hierarchical data
- Creating APIs that need to capture variable-length path segments
- Building URL-like patterns similar to REST APIs
Note that like regular parameters, each wildcard parameter must still be a named parameter in your function signature, and all required function parameters must appear in the URI template.
Default Values
New in version: 2.2.0
When creating resource templates, FastMCP enforces two rules for the relationship between URI template parameters and function parameters:
- Required Function Parameters: All function parameters without default values (required parameters) must appear in the URI template.
- URI Parameters: All URI template parameters must exist as function parameters.
However, function parameters with default values don’t need to be included in the URI template. When a client requests a resource, FastMCP will:
- Extract parameter values from the URI for parameters included in the template
- Use default values for any function parameters not in the URI template
This allows for flexible API designs. For example, a simple search template with optional parameters:
With this template, clients can request search://python
and the function will be called with query="python", max_results=10, include_archived=False
. MCP Developers can still call the underlying search_resources
function directly with more specific parameters.
An even more powerful pattern is registering a single function with multiple URI templates, allowing different ways to access the same data:
Now an LLM or client can retrieve user information in two different ways:
users://email/alice@example.com
→ Looks up user by email (with name=None)users://name/Bob
→ Looks up user by name (with email=None)
In this stacked decorator pattern:
- The
name
parameter is only provided when using theusers://name/{name}
template - The
email
parameter is only provided when using theusers://email/{email}
template - Each parameter defaults to
None
when not included in the URI - The function logic handles whichever parameter is provided
Templates provide a powerful way to expose parameterized data access points following REST-like principles.
Error Handling
New in version: 2.4.1
If your resource function encounters an error, you can raise a standard Python exception (ValueError
, TypeError
, FileNotFoundError
, custom exceptions, etc.) or a FastMCP ResourceError
.
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
ResourceError
to explicitly control what error information is sent to clients:
When mask_error_details=True
, only error messages from ResourceError
will include details, other exceptions will be converted to a generic message.
Server Behavior
Duplicate Resources
New in version: 2.1.0
You can configure how the FastMCP server handles attempts to register multiple resources or templates with the same URI. Use the on_duplicate_resources
setting during FastMCP
initialization.
The duplicate behavior options are:
"warn"
(default): Logs a warning, and the new resource/template replaces the old one."error"
: Raises aValueError
, preventing the duplicate registration."replace"
: Silently replaces the existing resource/template with the new one."ignore"
: Keeps the original resource/template and ignores the new registration attempt.