Skip to content
Index Ai Academy
Phase 9 · Production MCP

Testing, designing and shipping servers

Conformance checks, tool design for models, SDKs and deployment.

About 40 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 covers8

First principles

What would a real client test catch that the handler's own unit test might miss?

Handler tests check business behavior with direct inputs. Protocol and conformance tests add message shape, discovery, transport, and compatibility checks to that evidence.

  1. Starting point

    Unit test exercises one handler's result

  2. What changes

    Client test sends an actual protocol exchange

  3. Result

    Conformance check compares deployed behavior against the contract

Compare all three steps
  1. Starting point

    Unit test exercises one handler's result

  2. What changes

    Client test sends an actual protocol exchange

  3. Result

    Conformance check compares deployed behavior against the contract

Complete and reverse the trace

Given Unit test exercises one handler's result and Conformance check compares deployed behavior against the contract, write down the missing step that connects them.

Compare with the worked step

Client test sends an actual protocol exchange

Now take Client test sends an actual protocol exchange and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Unit test exercises one handler's result. Check that your implementation produces the result shown above.

Try it on a new case

A handler test shows two pages of reports, but a client receives only one. Where should you investigate first?

Show worked reasoning

Check the second request made by the client and the cursor in the first response. The defect may be in how the protocol passes page state even though direct handler calls work.

Run, change, and build

Check this when debugging. Mapping every API endpoint to its own tool.

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. A handler test shows two pages of reports, but a client receives only one. Where should you investigate first?

Why it matters

A server that works with one host on your laptop isn't done. It has to work with every host, keep working as the protocol evolves, and actually help models get tasks done. That last part is a design problem as much as a coding one. This lesson covers how professionals test servers, the tool design habits that separate useful servers from frustrating ones, and how servers get packaged, found and run.

What you'll be able to do

  • Test a server at three levels: handlers, full JSON-RPC exchanges, and conformance probes
  • Design tools for models: task-shaped, well described, concise and recoverable
  • Package and distribute a server, and know the official SDKs and the MCP Registry
  • Deploy a stateless remote server that scales, and observe it in production
Quick check
A server passes all its unit tests but replies to notifications, which no client expects. Which tests catch that?
  1. Protocol tests that send whole JSON-RPC messages
  2. Load tests that send thousands of requests
  3. A spell check of the tool descriptions
  4. More unit tests of each tool's function
Show the answer

Protocol tests that send whole JSON-RPC messages

Unit tests check each tool's logic; only tests that speak the protocol end to end check behavior like ids, notifications and errors, which every client depends on.

The idea: three levels of testing, and tools designed for a model

This rests on Build a client: a test plays a client's part. It sends a message, reads the reply and matches it by id, then compares what it got with what the protocol requires.

Three levels of testing

A car maker tests each part, then the assembled engine, then runs a standard road test that every car must pass. Servers get the same three levels:

  1. Handler tests. Each tool is a function, so test it like one: inputs in, result out, with fakes for the APIs it calls. Fast, and most of your tests.
  2. Protocol tests. Feed whole JSON-RPC messages to the server through an in-memory transport and check the replies: ids echoed, errors coded correctly, notifications unanswered. This catches the mistakes that only appear when a real client connects.
  3. Conformance probes. A fixed battery of checks any MCP server should pass, regardless of its tools: does server/discover work, does an unknown method give -32601, does a missing _meta give -32602? Run them in CI, so a refactor can't silently break compatibility.

For poking at a server by hand, the MCP Inspector is a developer tool that connects to a server and lets you browse and call its tools, resources and prompts in a browser:

npx @modelcontextprotocol/inspector uv run shop_server.py

Finally, take it for a test drive: a real host, with a real model, on real tasks. That's where you learn whether the tools are well designed.

Quick check
From the lesson on building a client: a table of pending requests lets replies that arrive in any order find their question, and unknown ids are ignored. What does this print?
pending = {12: "tools/list", 13: "tools/call"}

def on_reply(reply):
    return pending.pop(reply["id"], "ignored")

print(on_reply({"id": 13, "result": {}}), on_reply({"id": 12, "result": {}}),
      on_reply({"id": 99, "result": {}}), len(pending))
  1. tools/list tools/call ignored 0
  2. tools/call tools/list tools/call 0
  3. tools/call tools/list ignored 2
  4. tools/call tools/list ignored 0
Show the answer

tools/call tools/list ignored 0

The reply to 13 arrives first and still finds its own request, and then 12 finds its own. A reply to an id nobody asked about is dropped, and the table ends up empty. A test for a server plays this client's part: send a message, read the reply, match it by id.

Quick check
What does this print?
def handle(msg):
    if msg.get("method") == "server/discover":
        return {"id": msg["id"], "result": {"supportedVersions": ["2026-07-28"]}}
    return {"id": msg["id"], "error": {"code": -32601}}
print(handle({"id": 9, "method": "nope"})["error"]["code"])
  1. -32601
  2. 9
  3. nope
  4. None
Show the answer

-32601

The method isn't "server/discover", so the reply carries the error, and ["error"]["code"] reads -32601. A protocol test feeds in a whole message and checks the reply's error code.

