Expose data sources and dynamic content generators to your MCP client.
@mcp.resource
decorator.
@resource
Decorator@resource
is the unique URI (e.g., "resource://greeting"
) clients use to request this data.get_greeting
, get_config
) is only executed when a client specifically requests that resource URI via resources/read
.get_greeting
).@mcp.resource
decorator:
text/plain
or application/json
, but explicit is better for non-text typesAnnotations
object or dictionary to add additional metadata about the resource.New in version: 2.11.0
Optional meta information about the resource. This data is passed through to the MCP client as the _meta
field of the client-side resource object and can be used for custom metadata, versioning, or other application-specific purposes.str
: Sent as TextResourceContents
(with mime_type="text/plain"
by default).dict
, list
, pydantic.BaseModel
: Automatically serialized to a JSON string and sent as TextResourceContents
(with mime_type="application/json"
by default).bytes
: Base64 encoded and sent as BlobResourceContents
. You should specify an appropriate mime_type
(e.g., "image/png"
, "application/octet-stream"
).None
: Results in an empty resource content list being returned.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:
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
:
async def
for resource functions that perform I/O operations (e.g., reading from a database or network) to avoid blocking the server.
@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.
TextResource
: For simple string content.BinaryResource
: For raw bytes
content.FileResource
: Reads content from a local file path. Handles text/binary modes and lazy reading.HttpResource
: Fetches content from an HTTP(S) URL (requires httpx
).DirectoryResource
: Lists files in a local directory (returns JSON).FunctionResource
: Internal class used by @mcp.resource
).New in version: 2.2.0
When adding resources directly with mcp.add_resource()
, you can optionally provide a custom storage key:
add_resource()
directly and not through the @resource
decorator, as URIs are provided explicitly when using the decorator.
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.
New in version: 2.11.0
FastMCP allows you to add specialized metadata to your resources through annotations. These annotations communicate how resources behave to client applications without consuming token context in LLM prompts.
Annotations serve several purposes in client applications:
annotations
parameter in the @mcp.resource
decorator:
Annotation | Type | Default | Purpose |
---|---|---|---|
readOnlyHint | boolean | true | Indicates if the resource only provides data without side effects |
idempotentHint | boolean | true | Indicates if repeated reads have the same effect as a single read |
@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, annotations), 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.
*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.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 repositoryNew in version: 2.2.4
{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.
New in version: 2.2.0
When creating resource templates, FastMCP enforces two rules for the relationship between URI template parameters and function parameters:
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.
You can also create multiple resource templates that provide different ways to access the same underlying data by manually applying decorators to a single function:
users://email/alice@example.com
→ Looks up user by email (with name=None)users://name/Bob
→ Looks up user by name (with email=None)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:
mask_error_details=True
parameter when creating your FastMCP
instance:ResourceError
to explicitly control what error information is sent to clients:mask_error_details=True
, only error messages from ResourceError
will include details, other exceptions will be converted to a generic message.
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.
"warn"
(default): Logs a warning, and the new resource/template replaces the old one."error"
: Raises a ValueError
, 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.