FastMCP: Serving Resources
Relevant source files
The following files were used as context for generating this wiki page:
src/mcp/server/fastmcp/resources/base.pysrc/mcp/server/fastmcp/resources/resource_manager.pyexamples/servers/simple-resource/mcp_simple_resource/server.pyexamples/snippets/servers/images.pytests/server/fastmcp/test_server.pytests/server/fastmcp/servers/test_file_server.pytests/server/fastmcp/resources/test_function_resources.pytests/server/fastmcp/resources/test_resource_manager.pytests/server/fastmcp/test_integration.py
The FastMCP framework provides a powerful system for exposing data and functionality to clients as "resources." These resources are identified by a URI and can be discovered, listed, and read by clients. This system is designed to be flexible, supporting everything from static files to dynamically generated content from Python functions.
The core of the resource system revolves around the ResourceManager, which manages a collection of Resource objects. Developers can define resources using decorators on functions or by instantiating resource classes directly. The framework also supports resource templates, allowing for the creation of dynamic resources based on parameters in the URI.
Core Components
The resource system is comprised of several key classes that work together to register, manage, and serve resources.
ResourceManager
The ResourceManager is the central hub for all resources within a FastMCP server. It is responsible for registering, retrieving, and listing both static resources and resource templates.
This diagram shows the main interactions with the ResourceManager.
Key Responsibilities:
- Registration: Adds
Resourceobjects andResourceTemplateobjects to the server's registry. - Listing: Provides lists of available resources and resource templates to clients.
- Retrieval: Fetches a specific resource by its URI. If the URI matches a template, it instantiates a concrete
Resourceobject on the fly. - Duplicate Handling: By default, it logs a warning when a resource with an existing URI is added again. This can be disabled.
Sources: src/mcp/server/fastmcp/resources/resource_manager.py, tests/server/fastmcp/resources/test_resource_manager.py:27-35, 80-87
Resource Types
FastMCP provides several concrete Resource implementations. The two primary types are FunctionResource and FileResource.
| Resource Type | Description | Primary Use Case |
|---|---|---|
FunctionResource | A resource whose content is generated by executing a Python function. The return value of the function becomes the resource's content. | Serving dynamic or computed data. |
FileResource | A resource that represents a file on the local filesystem. Reading the resource returns the contents of the file. | Serving static files like text, configs, or logs. |
Sources: tests/server/fastmcp/resources/test_function_resources.py:10-23, tests/server/fastmcp/servers/test_file_server.py:38-52
This class diagram illustrates the basic structure of the resource classes.
Defining and Registering Resources
The most common way to define a resource is by using the @mcp.resource decorator on a function. This automatically creates and registers a FunctionResource.
Using the @mcp.resource Decorator
The @mcp.resource decorator transforms a Python function into a discoverable resource. The URI for the resource is a required argument to the decorator.
# From tests/server/fastmcp/test_server.py:166-172
mcp = FastMCP()
@mcp.resource("r://{x}")
def get_data(x: str) -> str:
return f"Data: {x}"
This registers a resource template. When a client requests r://some_value, the get_data function will be called with x="some_value".
It is crucial to use the decorator with parentheses, even if only the URI is provided. Incorrect usage will result in a TypeError.
# From tests/server/fastmcp/test_server.py:177-183
mcp = FastMCP()
with pytest.raises(TypeError, match="The @resource decorator was used incorrectly"):
@mcp.resource # Missing parentheses #type: ignore
def get_data(x: str) -> str:
return f"Data: {x}"
Sources: tests/server/fastmcp/test_server.py:164-183
FunctionResource In-Depth
A FunctionResource is highly versatile in how it handles return types from the decorated function.
str: Returned astext/plaincontent.bytes: Returned as binary content, typicallyapplication/octet-streamunless amime_typeis specified.pydantic.BaseModelordict: Automatically serialized to a JSON string and returned asapplication/json.- Other types: Converted to a string representation.
The FunctionResource can wrap both synchronous and asynchronous functions.
Sources: tests/server/fastmcp/resources/test_function_resources.py:26-66, 99-110
FileResource
FileResource is used to expose a file from the server's filesystem. It can be instantiated and added to the ResourceManager manually.
# From tests/server/fastmcp/test_server.py:700-707
mcp = FastMCP()
# Create a text file
text_file = tmp_path / "test.txt"
text_file.write_text("Hello from file!")
resource = FileResource(uri=AnyUrl("file://test.txt"), name="test.txt", path=text_file)
mcp.add_resource(resource)
The resource's content type is inferred from the file extension, but can be overridden by setting the mime_type parameter.
Sources: tests/server/fastmcp/test_server.py:700-724, tests/server/fastmcp/servers/test_file_server.py:38-52
Resource Templates
Resource templates allow for the creation of dynamic resources based on patterns in a URI. A template is defined by a URI containing placeholders, such as resource://{org}/{repo}/data.
When a client requests a URI that matches a template, FastMCP:
- Parses the parameters from the request URI (e.g.,
org="cursor"andrepo="fastmcp"). - Finds the corresponding
ResourceTemplate. - Instantiates a temporary
FunctionResourceby passing the parsed parameters to the template's function. - Calls the
read()method on the new resource to generate the content.
Defining a Template
A resource template is created automatically when the @mcp.resource decorator is used with a URI containing placeholders. The names of the placeholders in the URI must match the names of the arguments in the decorated function.
# From tests/server/fastmcp/test_server.py:796-800
mcp = FastMCP()
@mcp.resource("resource://{org}/{repo}/data")
def get_data(org: str, repo: str) -> str:
return f"Data for {org}/{repo}"
A ValueError will be raised if the URI parameters and function arguments do not match.
Sources: tests/server/fastmcp/test_server.py:760-768, 794-800
Template Resolution Flow
This diagram illustrates the process of a client reading a resource that matches a template.
Client Interaction
From a client's perspective, interacting with resources involves a few simple API calls.
initialize(): The client connects to the server and learns about its capabilities, including whether it supports resources.list_resources(): The client requests a list of all available static resources.list_resource_templates(): The client requests a list of all available resource templates.read_resource(uri): The client requests the content of a specific resource by its URI.
This flow is demonstrated in integration tests, where a client connects to a server and reads various resources.
# Based on tests/server/fastmcp/test_integration.py:228-251
async with ClientSession(read, write) as session:
# Test initialization
result = await session.initialize()
assert result.capabilities.resources is not None
# Test document resource
doc_content = await session.read_resource(AnyUrl("file://documents/readme"))
assert isinstance(doc_content, ReadResourceResult)
assert "Content of readme" in doc_content.contents[0].text
# Test settings resource (from a function)
settings_content = await session.read_resource(AnyUrl("config://settings"))
settings_json = json.loads(settings_content.contents[0].text)
assert settings_json["theme"] == "dark"
Sources: tests/server/fastmcp/test_integration.py:228-251, examples/servers/simple-resource/README.md
Summary
The resource system in FastMCP is a cornerstone feature for exposing server-side data to clients. It provides a unified interface for accessing both static content (via FileResource) and dynamic content (via FunctionResource). The use of the @mcp.resource decorator simplifies the process of creating resources from Python functions, while resource templates offer a powerful mechanism for generating a wide range of dynamic content from a single function definition. This flexible and extensible system allows developers to easily integrate data sources into their MCP servers.