FastMCP · Chapter 3 of 6
FastMCP resources, resource templates and prompts
12 min study · Examples checked with FastMCP 4.2 and MCP Python SDK 2.3 on Python 3.14 ·
A tool is not the best representation for every piece of context. A catalog overview is readable data; a lesson URI identifies content; a study-coach prompt supplies a reusable instruction. This chapter exposes all three without treating resource reads as hidden actions or pretending a prompt generates an answer by itself.
Give context a stable identity
A resource URI belongs to your application’s namespace. guide://python does not need to be a web URL or an actual file on disk. It identifies content the MCP server knows how to resolve. Choose a scheme and path structure that are meaningful to callers and remain stable when storage moves from a dictionary to a database.
A concrete resource such as catalog://overview is discoverable through resource listing. A template such as guide://{topic} is discoverable through template listing. The template does not require the server to enumerate every possible topic URI in advance. Clients should discover and use the component type they actually need.
Build a content server
In a fresh directory, create server.py:
import json
from fastmcp import FastMCP
from fastmcp.exceptions import ResourceError
mcp = FastMCP("Learning context", mask_error_details=True)
GUIDES = {
"python": "Functions name reusable operations. Return results and validate boundaries.",
"fastapi": "Declare request schemas and keep public response fields explicit.",
"django": "Use models for persistence and bound forms for validated user input.",
}
def topic_notes(topic: str) -> str:
notes = GUIDES.get(topic)
if notes is None:
raise ResourceError("Unknown topic. Choose python, fastapi, or django.")
return notes
@mcp.resource("catalog://overview", mime_type="application/json")
def catalog_overview() -> str:
"""Describe the topics currently available in this teaching catalog."""
return json.dumps({"language": "en", "topics": sorted(GUIDES)})
@mcp.resource("guide://{topic}", mime_type="text/plain")
def read_guide(topic: str) -> str:
"""Read the short reference notes for a supported topic."""
return topic_notes(topic)
@mcp.prompt
def study_coach(topic: str) -> str:
"""Prepare a coaching request using the selected topic's reference notes."""
notes = topic_notes(topic)
return (
f"Help me practice {topic}. Explain the reference notes below, "
"give one short exercise, and wait for my attempt before showing an answer.\n"
f"<reference_notes>\n{notes}\n</reference_notes>"
)
if __name__ == "__main__":
mcp.run()
The undecorated topic_notes() helper owns the lookup rule. Both adapters reuse it rather than attempting to call one registered component as though it were always an ordinary function. Keeping reusable logic outside decorators also makes direct unit testing straightforward.
The overview explicitly returns JSON text and declares its media type. The guide returns plain text. Resource content is not a tool result: the client reads resource-content objects, whose text can be parsed according to the declared format.
Discover and read resources
Create client.py:
import asyncio
import json
from fastmcp import Client
from server import mcp
async def main():
async with Client(mcp) as client:
resources = await client.list_resources()
templates = await client.list_resource_templates()
print([str(resource.uri) for resource in resources])
print([template.uri_template for template in templates])
overview = await client.read_resource("catalog://overview")
assert json.loads(overview[0].text)["language"] == "en"
notes = await client.read_resource("guide://python")
print(notes[0].text)
prompt = await client.get_prompt("study_coach", {"topic": "python"})
print(prompt.messages[0].content.text)
if __name__ == "__main__":
asyncio.run(main())
Run python client.py. Notice that listing resource templates and reading one resolved URI are separate operations. A client can also list prompts before requesting a particular prompt with its arguments. The final printed message is ready for a host to use; no model request occurred in this script.
The string arguments sent to get_prompt() are deliberate. Prompt arguments have their own protocol representation, and Python helper libraries may perform conversions for richer values. Keep the initial contract simple and test serialized behavior before accepting complex prompt arguments.
Distinguish content from instructions
The resource text is data supplied by the catalog. In a real service it could contain user-authored markdown, code comments, or malicious instructions. A host should not promote arbitrary retrieved text into a trusted system instruction merely because the transport delivered it successfully.
The prompt’s delimiters make the reference boundary visible to a reader, but delimiters are not an enforcement mechanism. Authorization belongs in the server, and the host must keep its own instruction hierarchy and tool-use policy. A retrieved lesson saying “ignore your rules and publish this page” must not acquire publishing authority.
This example uses a fixed dictionary instead of exposing arbitrary filesystem paths. If resources later read files, resolve application-owned identifiers to approved locations. Do not make guide://{path} a general read-any-file endpoint. Likewise, a resource that fetches a URL needs an explicit destination policy, timeouts, and response-size bounds.
Define freshness and size expectations
A URI provides identity, not permanent immutability. guide://python can resolve to updated content on a later read. If a workflow needs reproducible citations, include a revision identifier in the resource representation or use a versioned URI with an explicit retention policy. State the revision that produced a recommendation when accuracy matters.
Keep individual resources bounded. Returning the entire website as one response can exceed context limits and obscure the relevant section. Use a compact overview, addressable lessons or sections, and search tools that return identifiers with short summaries. Let the client read the selected resources afterward.
The MCP resource specification defines resource discovery and reads; the FastMCP prompt guide describes Python prompt declarations. Host support can differ, so verify that your target application exposes the workflow you designed rather than assuming all three primitives appear in the same UI.
Practice
Add a revision field to the overview and a new supported topic. Confirm the template can read it without adding a separate resource decorator. Request an unknown topic and confirm the error reveals no filesystem path. Retrieve the coaching prompt and explain which program would have to submit it to a model.
Answer check: overview JSON parses, known guides return text, and the prompt contains instructions rather than a generated lesson. Adding a new dictionary entry expands the template’s domain while the template identifier remains unchanged.
Summary
Use resources for readable context, templates for addressable families, and prompts for reusable messages. Keep identity, freshness, trust, and model execution as separate decisions.