Quick check
Which level of testing catches a server that wrongly replies to notifications?
  1. Handler tests that call each tool function directly with sample inputs
  2. Protocol tests: whole JSON-RPC messages through an in-memory transport
  3. Load tests that send thousands of requests at the same time
  4. A spell-check of the tool descriptions before each release
Show the answer

Protocol tests: whole JSON-RPC messages through an in-memory transport

Handler tests call tool functions directly, so they never see notifications. Protocol tests check the message handling itself.

Designing tools for models

A model only knows your tools through their names, descriptions and schemas, and it pays in tokens for every result. Ask a waiter what's good tonight and you want a recommendation, not the supplier list. The habits that work:

  • Shape tools around tasks, not endpoints. Don't mirror an API's 40 endpoints as 40 tools. A model asked "how's the spring campaign doing?" does better with one campaign_report(name) tool than with a chain of list_campaigns, get_campaign and get_metrics calls.
  • Name and describe for the model. Say what it does, when to use it, and what comes back. Describe each parameter's format with an example: "ISO date, e.g. 2026-10-30".
  • Constrain inputs. Use enums, minimums and required fields, so wrong calls fail fast with a clear message instead of doing something odd.
Quick check
Why constrain a tool's inputs with enums and required fields?
  1. Wrong calls fail fast, with a clear message
  2. It lets the tool skip its own checks
  3. Models can't send strings otherwise
  4. It makes the tool's description shorter
Show the answer

Wrong calls fail fast, with a clear message

A call with a bad value is refused straight away and the model can correct itself, instead of the tool doing something odd.

  • Return what's useful, concisely. Long raw JSON wastes context and buries the answer. Return the fields that matter, paginate long lists, and consider a detail parameter ("summary" or "full"). Include ids the model will need for follow-up calls.
  • Make errors teach. "No campaign named 'sprng'. Did you mean 'Spring sale'?" gets fixed on the next call. Use isError results for these, not protocol errors.
  • Keep the list small and stable. Fewer, distinct tools are easier for a model to choose between. A fixed order helps caching.
  • Test with a model. Write a few realistic tasks, run them, and read the transcripts. The model's confusion shows you which description to fix. That's an eval, as in Phase 1.

In plain words: design tools for what people ask, and read how the model uses them.

Worked example

Two tool designs, compared

Tools that mirror your API make the model do the joining. Count what it takes to answer "where's Ann's order?" with each design.

CUSTOMERS = {"ann@shop.example": "c1"}
ORDERS = {"c1": ["o9"]}
STATUS = {"o9": "shipped"}

calls = []
def find_customer(email):
    calls.append("find_customer"); return CUSTOMERS[email]
def list_orders(customer):
    calls.append("list_orders"); return ORDERS[customer]
def get_order(order):
    calls.append("get_order"); return STATUS[order]

status = get_order(list_orders(find_customer("ann@shop.example"))[0])
print("API-shaped:", status, "after", len(calls), "tool calls")

calls.clear()
def latest_order_status(email):
    calls.append("latest_order_status")
    return STATUS[ORDERS[CUSTOMERS[email]][0]]

print("Task-shaped:", latest_order_status("ann@shop.example"), "after", len(calls),
      "tool call")
It runs right here in your browser, with nothing to install.

Each extra call is another trip to the model, with more waiting, more tokens and another chance to go wrong. Design tools around what people ask for, not around your database tables.

Quick check
Your server wraps a CRM API with 35 endpoints. What's usually the better design for an agent?
  1. No tools at all, only resources, so the agent can't change anything in the CRM
  2. A handful of task-shaped tools (find_contact, log_call, deal_summary) with clear descriptions
  3. One tool that takes a raw HTTP request, so the agent can reach any endpoint
  4. 35 tools, one for each endpoint, so the agent never finds anything missing
Show the answer

A handful of task-shaped tools (find_contact, log_call, deal_summary) with clear descriptions

Fewer, higher-level tools mean fewer choices, fewer calls per task, and less context spent on definitions.

Try it now

A probe table drawn as a conversation: four probes against a good server, then one against a faulty one. Each gate is a probe's verdict.

In your own words
What makes a tool design good for a model?

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

In Python: probes, a suite and renames

This part writes a conformance suite that works on any server, and a check that catches a rename before it ships.

Worked example

Two probes against the practice server

Conformance probes are ordinary requests with expected answers. Here are two, run against the live practice server.

import requests

URL = "https://api.gradient.test/mcp"
GOOD = {"io.modelcontextprotocol/protocolVersion": "2026-07-28",
        "io.modelcontextprotocol/clientCapabilities": {}}

def post(method, meta, id=1, version="2026-07-28"):
    body = {"jsonrpc": "2.0", "id": id, "method": method, "params": {"_meta": meta}}
    headers = {"MCP-Protocol-Version": version, "Mcp-Method": method}
    return requests.post(URL, json=body, headers=headers, timeout=10)

r = post("resources/unknown", GOOD)
print("unknown method:", r.status_code, r.json()["error"]["code"], "(want 404, -32601)")

