@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.
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.
- URI: The first argument to
@resourceis 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 typesA set of strings used to categorize the resource. These can be used by the server and, in some cases, by clients to filter or group available resources.
A boolean to enable or disable the resource. See Disabling Resources for more information
Optional list of icon representations for this resource or template. See Icons for detailed examples
An optional
Annotations object or dictionary to add additional metadata about the resource.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.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
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 theenabled parameter in the decorator:
Accessing MCP Context
Resources and resource templates can access additional MCP information and features through theContext object. To access it, add a parameter to your resource function with a type annotation of Context:
Async Resources
Useasync 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.
TextResource: For simple string content.BinaryResource: For rawbytescontent.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).
Notifications
FastMCP automatically sendsnotifications/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.
Annotations
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:- Indicating whether resources are read-only or may have side effects
- Describing the safety profile of resources (idempotent vs. non-idempotent)
- Helping clients optimize caching and access patterns
annotations parameter in the @mcp.resource decorator:
Remember that annotations help make better user experiences but should be treated as advisory hints. They help client applications present appropriate UI elements and optimize access patterns, but won’t enforce behavior on their own. Always focus on making your annotations accurately represent what your resource actually does.
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, 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.
Here is a complete example that shows how to define two resource templates:
weather://london/current→ Returns weather for Londonweather://paris/current→ Returns weather for Parisrepos://PrefectHQ/fastmcp/info→ Returns info about the PrefectHQ/fastmcp repositoryrepos://prefecthq/prefect/info→ Returns info about the prefecthq/prefect repository
RFC 6570 URI Templates
FastMCP implements RFC 6570 URI Templates for resource templates, providing a standardized way to define parameterized URIs. This includes support for simple expansion, wildcard path parameters, and form-style query parameters.Wildcard Parameters
Resource templates support wildcard parameters that can match multiple path segments. Standard parameters ({param}) match a single URI segment before decoding and do not cross literal ”/” boundaries in the request URI. 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.
- 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
Filesystem Path Safety
Template parameters are decoded before your function receives them. A standard{filename} parameter matches one URI segment before decoding, so a request like files://a%2Fb passes filename="a/b" to the handler. Treat template values as untrusted decoded URI data whenever they determine filesystem paths.
Validate the final resolved path against an allowed root before reading:
{path*}) for resources whose URI shape intentionally includes slashes, and apply the same containment check before accessing the filesystem.
Query Parameters
FastMCP supports RFC 6570 form-style query parameters using the{?param1,param2} syntax. Query parameters provide a clean way to pass optional configuration to resources without cluttering the path.
Query parameters must be optional function parameters (have default values), while path parameters map to required function parameters. This enforces a clear separation: required data goes in the path, optional configuration in query params.
data://123→ Uses default format"json"data://123?format=xml→ Uses format"xml"api://users?version=2&limit=50→version=2, limit=50, offset=0files://src/main.py?encoding=ascii&lines=50→ Custom encoding and line limit
int, float, bool, str).
Query parameters vs. hidden defaults:
Query parameters expose optional configuration to clients. To hide optional parameters from clients entirely (always use defaults), simply omit them from the URI template:
Template Parameter Rules
FastMCP enforces these validation rules when creating resource templates:- Required function parameters (no default values) must appear in the URI path template
- Query parameters (specified with
{?param}syntax) must be optional function parameters with default values - All URI template parameters (path and query) must exist as function parameters
- Included as query parameters (
{?param}) - clients can override via query string - Omitted from URI template - always uses default value, not exposed to clients
- Used in alternative path templates - enables multiple ways to access the same resource
users://email/alice@example.com→ Looks up user by email (with name=None)users://name/Bob→ Looks up user by name (with email=None)
Error Handling
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=Trueparameter when creating yourFastMCPinstance:
- Or use
ResourceErrorto 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.
Server Behavior
Duplicate Resources
You can configure how the FastMCP server handles attempts to register multiple resources or templates with the same URI. Use theon_duplicate_resources setting during FastMCP initialization.
"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.

