Skip to content
Index Ai Academy
Phase 9 · Building servers

Resources and prompts

Readable data, URI templates and reusable prompt templates.

About 40 minutes · Model names, versions and API rules checked November 2026 · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers7

First principles

Should a report, a reusable analysis template, and a request to create a note use the same protocol primitive?

A resource gives a thing a stable address, a prompt offers a reusable interaction to the user, and a tool lets a model request an operation through the host.

  1. Starting point

    Designer identifies the data, template or action

  2. What changes

    Server exposes it under the matching primitive

  3. Result

    Host presents or executes it through the right interaction

Compare all three steps
  1. Starting point

    Designer identifies the data, template or action

  2. What changes

    Server exposes it under the matching primitive

  3. Result

    Host presents or executes it through the right interaction

Complete and reverse the trace

Given Designer identifies the data, template or action and Host presents or executes it through the right interaction, write down the missing step that connects them.

Compare with the worked step

Server exposes it under the matching primitive

Now take Server exposes it under the matching primitive and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Designer identifies the data, template or action. Check that your implementation produces the result shown above.

Try it on a new case

Which primitive would hold campaign://reports/17, and which would create a review note?

Show worked reasoning

Use a resource for the report at its URI, and a tool for creating a note. The resource identifies retrievable data while the tool changes state and needs the corresponding permission checks.

Run, change, and build

Check this when debugging. Making everything a tool, even data the user should pick.

Trace the cause · MCP message and permission
  1. Mark which message crosses the client–server boundary and which check determines what the caller may do.
  2. Change the tool input or approved scope. Compare the returned message and stored state to distinguish a denial from an allowed change.
  3. Try the same reasoning on this case. Which primitive would hold campaign://reports/17, and which would create a review note?

Why it matters

Tools get the attention, but MCP has two other primitives. Resources give a model data to read: documents, records, files. Prompts give users ready-made, well-tested requests. Knowing when to use each makes a server pleasant to use rather than a pile of tools. A help center fits as resources. A "review this campaign" workflow fits as a prompt. Picking well also keeps the model's context lean, because not everything has to be a tool.

What you'll be able to do

  • Explain who controls each MCP primitive: tools, resources and prompts
  • Serve resources by URI, including URI templates for whole families of resources
  • Serve prompt templates with arguments that hosts show to users
  • Choose the right primitive for a capability you want to expose
Quick check
In a restaurant, the chef grabs knives on their own, but a diner picks from the menu. In MCP, who picks a prompt?
  1. The server, which sends it on a schedule
  2. The user, who chooses a ready-made request
  3. Nobody: prompts run automatically
  4. The model, whenever it decides it needs one
Show the answer

The user, who chooses a ready-made request

Tools are model-controlled, resources are usually app-controlled, and prompts are user-controlled: ready-made, tested requests a person picks, like items on a menu.

The idea: who pulls what into the context

This rests on Build a server: tools: a tool is something the model decides to call. Two other primitives put text in front of the model, and the difference is who decides.

Who's in control

Picture a restaurant kitchen. The chef reaches for knives and pans on their own, as the dish needs them. The restaurant decides which ingredients are on the counter. And the customer picks from the set menu. MCP's three primitives differ the same way, in who decides when they're used:

primitivecontrolled bytypical host behavior
toolsthe modelthe model decides to call one during a conversation
resourcesthe applicationthe host (or the user) chooses what to read and add to the context
promptsthe usershown as a menu or slash command; the user picks one
Quick check
From the lesson on building a server's tools: a result carries structuredContent for programs, and a text copy of the same data for readers that only take text. What does this print?
import json

data = {"sold": 12, "sku": "TE-107"}
result = {"content": [{"type": "text", "text": json.dumps(data)}],
          "structuredContent": data, "isError": False}
print(json.loads(result["content"][0]["text"]) == result["structuredContent"],
      result["structuredContent"]["sold"] + 1)
  1. False 13
  2. True 13
  3. True 121
  4. True 12
Show the answer

True 13

The text block and the structured block hold the same data, one as JSON text and one as an object a program can use directly, so sold + 1 is plain arithmetic. A tool is something the model decides to call. The two primitives in this lesson, resources and prompts, are chosen by the app and by the user.

