Build and Deploy MCP Integrations
Build a Model Context Protocol client and server, then verify the integration with a compatible host.
Readable data, URI templates and reusable prompt templates.
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.
Designer identifies the data, template or action
Server exposes it under the matching primitive
Host presents or executes it through the right interaction
Designer identifies the data, template or action
Server exposes it under the matching primitive
Host presents or executes it through the right interaction
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.
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.
Designer identifies the data, template or action. Check that your implementation produces the result shown above.
Which primitive would hold campaign://reports/17, and which would create a review note?
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.
Check this when debugging. Making everything a tool, even data the user should pick.
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.
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.
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.
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:
| primitive | controlled by | typical host behavior |
|---|---|---|
| tools | the model | the model decides to call one during a conversation |
| resources | the application | the host (or the user) chooses what to read and add to the context |
| prompts | the user | shown as a menu or slash command; the user picks one |
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)
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.
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.
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).ttlMs and cacheScope.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.
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.
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.
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.
Write a sentence or two, then compare it with a good answer in the lesson.
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.
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"))
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.
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.
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)
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.
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"))
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.
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))
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.
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.
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"))
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"])
Write a sentence or two, then compare it with a good answer in the lesson.
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.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
Which primitive is controlled by the model?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
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