Skip to content
Index Ai Academy
Phase 9 · Production MCP

Capstone: a production MCP server

A complete, tested server for the practice shop.

About 45 minutes · 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 covers10

First principles

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.

  1. Starting point

    Fresh client starts from the published connection instructions

  2. What changes

    Client lists capabilities and performs authorized and denied requests

  3. Result

    Checks confirm reply framing, result shape and resulting state

Compare all three steps
  1. Starting point

    Fresh client starts from the published connection instructions

  2. What changes

    Client lists capabilities and performs authorized and denied requests

  3. Result

    Checks confirm reply framing, result shape and resulting state

Complete and reverse the trace

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.

Compare with the worked step

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.

Check one starting point

Fresh client starts from the published connection instructions. Check that your implementation produces the result shown above.

Try it on a new case

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?

Show worked reasoning

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.

Run, change, and build

Check this when debugging. Routing by method before checking the version and metadata.

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. 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?

Why it matters

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.

What you'll be able to do

  • Plan an MCP server: which tools, resources and prompts, and how each is described
  • Wire the pieces of this phase into one dispatcher that follows the 2026-07-28 rules
  • Serve it over stdio framing and test it end to end through a client
  • Pass a conformance suite and review the server against a security checklist
Quick check
A support team wants an MCP server for the shop. Which tool design suits an agent best?
  1. One tool per database table, with raw SQL access
  2. A single tool that runs any Python code it's given
  3. A few task-shaped tools with clear descriptions and limits
  4. As many tools as possible, one per API endpoint
Show the answer

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.

The brief

"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."

The plan

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:

primitivenamewhy
toolget_order(order_id)read-only; returns status, items and total as structured content
toolcheck_stock(sku)read-only; teaching error listing known skus when it's wrong
resourcedocs://help/{id} (template) + listed articlesthe app or user attaches articles as context
promptdraft_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.

Quick check
Staff want a one-click "draft a reply" that they pick from a menu. Which primitive fits?
  1. A prompt
  2. A tool
  3. A resource
  4. A resource template
Show the answer

A prompt

Things staff pick from a menu are prompts. Tools are what the model reaches for, and resources are content people attach.

The architecture

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.

Try it now
Quick check
From the lesson on resources and prompts: the three primitives differ in who chooses them. The brief asks for order lookups, help-center reading, and a one-click "draft a reply". What does this print?
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])
  1. ['the user', 'the application', 'the model']
  2. ['the application', 'the user', 'the model']
  3. ['the model', 'the model', 'the model']
  4. ['the model', 'the application', 'the user']
Show the answer

['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.

In your own words
Pick one need from the brief and say which primitive it is and who chooses it.

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

Build it

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.

Worked example

A teaching error for a wrong sku

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"])
It runs right here in your browser, with nothing to install.

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.

Drill

Suggest the sku they meant

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))
In the lesson, your code is checked as you write it.
Quick check
In what order should the dispatcher check an incoming request?
  1. Only the method; the rest is optional
  2. Version first, then shape
  3. Shape (JSON-RPC), then required _meta, then protocol version, then route by method
  4. Route by method first, then check the version if the method needs it
Show the answer

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.

Worked example

One request, all the way through

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)
In the lesson you can change this and run it.

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.

Quick check
The dispatcher checks a message step by step. What does this print?
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": {}}))
  1. error -32602
  2. error -32601
  3. notification: no reply
  4. route tools/list
Show the answer

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.

Getting the order right

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"}}}))

Nothing may escape the dispatcher

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.

Read-only now, safe later

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.

Quick check
When you add tools that write, why not rely on the model to ask the user first?
  1. Users dislike being asked anything
  2. A prompt injection could talk it out of asking
  3. The protocol doesn't allow questions
  4. Models aren't able to ask questions
Show the answer

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.

In your own words
What should happen when a handler raises an exception nobody expected?

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

Ship it

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.

Review checklist

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:

  • Protocol: 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.
  • Tools: task-shaped, described for the model, strict schemas, concise structured results, teaching isError messages, annotations that tell the truth, a fixed order.
  • Resources and prompts: a template instead of a giant list; -32602 for missing resources; prompt arguments validated and filled safely.
  • Transport: nothing but protocol on stdout; logs on stderr; compact one-line JSON.
  • Security: read-only credentials for a read-only server; no secrets in descriptions or results; input validated; no token passthrough when it goes remote.
  • Shipping: conformance probes in CI; semantic versioning; listed in the registry when public.

A checklist your server fills in

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)
Worked example

Nothing may change data

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")
In the lesson you can change this and run it.

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.

Drill

Prove nothing can change data

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))
In the lesson, your code is checked as you write it.
Quick check
The checklist says to use a resource template instead of a giant list. Why?
  1. One template describes thousands of help articles without listing each one
  2. Templates hide the articles from the model, so it can't read them all
  3. Lists aren't allowed in MCP, so a template is the only way to offer many
  4. Templates load faster in Python than lists do, so the server starts sooner
Show the answer

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.

Test beyond your own setup

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.

Writing the README

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.

Quick check
Which line does a security reviewer most want to find in your server's README?
  1. "Supports every MCP feature"
  2. "Read-only: it can't change orders"
  3. "Built with love by our team"
  4. "See the code for details"
Show the 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.

Written brief · README

Ship the support server: a README with proof

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.

It must

  • Says what the server cannot do (it is read-only)
  • Lists every tool with what it needs
  • Gives an install config with an exact version
  • Pastes the Inspector's tools/list output
  • Names the credentials it uses and says they are read-only

Go further

  • Says what you would check before adding a write tool

The template

## 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.
In the lesson, you write over it, 150 to 400 words, and the tutor can mark it.
In your own words
Why test beyond your own setup, and what goes in the README?

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

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

Try a quiz question

Why are both of the support server's tools annotated readOnlyHint: true?

  1. They only read data, which hosts (that trust the server) can use to skip approval prompts
  2. So they run faster, because hosts can skip logging and checks on anything marked as read-only
  3. Because MCP requires it, and a tool with no annotations gets rejected when the server is listed
  4. To hide them from the model, so that it can only reach those tools through a user's request

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
Step by step 6 steps

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.

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