Quick check
Who usually decides that a help center article goes into the model's context?
  1. Nobody: every resource is always included
  2. The model, by calling it like a tool
  3. The application, or the user through it
  4. The server, as soon as it starts
Show the answer

The application, or the user through it

Resources are controlled by the application: the host, or the user, chooses what to read and add. Tools are the model's choice; prompts are the user's.

A help center article is a resource. The app might show the list, let the user attach one, or search them and add the best match. "Write a weekly report" is a prompt. The user triggers it, fills in a couple of arguments, and gets a carefully written request that took the server's authors an afternoon to tune.

Resources

Each resource has a URI, an address for one item, like a library call number: file:///home/ada/notes.md, https://..., or a scheme the server invents, like docs://help/doc_shipping.

  • resources/list returns entries with uri, name, optional title, description and mimeType, paged with cursors like tools.
  • resources/read with a uri returns contents: a list of items, each with uri, mimeType, and either text or blob (base64 bytes, for images and other binary files).
  • A missing resource is error -32602. Revisions up to 2025-11-25 used -32002, so clients should accept both from older servers.
  • List and read results are cacheable, with ttlMs and cacheScope.

URI templates

Nobody prints a list of every apartment in a city. "Apartment {number}, 12 Main Street" covers them all. Listing every invoice or every customer record isn't practical either. A resource template describes a whole family with an RFC 6570 URI template, such as docs://help/{id} or crm://customers/{customer_id}/orders. resources/templates/list returns them. A client fills in the variables to build a URI, then reads it.

Try it now

The practice server's help articles are resources, with one template, docs://help/{id}. Its one prompt fills a campaign's data into a review request.

Quick check
Your server gives access to 40,000 customer records. How should it expose them as resources?
  1. List all 40,000 records in resources/list, so the client can see every customer at once
  2. It can't: customer data isn't allowed to be a resource, only the result of a tool
  3. Put every record into one huge resource, so the model gets them all in a single read
  4. A resource template like crm://customers/{customer_id}, plus maybe a search tool to find ids
Show the answer

A resource template like crm://customers/{customer_id}, plus maybe a search tool to find ids

Templates describe a family without listing it. A small search tool helps the model or user find the right id.

Quick check
Your data is a document that a person wants to attach as context. Which primitive fits?
  1. A resource
  2. A prompt
  3. An annotation
  4. A tool
Show the answer

A resource

The app or the user chooses resources. The app can show a picker, and the model doesn't spend a turn asking for the document.

In your own words
Who controls tools, resources and prompts?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: templates, prompts and pages

This part matches URIs against templates, fills prompts safely and pages long lists, then fetches a real prompt from the practice server and sends it to a model.

Matching a URI against a template

When a read arrives for docs://help/doc_shipping, the server must find which template it fits and pull out id = "doc_shipping". Think of a clerk checking an address against a form with one blank. For simple templates, where each {name} stands for one path segment, a regular expression does it:

import re

def match_template(template, uri):
    parts = re.split(r"(\{\w+\})", template)
    pattern = "".join(f"(?P<{p[1:-1]}>[^/]+)" if p.startswith("{") else re.escape(p)
                      for p in parts)
    m = re.fullmatch(pattern, uri)
    return m.groupdict() if m else None

print(match_template("docs://help/{id}", "docs://help/doc_shipping"))
print(match_template("crm://customers/{cid}/orders/{oid}",
                     "crm://customers/c42/orders/o7"))
print(match_template("docs://help/{id}", "docs://help/a/b"))
It runs right here in your browser, with nothing to install.

Each {name} becomes a named group that matches one or more characters other than /. Every other character is escaped, so dots and slashes in the template mean themselves. RFC 6570 defines richer forms too, such as {+path} that may include slashes, but this simple level covers most servers.

Prompts

A prompt is a form letter with blanks, written by someone who knows what works. prompts/list returns prompt definitions: name, title, description and arguments (each with a name, description and required flag). prompts/get with a name and arguments returns messages, ready to send to a model:

