Sub topic 7
Resources: context the application can read
This chapter assumes you have read the earlier chapters on roles, JSON-RPC messages, and session initialization. You should be able to read a JSON-RPC request and its response, and know what the initialize handshake does. Basic Python is enough for the code.
What a resource is
A resource is a piece of data that a server exposes and a client can read by URI. Examples are a file, a database row, a log, a page of documentation, or a generated report. A resource does not run anything. It returns content.
Resources differ from tools in who decides to use them. The MCP specification calls tools model-controlled and resources application-controlled. The host application decides which resources to read and when to put them in front of the model. A host might show a resource picker, attach a resource when the user drags it into the chat, or run its own search over the resource list. The protocol does not require any one of these. It only defines how to list and read.
| Primitive | Controlled by | Typical use |
|---|---|---|
| Tool | The model | Take an action or compute something |
| Resource | The application | Supply context to read |
| Prompt | The user | Start from a reusable template |
Choose a resource when the content is data that the application or user should be able to browse and attach. Choose a tool when the model must decide to fetch something on its own, or when the call has side effects or needs arguments. Many servers expose the same data both ways, as a resource for hosts that support attaching and as a read-only tool for hosts that only wire tools into the model.
Declaring the capability
A server that offers resources declares the resources capability in its initialize response. Two optional flags refine it:
subscribe: the client may subscribe to changes of an individual resource.listChanged: the server will send a notification when the set of available resources changes.
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2025-06-18",
"capabilities": {
"resources": {"subscribe": true, "listChanged": true}
},
"serverInfo": {"name": "notes", "version": "1.0.0"}
}
}A client must not send resources/* requests unless the server declared the capability. An empty object, "resources": {}, is valid and means resources are supported without either optional feature.
The message flow
Four request types cover the basics, and two notifications cover change tracking.
| Message | Direction | Purpose |
|---|---|---|
| `resources/list` | client to server | List concrete resources, with optional paging |
| `resources/templates/list` | client to server | List URI templates for parameterized resources |
| `resources/read` | client to server | Fetch the content of one URI |
| `resources/subscribe` | client to server | Ask to be told when one URI changes |
| `notifications/resources/updated` | server to client | One subscribed resource changed |
| `notifications/resources/list_changed` | server to client | The list itself changed |
Listing resources
A resources/list result contains an array of resource descriptors:
{
"jsonrpc": "2.0",
"id": 3,
"result": {
"resources": [
{
"uri": "notes://index",
"name": "index",
"title": "Note index",
"description": "All note ids, one per line",
"mimeType": "text/plain"
}
],
"nextCursor": "page-2"
}
}The fields mean the following:
uriidentifies the resource. It is the only field you pass back when reading.nameis a machine-friendly label.titleis the human-readable display name.descriptionandmimeTypehelp the host decide whether and how to show the content.size(optional) is the raw size in bytes, which hosts can use to estimate context cost.
If nextCursor is present, the list is paged. Send another resources/list with "params": {"cursor": "page-2"} until the field is absent. Treat the cursor as an opaque string.
Reading a resource
The request names a URI. The result holds a contents array, because one URI can resolve to several items, such as the files in a directory.
{"jsonrpc": "2.0", "id": 4, "method": "resources/read", "params": {"uri": "notes://index"}}{
"jsonrpc": "2.0",
"id": 4,
"result": {
"contents": [
{"uri": "notes://index", "mimeType": "text/plain", "text": "todo\nideas"}
]
}
}Each content item carries either text or blob, never both. Text content is a plain string. Binary content, such as an image or a PDF, is base64 text in blob, and mimeType tells the client how to decode it. A client that ignores mimeType will guess wrong, so check it before displaying anything.
URI schemes and templates
The URI is an identifier, and its scheme is a convention between server and host. The specification names a few: https:// for content the client could fetch itself, file:// for filesystem-like data, and git:// for version-control data. Servers are free to define custom schemes such as notes:// or db://. Hosts should not assume a custom scheme can be opened outside the server.
When the set of resources is large or computed, a server publishes a template instead of listing every item. Templates follow RFC 6570 URI template syntax:
{
"jsonrpc": "2.0",
"id": 5,
"result": {
"resourceTemplates": [
{
"uriTemplate": "notes://{note_id}",
"name": "note",
"description": "One note by id",
"mimeType": "text/plain"
}
]
}
}A client fills in the variable and calls resources/read with the resulting URI, such as notes://todo. Templates are why resources/list is not a complete catalog. A host that wants to offer "everything the server has" needs to read both lists.
A server with a static resource and a template
This server uses the Python SDK's FastMCP class. A decorator with no URI variables registers a concrete resource. A decorator with {note_id} in the URI registers a template, and the function parameter must have the same name.
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("notes")
NOTES = {
"todo": "Write the resources chapter.",
"ideas": "Try a subscription demo.",
}
@mcp.resource("notes://index", mime_type="text/plain")
def index() -> str:
"""List all note ids, one per line."""
return "\n".join(sorted(NOTES))
@mcp.resource("notes://{note_id}", mime_type="text/plain")
def get_note(note_id: str) -> str:
"""Return one note by id."""
if note_id not in NOTES:
raise ValueError(f"No note named {note_id!r}")
return NOTES[note_id]
if __name__ == "__main__":
mcp.run(transport="stdio")Save it as notes_server.py. The client below launches it, lists both kinds of resource, and reads one of each.
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from pydantic import AnyUrl
async def main():
params = StdioServerParameters(command="python", args=["notes_server.py"])
async with stdio_client(params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
listed = await session.list_resources()
print([str(r.uri) for r in listed.resources])
templates = await session.list_resource_templates()
print([t.uriTemplate for t in templates.resourceTemplates])
index = await session.read_resource(AnyUrl("notes://index"))
print(index.contents[0].text)
note = await session.read_resource(AnyUrl("notes://todo"))
print(note.contents[0].text)
asyncio.run(main())Expected output:
['notes://index']
['notes://{note_id}']
ideas
todo
Write the resources chapter.The index lists only notes://index, because notes://todo and notes://ideas are reachable only through the template.
Subscriptions and list changes
Resources can change while a session is open. MCP offers two separate mechanisms.
- List changes. If the server declared
listChanged, it sendsnotifications/resources/list_changedwhenever resources are added or removed. The client should callresources/listagain. - Content changes. If the server declared
subscribe, the client sendsresources/subscribewith a URI. When that resource changes, the server sendsnotifications/resources/updatedwith the URI. The notification carries no content. The client must callresources/readto get the new data.
The two are independent. A server may support one without the other. Because notifications carry no payload, a client that receives an update for a resource it no longer cares about can simply ignore it, or send resources/unsubscribe.
Common errors
- Reading before checking the capability. Calling
resources/readon a server that never declaredresourcesgives a method-not-found error. Check theinitializeresult first. - Missing resource. The specification suggests error code
-32002for a resource that does not exist. Many SDKs return a generic error instead, so handle any error response fromresources/read. - Template parameter mismatch. In
FastMCP, the URI variables and function parameters must match exactly. A mismatch fails at registration time, not on the first read. - Assuming the list is complete. Template-based resources never appear in
resources/list. - Treating
textandblobas interchangeable. Read whichever field is present, and decodeblobfrom base64 usingmimeType. - Expecting the content in an update notification. The notification only names the URI.
- Returning large content blindly. The host pays for every byte that reaches the model. Set
sizewhere you can, and split big data into several URIs.
Security notes
A resource URI is input from the client, so the server must validate it. A file:// server that joins the URI path onto a base directory without checks allows path traversal such as ../../etc/passwd. Resolve the path, confirm it is inside the allowed root, and refuse otherwise. Resource content can also contain text written by third parties, and hosts should treat it as untrusted data, not as instructions. Hosts should ask for user consent before sending sensitive resources to a model.
Exercise
A server declares "resources": {"listChanged": true} but not subscribe. The client has read notes://todo, and later the note text changes on the server. Which notification could the server send, and what must the client do to see the change?
Show answer
The server cannot send notifications/resources/updated, because that depends on the subscribe capability and the client could not have subscribed. list_changed only reports that the set of resources changed, which is not the case here. The client has no push signal for content changes and must call resources/read again, for example on a timer or when the user refreshes.
Exercise
Using the notes_server.py above, a client calls resources/read with the URI notes://missing. What happens on the server side, and why is notes://missing absent from resources/list?
Show answer
The template matches with note_id set to missing, so get_note runs, finds no such key, and raises ValueError. The SDK turns this into an error response for the request. The URI is absent from resources/list because the list contains only concrete resources, and the notes are reachable only through the template notes://{note_id}.