r = post("tools/list",
         {**GOOD, "io.modelcontextprotocol/protocolVersion": "1999-01-01"},
         version="1999-01-01")
err = r.json()["error"]
print("bad version:", r.status_code, err["code"], err["data"]["supported"],
      "(want 400, -32022)")
In the lesson you can change this and run it.

Each probe sends one request and compares the answer with what the spec requires. A conformance suite is a few dozen of these, run against any server. The exercise builds one that works on any in-memory server.

Quick check
What does a conformance suite check that your handler tests don't?
  1. Whether the model likes the tools and picks them for the right tasks
  2. How fast the server starts and how much memory it uses under load
  3. Protocol behavior every client relies on: error codes, ids, notifications, discovery and versions
  4. Whether each tool's business logic is right, for every input the tool accepts
Show the answer

Protocol behavior every client relies on: error codes, ids, notifications, discovery and versions

Handler tests check your tools; conformance checks your server speaks MCP correctly, whatever its tools are.

Drill

Group endpoints into fewer tools

Wrapping 35 endpoints as 35 tools overwhelms a model; grouping by resource is a better start. Write by_resource(endpoints): each endpoint is like "GET /customers/{id}/orders". Return a dictionary from the first path segment (customers) to the number of endpoints under it, with keys in alphabetical order.

ENDPOINTS = [
    "GET /customers", "GET /customers/{id}", "POST /customers",
    "GET /customers/{id}/orders", "GET /orders/{id}", "POST /orders/{id}/refund",
    "GET /products",
]


def by_resource(endpoints):
    return {}


print(by_resource(ENDPOINTS))
In the lesson, your code is checked as you write it.

Renames break things

Rename a street, and every map and delivery route that used the old name goes wrong. A tool's name is a public interface. Models, prompts and saved approvals all depend on it, so treat a rename as a breaking change.

Drill

Keep old tool names working

After a rename, old clients still call the old name. Write resolve(name, renames, tools): follow renames (old name to new name) until you reach a name in tools, and return it. Raise KeyError if a name leads nowhere, or if the renames loop.

TOOLS = {"search_products", "get_order"}
RENAMES = {"search": "find_products", "find_products": "search_products",
           "order": "get_order"}


def resolve(name, renames, tools):
    return renames.get(name, name)


print(resolve("search", RENAMES, TOOLS))
In the lesson, your code is checked as you write it.
In your own words
What does deploying a remote server need?

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

In production: packaging, testing with the SDK and running it

Purpose. The same three levels of tests, written with the official SDK, and what changes when the server is public.

Packaging and finding servers

  • Python servers are usually published to PyPI and run with uvx shop-mcp, which installs and runs them in an isolated environment. Node servers are published to npm and run with npx. Many are also published as container images.
  • The MCP Registry is the community's central directory of public servers, a phone book that hosts and people can search. Publishing there gives yours a stable name and metadata.
  • Version your server with semantic versioning, numbers like 1.4.2 whose first part goes up when something breaks. Changing a tool's name, removing a parameter or changing what it returns is a breaking change for every host and every prompt that relies on it.
  • The official SDKs (Python and TypeScript are the most used, and there are others, such as C#, Java, Kotlin, Go and Rust) handle framing, transports, schemas and protocol versions. They're how most servers are built. Knowing what they do inside, which is what this phase has taught, is how you debug them.
Quick check
Under semantic versioning, which of these is a breaking change?
  1. Fixing a typo in the README
  2. Making a handler run faster
  3. Adding a new optional tool
  4. Renaming a tool
Show the answer

Renaming a tool

Every host and every prompt that uses the old name stops working. The first number of the version goes up.

Running a remote server

Modern MCP is stateless, which makes deployment ordinary web engineering:

  • Run several copies behind a load balancer, with no sticky sessions. Any copy can answer any request.
  • Put OAuth in front (Securing remote servers with OAuth), plus rate limits per user and per tool.
  • Use ttlMs on list results, so clients don't hammer tools/list.
  • Log to stderr (or your platform's logs) with a request id. Clients can pass OpenTelemetry trace context (traceparent) in _meta, so one trace can follow a request from the host through your server to the APIs it calls.
  • Watch per-tool error rates and latency. A tool that fails 30% of the time is a design bug.

In an engineer's week. A server release goes out on Friday. The checklist: handler tests green, protocol tests green, the conformance suite green in CI, the version bumped by the rules above, and one real task run in a real host. What goes wrong is a rename in a "small" release. Models, prompts and saved approvals depend on the old name, and nothing in the unit tests fails.

Goes deeper in

In your own words
A colleague wants to ship a small server release that renames one tool. What do you tell them?

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

  • 2 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

What is the MCP Inspector for?

  1. Connecting to a server and browsing or calling its tools, resources and prompts by hand while developing
  2. Scanning servers for malware and known security holes, before you connect them to a host that has your data
  3. Deploying servers to the cloud, by packaging each one and checking it answers once it's running there
  4. Training models to use tools, by recording each call you make by hand and replaying it as an example

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
Practice for interviews 21 questions

AI agent interview questions and answers

Questions on designing and running agents: tools, the agent loop, permissions, context, multi-agent systems, security and evaluation.

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