@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 Component Visibility for the recommended approach.
New in version
2.13.0Optional list of icon representations for this resource or template. See Icons for detailed examplesAn optional
Annotations object or dictionary to add additional metadata about the resource.New in version
2.11.0Optional 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.New in version
3.0.0Optional version identifier for this resource. See Versioning for details.Using with Methods
For decorating instance or class methods, use the standalone@resource decorator and register the bound method. See Tools: Using with Methods for the pattern.
Return Values
Resource functions must return one of three types:str: Sent asTextResourceContents(withmime_type="text/plain"by default).bytes: Base64 encoded and sent asBlobResourceContents. You should specify an appropriatemime_type(e.g.,"image/png","application/octet-stream").ResourceResult: Full control over contents, MIME types, and metadata. See ResourceResult below.
To return structured data like dicts or lists, serialize them to JSON strings using
json.dumps(). This explicit approach ensures your type checker catches errors during development rather than at runtime when a client reads the resource.ResourceResult
New in version3.0.0
ResourceResult gives you explicit control over resource responses: multiple content items, per-item MIME types, and metadata at both the item and result level.
ResourceContent accepts three fields:
content - The actual resource content. Can be str (text content) or bytes (binary content). This is the data that will be returned to the client.
mime_type - Optional MIME type for the content. Defaults to "text/plain" for string content and "application/octet-stream" for binary content.
meta - Optional metadata dictionary that will be included in the MCP response’s meta field. Use this for runtime metadata like Content Security Policy headers, caching hints, or other client-specific data.
For simple cases, you can pass str or bytes directly to ResourceResult:
ResourceResult
ResourceContent
The content data. Strings and bytes pass through directly. Other types (dict, list, BaseModel) are automatically JSON-serialized.
MIME type. Defaults to
text/plain for strings, application/octet-stream for bytes, application/json for serialized objects.Item-level metadata for this specific content.
Component Visibility
New in version3.0.0
You can control which resources are enabled for clients using server-level enabled control. Disabled resources don’t appear in list_resources and can’t be read.
Accessing MCP Context
New in version2.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 Resources
FastMCP supports bothasync def and regular def resource functions. Synchronous functions automatically run in a threadpool to avoid blocking the event loop.
For I/O-bound operations, async functions are more efficient:
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).
Custom Resource Keys
New in version2.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.
Notifications
New in version2.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.
Annotations
New in version2.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:
- 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:
| 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 |
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://jlowin/fastmcp/info→ Returns info about the jlowin/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
New in version2.2.4
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.
- 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
Query Parameters
New in version2.13.0
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
New in version2.2.0
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/[email protected]→ Looks up user by email (with name=None)users://name/Bob→ Looks up user by name (with email=None)
Error Handling
New in version2.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=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
New in version2.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 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.
Versioning
New in version3.0.0
Resources and resource templates support versioning, allowing you to maintain multiple implementations under the same URI while clients automatically receive the highest version. See Versioning for complete documentation on version comparison, retrieval, and migration patterns.
