Sub topic 14
Using resources and prompts from your host
This chapter assumes you have completed the earlier chapters on the client session and the tool-calling loop. You should be able to start a server over stdio, call initialize(), and list tools. Here you will use the other two primitives, resources and prompts, from your own host application.
Who decides what gets used
Tools, resources and prompts differ mainly in who controls them.
| Primitive | Controlled by | Typical use | Host's job |
|---|---|---|---|
| Tool | The model | Actions and lookups the model chooses to run | Pass to the LLM API, execute calls |
| Resource | The application | Read-only data to put in context | Decide which resources to read and where to put them |
| Prompt | The user | Reusable instruction templates, like slash commands | Show a picker, collect arguments, send the result |
Your host has no required behavior for resources and prompts. The protocol only lets you list and fetch them. You decide how they appear in your product. A host might show resources in a file-picker-style menu and prompts as /commands. Another might read a resource automatically on startup.
A server with resources and a prompt
Save this as notes_server.py. It exposes one fixed resource, one resource template, and one prompt.
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("notes")
NOTES = {
"todo": "1. Renew passport\n2. Book dentist\n3. Reply to Sam",
"ideas": "A CLI that explains cron expressions in plain English.",
}
@mcp.resource("notes://index")
def index() -> str:
"""List of note names, one per line."""
return "\n".join(sorted(NOTES))
@mcp.resource("notes://{name}")
def note(name: str) -> str:
"""The text of one note."""
if name not in NOTES:
raise ValueError(f"No note named {name!r}")
return NOTES[name]
@mcp.prompt()
def summarize_note(name: str) -> str:
"""Ask the model to summarize one note."""
return (
f"Summarize the note called '{name}' in two sentences. "
"Use the notes://" + name + " resource if you have access to it."
)
if __name__ == "__main__":
mcp.run(transport="stdio")FastMCP turns notes://index into a concrete resource, because it has no parameters. It turns notes://{name} into a resource template, because the URI contains a placeholder that matches a function parameter. The prompt function's return string becomes a single user message.
Listing and reading resources
A resource is identified by a URI. A server may use any scheme it likes (file://, notes://, db://). The URI is an identifier, not necessarily something you can fetch yourself.
Servers advertise two kinds of resources:
- Concrete resources are listed by
resources/list. Each one has auri, aname, and optionally adescriptionandmimeType. - Resource templates are listed by
resources/templates/list. Each has auriTemplatesuch asnotes://{name}. You fill in the placeholders and read the result.
resources/read returns a list of contents. Each item has either text (for text) or blob (base64 for binary data), plus its uri and mimeType.
Fetching a prompt
prompts/list returns each prompt's name, description and declared arguments. prompts/get takes the name and a dictionary of argument values. It returns a list of messages, each with a role (user or assistant) and a content block. The content is usually text, but it can also be an embedded resource.
A host that uses both
This client reads a resource into the model's context and turns a prompt into chat messages. It stops before calling the model, so you can run it without an API key.
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from pydantic import AnyUrl
server_params = StdioServerParameters(command="python", args=["notes_server.py"])
def resource_to_context(uri, contents):
"""Wrap resource text so the model can tell data from instructions."""
parts = [c.text for c in contents if hasattr(c, "text")]
body = "\n".join(parts)
return f'<resource uri="{uri}">\n{body}\n</resource>'
def prompt_to_messages(result):
"""Convert MCP prompt messages to chat messages (text and embedded text)."""
messages = []
for m in result.messages:
content = m.content
if content.type == "text":
text = content.text
elif content.type == "resource" and hasattr(content.resource, "text"):
text = content.resource.text
else:
continue # skip images, audio, binary blobs
messages.append({"role": m.role, "content": text})
return messages
async def main():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
init = await session.initialize()
print("resources:", init.capabilities.resources is not None)
print("prompts:", init.capabilities.prompts is not None)
for r in (await session.list_resources()).resources:
print("resource:", r.uri, r.name)
templates = await session.list_resource_templates()
for t in templates.resourceTemplates:
print("template:", t.uriTemplate)
uri = "notes://todo"
read_result = await session.read_resource(AnyUrl(uri))
context = resource_to_context(uri, read_result.contents)
print(context)
for p in (await session.list_prompts()).prompts:
print("prompt:", p.name, [a.name for a in (p.arguments or [])])
prompt = await session.get_prompt("summarize_note", {"name": "todo"})
messages = prompt_to_messages(prompt)
messages[0]["content"] = context + "\n\n" + messages[0]["content"]
print(messages)
asyncio.run(main())You would pass messages to the same model call your agent loop already uses. Prompt message roles (user, assistant) match the roles most chat APIs accept.
Design decisions for your host
Check capabilities first
A server only has to support what it declares. Check init.capabilities.resources and init.capabilities.prompts before calling the list methods. Calling an unsupported method returns a JSON-RPC "method not found" error, which the SDK raises as an exception.
Choose how resource content reaches the model
You have three common options:
- User attaches it. The user picks a resource in your UI, and you insert it into the next message.
- Application attaches it. Your code reads a known resource on every session, for example a project README.
- Expose it through a tool. You write a wrapper tool such as
read_resource(uri)so the model can ask for it. This gives the model control, so apply the same approval rules you use for other tools.
Watch the size
A resource can be large. Check len(text) before inserting it, truncate or reject oversized content, and tell the user when you do. Resource text counts against your context window and your bill like any other input.
Handle changes
Servers may send notifications/resources/list_changed and notifications/prompts/list_changed when their lists change. A server that supports subscribe also sends notifications/resources/updated for a specific URI. A simple host can ignore these and re-list when the user opens a menu. A long-running host should refresh its cached lists.
Lists can be paginated
Listing methods can return a nextCursor. If it is set, call the method again with that cursor until it is empty. Small servers rarely paginate, but servers backed by large file trees or databases may.
Common mistakes
- Passing a plain
strURI everywhere. Recent SDK versions expect apydantic.AnyUrlforread_resource. Wrap it to avoid version-dependent errors. - Assuming every content item is text. Check for
textbefore using it. Binary items haveblobinstead. - Dropping the URI. Keep the URI with the content you insert. It helps the model cite the source and helps you debug.
- Treating prompts as system prompts. A prompt returns ordinary messages. Your host decides whether they go in the user turn, the conversation start, or elsewhere.
- Ignoring missing arguments. Read the prompt's declared
arguments, including which are required, and ask the user for them instead of guessing.
Exercise
Your host connects to a documentation server that exposes a template docs://{page}. A user types a page name into a search box and wants the page added to the conversation. List the MCP calls your host makes, in order, and explain who decided to read the resource.
Show answer
The host calls initialize() and checks that capabilities.resources is present. It calls resources/templates/list to find docs://{page}. It then fills in the user's page name and calls resources/read with the resulting URI, for example docs://install. It wraps the returned text in a labeled block and adds it to the next user message, after checking the size. The user decided to read it by typing the page name. This is application-controlled use, not a model decision. The host should still mark the content as untrusted data.
Exercise
A server's summarize_note prompt returns one message with role user and a text block. Name two ways your host could use that message, and one thing it must check before sending it to the model.
Show answer
The host could send the message as the next user turn in a fresh conversation, or prepend resource context to it and send it as the user turn of an existing conversation. Before sending, the host must make sure the user has supplied the required arguments, and it should confirm the content is text it can send (skipping or handling images and binary blobs). Reviewing the final text for unexpected instructions is also reasonable for third-party servers.