Build an MCP server in Python from scratch
A working Model Context Protocol server with tools, resources and prompts, written without an SDK so you can see exactly what goes over the wire.
A complete, tested server for the practice shop.
What evidence shows a complete server works for an unfamiliar client?
An integration has multiple contracts. The transport must carry valid messages, the server must discover and execute supported operations, and a denied operation must preserve durable state.
Fresh client starts from the published connection instructions
Client lists capabilities and performs authorized and denied requests
Checks confirm reply framing, result shape and resulting state
Fresh client starts from the published connection instructions
Client lists capabilities and performs authorized and denied requests
Checks confirm reply framing, result shape and resulting state
Given Fresh client starts from the published connection instructions and Checks confirm reply framing, result shape and resulting state, write down the missing step that connects them.
Client lists capabilities and performs authorized and denied requests
Now take Client lists capabilities and performs authorized and denied requests and the result above. Write an input and an implementation that could produce this trace.
Fresh client starts from the published connection instructions. Check that your implementation produces the result shown above.
All handler unit tests pass, but a client never sees a result because startup text appears on standard output. Where should the fix and regression test go?
Keep the protocol stream for framed replies and send diagnostics to standard error. Add a subprocess-level test because a unit test of one handler cannot observe the startup stream.
Check this when debugging. Routing by method before checking the version and metadata.
This capstone assembles the phase into one server for the practice shop: the JSON-RPC dispatcher, version and metadata checks, tools with schemas and teaching errors, resources with a template, a prompt, paging and caching hints, stdio framing and the conformance probes. It's the shape of a real server you could publish, and building it end to end is the best check that the pieces fit.
A few task-shaped tools with clear descriptions and limits
Agents do best with a handful of tools shaped like the jobs they do (look up an order, check stock), each with a clear description and safe limits. Raw access is risky, and too many tools crowd the context.
"Our support team wants an MCP server for the shop. Agents should look up orders and stock, read the help center, and staff should have a one-click 'draft a reply' prompt. Nothing may change data yet."
Start by sorting each need into the primitive that fits. Things the model reaches for are tools, things people attach are resources, and things staff pick from a menu are prompts:
| primitive | name | why |
|---|---|---|
| tool | get_order(order_id) | read-only; returns status, items and total as structured content |
| tool | check_stock(sku) | read-only; teaching error listing known skus when it's wrong |
| resource | docs://help/{id} (template) + listed articles | the app or user attaches articles as context |
| prompt | draft_reply(order_id, tone?) | staff pick it; it fills the order into a tuned request |
Both tools carry readOnlyHint: true, which the brief allows: nothing writes. Every result is "complete", and lists, reads and discovery carry ttlMs and cacheScope.
A prompt
Things staff pick from a menu are prompts. Tools are what the model reaches for, and resources are content people attach.
Think of a mailroom. One letter comes in, a clerk checks it and sends it to the right department, and one reply goes out. In code that is serve(): one JSON line in, dispatch(msg), one JSON line out. dispatch checks the shape, _meta and version, then routes by method to discovery, the tool registry, the resources or the prompts. Every piece comes from this phase. The new work is wiring: one dispatcher that applies the checks in the right order and wraps every answer correctly. The map shows where each piece sits.
CONTROL = {"tool": "the model", "resource": "the application", "prompt": "the user"}
features = [("look up an order", "tool"), ("read a help article", "resource"),
("draft a reply", "prompt")]
print([CONTROL[kind] for name, kind in features])['the model', 'the application', 'the user']
An order lookup is something the model decides to do while it works, so it is a tool. A help article is data the application attaches, so it is a resource. "Draft a reply" is something staff start with a click, so it is a prompt. Sorting each feature of a brief this way is the first design step of this capstone.
Write a sentence or two, then compare it with a good answer in the lesson.
The build. You wire the dispatcher in the exercise below. First the pieces that make it easy to get right: a teaching error for a wrong sku, a helper that suggests the nearest sku, and the order of the dispatcher's checks. The registry, resources and prompts are built for you, so every minute goes on the wiring.
The brief asks for a teaching error when a sku is wrong. Compare what the model gets from each version. It can only recover from one of them.
STOCK = {"TENT-2": 14, "STOVE-1": 3, "LAMP-4": 0}
def bad_check_stock(sku):
if sku not in STOCK:
return {"isError": True, "content": [{"type": "text", "text": "Error 500"}]}
return {"content": [{"type": "text", "text": f"{STOCK[sku]} in stock"}]}
def check_stock(sku):
if sku not in STOCK:
known = ", ".join(sorted(STOCK))
return {"isError": True,
"content": [{"type": "text",
"text": f"No sku {sku}. Known skus: {known}."}]}
return {"content": [{"type": "text", "text": f"{STOCK[sku]} in stock"}],
"structuredContent": {"sku": sku, "stock": STOCK[sku]}}
print(bad_check_stock("TENT2")["content"][0]["text"])
print(check_stock("TENT2")["content"][0]["text"])
print(check_stock("TENT-2")["structuredContent"])With the second message, the model can see that it dropped a hyphen, and it fixes that on its next try without bothering anyone. You'll write this kind of error in the exercise.
Write unknown_sku(sku, known): return No product SKU. Did you mean CLOSEST? using difflib.get_close_matches(sku, known, n=1), or No product SKU. if nothing is close. A suggestion helps the model fix its next call.
import difflib KNOWN = ["TENT-2P", "TENT-4P", "STOVE-1", "MAT-XL"] def unknown_sku(sku, known): return f"No product {sku}." print(unknown_sku("TENT2P", KNOWN))
Shape (JSON-RPC), then required _meta, then protocol version, then route by method
Malformed messages are rejected before anything else, and every method depends on the version and metadata being valid.
A miniature of the capstone: a request line goes in, passes the checks, is routed, and comes out as one line.
import json PV = "io.modelcontextprotocol/protocolVersion" CAPS = "io.modelcontextprotocol/clientCapabilities" SERVER_INFO = {"name": "mini", "version": "0.1.0"} def dispatch(msg): if "id" not in msg: return None meta = msg.get("params", {}).get("_meta", {}) if PV not in meta or CAPS not in meta: return {"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -32602, "message": "missing _meta"}} if msg["method"] == "server/discover": result = {"supportedVersions": ["2026-07-28"], "capabilities": {"tools": {}}} meta = {"io.modelcontextprotocol/serverInfo": SERVER_INFO} return {"jsonrpc": "2.0", "id": msg["id"], "result": {"resultType": "complete", **result, "_meta": meta}} return {"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -32601, "message": "Method not found"}} line_in = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": {"_meta": {PV: "2026-07-28", CAPS: {}}}}) line_out = json.dumps(dispatch(json.loads(line_in)), separators=(",", ":")) print(line_out)
The capstone's dispatcher is this, grown up: more checks, and routes to the tool registry, resources and prompts. Because it's a plain function, the conformance suite and the stdio loop can both drive it directly.
def classify(msg): if "id" not in msg: return "notification: no reply" if "_meta" not in msg.get("params", {}): return "error -32602" return "route " + msg["method"] print(classify({"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}))
error -32602
It has an id, so it's a request, but its params have no _meta, so classify returns error -32602. That's checked before routing, so it never reaches tools/list.
The order your dispatcher checks things in isn't arbitrary, and getting it wrong causes bugs that are easy to miss.
An airline checks your passport before it looks for your flight. Check the protocol version and metadata first, then route by method. If you route first, an unknown method gets "method not found" even when the real problem is that the client speaks a version you don't support. The client then looks for the wrong fix.
PV = "io.modelcontextprotocol/protocolVersion" def dispatch(msg, methods=("tools/list",), versions=("2026-07-28",)): meta = msg.get("params", {}).get("_meta", {}) if PV not in meta: return -32602, "missing _meta" if meta[PV] not in versions: return -32022, "unsupported version" if msg["method"] not in methods: return -32601, "method not found" return 0, "ok" print(dispatch({"method": "tools/list", "params": {}})) print(dispatch({"method": "nope", "params": {"_meta": {PV: "1999"}}})) print(dispatch({"method": "nope", "params": {"_meta": {PV: "2026-07-28"}}}))
One unhandled exception in a handler can end the whole connection, cutting off every other request in progress. So wrap the call to each handler. Log the details on your side, and return an internal error with no details in it.
This server changes nothing, which is what the brief asks for. When you add tools that write, like refunds, you'll want a confirmation from the user before anything happens, as in Progress, subscriptions and multi-round-trip requests. Don't rely on the model to ask first, since a prompt injection could talk it out of that.
A prompt injection could talk it out of asking
The confirmation has to be enforced by the server and host, where injected text can't reach it.
Write a sentence or two, then compare it with a good answer in the lesson.
Ship it. A server is finished when someone else can install it, trust it and test it. This part walks the checklist, runs a miniature conformance check you can fix, and ends with a README and a review.
Before you hand over the keys to a new house, you walk through every room. Before publishing, walk the server through what this phase taught:
server/discover works; a legacy initialize and unknown versions both give -32022 with supported; missing _meta gives -32602; unknown methods give -32601; notifications get no reply; ids are echoed.isError messages, annotations that tell the truth, a fixed order.Each line of the checklist can be a probe. This cell runs five of them against a miniature server and prints what passed. One fails on purpose: add the missing field to tools/list and run it again.
PV = "io.modelcontextprotocol/protocolVersion" CAPS = "io.modelcontextprotocol/clientCapabilities" META = {PV: "2026-07-28", CAPS: {}} def dispatch(msg): if "id" not in msg: return None params = msg.get("params", {}) def result(**fields): return {"jsonrpc": "2.0", "id": msg["id"], "result": {"resultType": "complete", **fields}} def error(code, text, data=None): return {"jsonrpc": "2.0", "id": msg["id"], "error": {"code": code, "message": text, "data": data}} if msg["method"] == "initialize": return error(-32022, "Unsupported protocol version", {"supported": ["2026-07-28"]}) meta = params.get("_meta", {}) if PV not in meta or CAPS not in meta: return error(-32602, "Missing _meta") if msg["method"] == "server/discover": return result(supportedVersions=["2026-07-28"], capabilities={"tools": {}}, ttlMs=3600000, cacheScope="public") if msg["method"] == "tools/list": return result(tools=[], ttlMs=300000) return error(-32601, "Method not found") def ask(method, params=None, id=1): return dispatch({"jsonrpc": "2.0", "id": id, "method": method, "params": {"_meta": META, **(params or {})}}) checks = [ ("Protocol", "discover works", "supportedVersions" in ask("server/discover")["result"]), ("Protocol", "legacy initialize gets -32022", dispatch({"id": 2, "method": "initialize"})["error"]["code"] == -32022), ("Protocol", "unknown method gets -32601", ask("nope")["error"]["code"] == -32601), ("Protocol", "a notification gets no reply", dispatch({"method": "notifications/cancelled"}) is None), ("Tools", "tools/list says how long to cache it", {"ttlMs", "cacheScope"} <= set(ask("tools/list")["result"])), ] for group, label, passed in checks: print("pass" if passed else "FIX ", group.ljust(9), label)
The brief says nothing may change data yet. Don't rely on memory for a rule like that. Make it a check that fails the build.
tools = [
{"name": "get_order", "annotations": {"readOnlyHint": True}},
{"name": "check_stock", "annotations": {"readOnlyHint": True}},
{"name": "cancel_order", "annotations": {"readOnlyHint": False}},
]
def writers(tools):
return [t["name"] for t in tools
if not t.get("annotations", {}).get("readOnlyHint")]
found = writers(tools)
print("tools that may change data:", found)
print("review", "FAILS" if found else "passes")Someone added cancel_order, and this check catches it before release. Annotations are hints to the client and don't enforce anything, so the handlers must be read-only too. But a check like this stops the easy mistakes.
The support server must be read-only. Write not_read_only(tools): return the sorted names of tools whose annotations don't set readOnlyHint to True (missing annotations count as not read-only).
TOOLS = [
{"name": "search_products", "annotations": {"readOnlyHint": True}},
{"name": "get_order", "annotations": {
"readOnlyHint": True, "openWorldHint": False}},
{"name": "update_address", "annotations": {"readOnlyHint": False}},
{"name": "order_history"},
]
def not_read_only(tools):
return []
print(not_read_only(TOOLS))
One template describes thousands of help articles without listing each one
A template like docs://help/{id} names a whole family of resources. The server lists a few useful ones and resolves the rest on demand.
A recipe that works in your oven may burn in someone else's. If you've only tried your server in one host, you've tested that host as much as your server. Hosts differ in what they send and how strictly they read replies. Your protocol tests and conformance probes run against the spec rather than one app. Run them in CI, and then try at least two hosts by hand before you publish. It's a small amount of work compared with a broken release.
A server isn't finished until someone else can install it. Think of the label on a medicine bottle: what it's for, how to take it and when not to. Your README should say what the server does, list every tool with what it needs, show the exact config to add to a host, and name any environment variables. Include one example of a real question it can answer.
"Read-only: it can't change orders"
Saying plainly what the server can't do tells a reviewer, and every user, where its limits are.
Say plainly what it can't do, too. "Read-only: it can't change orders" is exactly what a security reviewer wants to see. It also tells users what to expect from their agent, and it saves you from support questions you'd otherwise answer one at a time. Keep it up to date, because a wrong README is far worse than a short one, and it costs little to keep right.
Your support server passes its conformance checks. A teammate wants to add it to the team's host tomorrow. Write the README they will follow, and paste the evidence that it works: the Inspector's tools list and one real question answered in a host you have tried.
## What it does Two sentences, and one thing it cannot do. ## Tools, resources and prompts Each one, with what it needs. ## Install The exact config to add to a host, with a pinned version. ## Evidence The Inspector's tools/list output, and one real question with its answer. ## Security What credentials it uses, and why it is safe to connect.
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.
Why are both of the support server's tools annotated readOnlyHint: true?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
A working Model Context Protocol server with tools, resources and prompts, written without an SDK so you can see exactly what goes over the wire.
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