Sub topic 8
Exposing read-only data as resources
This chapter assumes you have built a FastMCP server with at least one tool, and that you know the session lifecycle and the stdio transport from earlier chapters. It also assumes basic familiarity with URIs and MIME types.
What a resource is
A resource is a piece of read-only content that a server publishes under a URI. Examples are a runbook, a service catalog, a config file, or a database schema. The client reads the content with a resources/read request. Reading a resource should not change anything on the server's side.
The three server features differ mainly in who decides when they are used:
| Feature | Controlled by | Typical use |
|---|---|---|
| Tool | The model | Actions and lookups that need arguments or have effects |
| Resource | The host application | Context that is loaded into the conversation |
| Prompt | The user | Reusable instructions the user picks explicitly |
"Application-controlled" means the host decides how resources are used. It might show a picker so the user can attach a runbook to the chat. It might also load a resource automatically, or let the model read one through a bridging tool. The protocol does not force one behavior, so you cannot assume a model will fetch a resource on its own. Hosts differ here, so test with the host your team uses.
Choosing between a resource and a tool
Use a resource when the data has a stable address, needs no real arguments, and is safe to read repeatedly. Use a tool when the call computes something from inputs, talks to a live system, or has side effects.
Some examples:
- A runbook for the billing service is a resource:
runbook://billing. - "Restart the billing worker" is a tool, because it changes state.
- "Which team owns service X?" can be either. If the answer is a small table, publish it as a resource. If the lookup needs a filter, use a tool.
If you are unsure, ask whether the host would reasonably want to show this content to the user before the model sees it. If so, make it a resource.
The protocol surface
A server that publishes resources declares the resources capability during initialization. FastMCP does this for you when you register a resource. The capability can also advertise two optional flags:
subscribe: the client can ask to be notified when a specific resource changes.listChanged: the server notifies the client when the set of available resources changes.
Three requests matter in day-to-day work:
resources/listreturns concrete resources: name, URI, description, and MIME type.resources/templates/listreturns URI templates such asrunbook://{service}.resources/readtakes a URI and returns its contents.
A read response contains a contents array. Each item has the URI, a MIME type, and either text or a base64 blob for binary data:
{
"contents": [
{
"uri": "runbook://billing",
"mimeType": "text/markdown",
"text": "1. Check the queue depth.\n2. Restart the worker.\n3. Page payments-team."
}
]
}Static resources and resource templates
A static resource has one fixed URI. A resource template has placeholders in braces, and the client fills them in to form a concrete URI. In FastMCP, the decorator decides which kind you get. If the URI contains {name} placeholders, FastMCP registers a template. In that case the function parameters must match the placeholder names exactly.
This example publishes one static resource and one template:
import json
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("team-tools")
SERVICES = {
"billing": {"owner": "payments-team", "tier": 1},
"search": {"owner": "discovery-team", "tier": 2},
}
RUNBOOKS = {
"billing": (
"# Billing runbook\n\n"
"1. Check the queue depth.\n"
"2. Restart the worker.\n"
"3. Page payments-team.\n"
),
"search": (
"# Search runbook\n\n"
"1. Check index freshness.\n"
"2. Page discovery-team.\n"
),
}
@mcp.resource("catalog://services", mime_type="application/json")
def service_catalog() -> str:
"""All services with their owning team and support tier."""
return json.dumps(SERVICES, indent=2)
@mcp.resource("runbook://{service}", mime_type="text/markdown")
def runbook(service: str) -> str:
"""Runbook text for one service."""
if service not in RUNBOOKS:
raise ValueError(f"No runbook for service: {service}")
return RUNBOOKS[service]
if __name__ == "__main__":
mcp.run()Three details matter here:
- The
mime_typetells the host how to render or parse the text. Set it deliberately. Without it, FastMCP defaults totext/plain, and a host that expects JSON will not treat your catalog as JSON. - The docstring becomes the resource description. Write it for someone choosing what to attach to a conversation.
- Raising an exception for an unknown key makes the read fail with an error. This is better than returning a placeholder string such as "not found", because a placeholder looks like real content to the model.
A template does not appear in resources/list. A host only discovers it through resources/templates/list. If you want specific runbooks to show up in a picker, you can also register static resources for the important ones.
Serving files safely
A common use is serving documents from a directory. This is also where the most common mistake happens. The URI parameter comes from the client, so treat it as untrusted input, the same as a tool argument.
from pathlib import Path
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("team-docs")
DOCS_ROOT = (Path(__file__).parent / "docs").resolve()
@mcp.resource("doc://{name}", mime_type="text/markdown")
def doc(name: str) -> str:
"""A team document from the docs directory, by name without extension."""
path = (DOCS_ROOT / f"{name}.md").resolve()
if not path.is_relative_to(DOCS_ROOT):
raise ValueError("Invalid document name")
if not path.is_file():
raise ValueError(f"No such document: {name}")
return path.read_text(encoding="utf-8")
if __name__ == "__main__":
mcp.run()The function resolves the final path and checks that it still sits inside DOCS_ROOT. This blocks names that use .. or symlinks to escape the directory. By default a template placeholder matches a single path segment, so a slash cannot appear in name. Do not rely on that alone. The explicit check is the control you can audit.
Returning structured data and binary content
If a function returns something other than str or bytes, FastMCP serializes it to JSON text. Returning a dict therefore works, but the explicit json.dumps in the earlier example keeps the formatting under your control. For binary content such as a PDF or an image, return bytes and set an accurate MIME type, for example application/pdf. The server sends it as a base64 blob. Many hosts cannot display binary resources, so prefer text formats for team documentation.
Keep resources reasonably small. The host may place the whole content into the model's context window. A 2 MB log file published as a resource is expensive and mostly noise. If a source is large, expose a template that selects a slice, such as logs://{service}/{date}, or make it a tool with a limit parameter.
Keeping content current
Resource content is read on demand, so each resources/read can return fresh data. If the data lives in a file or database, read it inside the function and not at import time. Otherwise the server serves stale data until you restart it.
Change notifications are a separate matter. A host that has already loaded a resource only learns about new content if the server supports listChanged or subscribe and the host acts on those notifications. Many hosts ignore them. For a team server, a safe default is to design for re-reading: assume content is fetched when needed and may be re-fetched.
Testing resources with the Inspector
Start the Inspector against your script:
npx @modelcontextprotocol/inspector python server.pyOpen the Resources tab. Check four things:
- The static resource appears in the resource list with the right MIME type.
- The template appears under the templates list.
- Reading
runbook://billingreturns the expected text. - Reading
runbook://unknownreturns an error and the server keeps running.
Run the same checks for hostile input such as doc://..%2F..%2Fetc%2Fpasswd, and confirm the error path rejects it.
Common errors
- Placeholder and parameter names differ.
@mcp.resource("runbook://{service}")withdef runbook(name: str)fails at registration. The names must match. - Writing to stdout. With the stdio transport, a stray
printcorrupts the protocol stream. Log to stderr, as set up in earlier chapters. - Expecting the model to browse resources. Whether and how a model reaches resources depends on the host. If your workflow needs the model to fetch a runbook by itself, also offer a small read-only tool, or confirm that your host supports it.
- Using resources for actions. A read that triggers a restart, a ticket, or a write breaks the contract that reads are safe to repeat. Make it a tool.
Exercise
Your team wants two things from the server: (1) the on-call handbook, which is a fixed Markdown document, and (2) a way to page the on-call engineer for a service. Which MCP feature fits each, and why? Also name one check you would add if the handbook were loaded from a file path built from a URI parameter.
Show answer
The handbook is a read-only, addressable document with no arguments, so it should be a resource, for example a static resource at handbook://oncall with mimetype text/markdown. Paging an engineer has a side effect and takes an argument (the service), so it should be a tool, ideally with user confirmation. If the handbook path is built from a URI parameter, resolve the final path and verify it is inside the allowed root directory (for example with isrelative_to), and reject names that do not map to an existing file, so the parameter cannot escape the directory.