{"resultType": "complete", "description": "Review of Brand Awareness - Video",
 "messages": [{"role": "user", "content": {"type": "text",
   "text": "Here is one campaign's data: ... In three sentences, say how it is
     performing and suggest one change."}}]}

Messages can also embed resources or images. A missing required argument is error -32602. Hosts typically show prompts as slash commands: type /review_campaign cmp_103, and the host calls prompts/get and sends the messages.

Worked example

Filling a prompt template safely

Prompts are templates with named slots. string.Template fills $name slots and won't evaluate anything else, so user text can't break the template.

from string import Template

PROMPT = Template("Write a $tone product description for $product, under $words words.")
ARGS = [{"name": "product", "required": True}, {"name": "tone", "required": False},
        {"name": "words", "required": False}]
DEFAULTS = {"tone": "friendly", "words": "60"}

def get_prompt(arguments):
    missing = [a["name"] for a in ARGS if a["required"] and a["name"] not in arguments]
    if missing:
        raise ValueError(f"missing required arguments: {', '.join(missing)}")
    text = PROMPT.substitute({**DEFAULTS, **arguments})
    return {"resultType": "complete",
            "messages": [{"role": "user", "content": {"type": "text", "text": text}}]}

print(get_prompt({"product": "the River tent"})["messages"][0]["content"]["text"])
reply = get_prompt({"product": "the {secret} mug", "tone": "playful"})
print(reply["messages"][0]["content"]["text"])
try:
    get_prompt({})
except ValueError as err:
    print("rejected:", err)
In the lesson you can change this and run it.

Optional arguments fall back to defaults, and a missing required one is refused. The second call puts braces in the user's text, and they come through as plain characters. str.format would treat {secret} as another slot and fail. Remember that a prompt's output goes to a model, so text a user supplies is still untrusted input inside it.

Quick check
A server matches resource URIs against the template docs://help/{id}. What does this print?
import re

template = "docs://help/{id}"
pattern = "^" + re.escape(template).replace(r"\{id\}", "(?P<id>[^/]+)") + "$"
m = re.match(pattern, "docs://help/billing")
print(m.group("id"))
  1. help
  2. {id}
  3. docs://help/billing
  4. billing
Show the answer

billing

The template's {id} becomes a named group that captures one path segment, so m.group("id") gives billing, and the server knows which article to read.

Drill

Page through a big resource list

Write list_page(uris, cursor, size): cursor is None for the first page, otherwise the string the previous page returned. Return (page, next_cursor): up to size URIs starting at the cursor's position, and the cursor for the next page as a string, or None when there are no more.

def list_page(uris, cursor, size):
    return uris, None


uris = [f"crm://customers/{n}" for n in range(1, 8)]
print(list_page(uris, None, 3))
In the lesson, your code is checked as you write it.

Don't list what you can't list

A server with 200,000 help articles shouldn't return all of them from resources/list. A client would have to fetch and hold them all, and most of them would never be used. A URI template, such as docs://help/{id}, describes the whole collection in one line. List only the handful of articles people use most, and let the template cover the rest.

Filling templates safely

str.format looks like the natural way to fill a prompt template. It isn't safe with user text. A form letter works because the blanks hold data. Trouble starts when what someone writes in a blank gets read as part of the form's instructions.

class Config:
    secret = "sk-123"

template = "Reply about: {topic}"
print(template.format(topic="my order"))

# A value is safe, but a template written with user text is not:
user_text = "{config.secret}"
print(("Reply about: " + user_text).format(config=Config))

If user text ever becomes part of the format string, the braces in it get read as instructions, and it can reach into the objects you pass in. Keep templates fixed, validate each argument, and use plain replacement for the values. Remember too that whatever the prompt contains is what the model will read, so a filled-in prompt is untrusted content. Treat it that way.

Drill

Say what a resource contains

Write mime_for(uri): return text/markdown for .md, application/json for .json, text/csv for .csv, image/png for .png, and text/plain for anything else. Match the extension case-insensitively, and ignore a ?query part.

def mime_for(uri):
    return "text/plain"


print(mime_for("docs://help/returns.md"), mime_for("files://exports/Q3.CSV?v=2"))
In the lesson, your code is checked as you write it.

Fetch a prompt and send it to a model

The practice server's one prompt fills a campaign's data into a review request. This cell fetches it with prompts/get and sends the messages it returns to the model API, which is what a host does when a user picks the prompt:

import requests

PV = "io.modelcontextprotocol/protocolVersion"
CAPS = "io.modelcontextprotocol/clientCapabilities"
params = {"name": "review_campaign", "arguments": {"campaign_id": "cmp_103"},
          "_meta": {PV: "2026-07-28", CAPS: {}}}
headers = {"MCP-Protocol-Version": "2026-07-28", "Mcp-Method": "prompts/get",
           "Mcp-Name": "review_campaign"}
got = requests.post("https://api.gradient.test/mcp", headers=headers, json={
    "jsonrpc": "2.0", "id": 1, "method": "prompts/get", "params": params}).json()
messages = [{"role": m["role"], "content": m["content"]["text"]}
            for m in got["result"]["messages"]]
print(len(messages), "message:", messages[0]["content"][:48])

reply = requests.post("https://api.anthropic.com/v1/messages", timeout=60,
    headers={"x-api-key": "added-by-the-academy-server",
             "anthropic-version": "2026-10-21"},
    json={"model": "claude-opus-5-5", "max_tokens": 300, "messages": messages}).json()
print(reply["stop_reason"], reply["content"][0]["type"])
In your own words
How does a server match a URI against a template?

Write a sentence or two, then compare it with a good answer in the lesson.

In the SDK and a real host: decorators, @ mentions and slash commands

Purpose. See the resource template and the prompt as the SDK writes them, and where a user meets each in a host.

In the Python SDK a resource is a function with a URI pattern, and a prompt is a function whose parameters become the prompt's arguments. The {id} in the URI becomes the function's parameter, which is your match_template. In a host, a resource is usually reached by an @ mention or an attach menu, and a prompt by a / command.

Two more features sit beside these, and the 2026-07-28 changelog doesn't change them. Argument completion lets a host ask the server for suggestions while the user types a prompt argument or a template variable. Resource annotations are hints such as who a resource is for and how important it is. Like tool annotations, they are the server's own claims.

In an engineer's week. A teammate asks "should this be a tool or a resource?" The test: if the model should decide to fetch it mid-task, make it a tool. If a person or the app should attach it up front, make it a resource. If it is a request a person runs again and again, make it a prompt. What goes wrong is a resource that changes data when read, and a prompt that pastes user text into a template with str.format.

Goes deeper in

In your own words
A support team wants staff to attach any help article to a chat with one click. Resource, tool or prompt, and why?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 4 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

Which primitive is controlled by the model?

  1. Tools
  2. Resources
  3. Prompts
  4. All three equally

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 9 · about 13 hours of study

Model Context Protocol

Build MCP servers, clients and hosts, from the wire format to production 17 lessons 1 free
  1. JSON-RPC 2.0 in depth FreeRequests, notifications, errors and a dispatcher built from scratch.35 min
  2. Versions and stateless requestsRevisions by date, the legacy handshake, per-request _meta and version negotiation.30 min
  3. Discovery, capabilities and the two erasserver/discover, declared capabilities, and talking to legacy and modern software alike.30 min
  4. Transports I: stdioNewline-delimited JSON over a subprocess's standard streams.30 min
  5. Transports II: Streamable HTTPOne endpoint, required headers, JSON or event-stream replies.40 min
  6. Build a server: toolsTool definitions, schemas from type hints, results and two kinds of error.45 min
  7. Resources and promptsReadable data, URI templates and reusable prompt templates.40 min
  8. The same server with the official SDKsYour registry and dispatcher on the SDK's decorator shape, in Python and TypeScript.40 min
  9. Build a clientMetadata on every request, version fallback, paging and caching.40 min
  10. Hosts: connecting servers to a modelMany servers, one agent: namespacing, routing and approvals.40 min
  11. Progress, subscriptions and multi-round-trip requestsLong-running work, change notifications and asking the user mid-call.45 min
  12. Securing remote servers with OAuthProtected resource metadata, PKCE, audiences and scope challenges.45 min
  13. MCP securityTool poisoning, rug pulls, confused deputies and local-server risks.40 min
  14. Lab: attack and defend a hostPoisoned tools, injected results, token replay and the defenses that stop each.40 min
  15. Testing, designing and shipping serversConformance checks, tool design for models, SDKs and deployment.40 min
  16. MCP in production: gateways, limits and auditAn allowlist, per-user rate limits, header checks and an audit log in front of many servers.35 min
  17. Capstone: a production MCP serverA complete, tested server for the practice shop.45 min
Part of a free course 15 lessons

Build and Deploy MCP Integrations

Build a Model Context Protocol client and server, then verify the integration with a compatible host.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write