Build and Deploy MCP Integrations
Build a Model Context Protocol client and server, then verify the integration with a compatible host.
Tool definitions, schemas from type hints, results and two kinds of error.
How can a server tell the client what went wrong when a valid tool request cannot be completed?
Protocol errors account for malformed or unsupported messages. A well-formed tool call can still fail while doing its work, and a tool-level result gives the model information it can use to recover.
Dispatcher validates the tool request and its arguments
Tool handler attempts the operation
Structured result reports either output or an actionable execution error
Dispatcher validates the tool request and its arguments
Tool handler attempts the operation
Structured result reports either output or an actionable execution error
Given Dispatcher validates the tool request and its arguments and Structured result reports either output or an actionable execution error, write down the missing step that connects them.
Tool handler attempts the operation
Now take Tool handler attempts the operation and the result above. Write an input and an implementation that could produce this trace.
Dispatcher validates the tool request and its arguments. Check that your implementation produces the result shown above.
The function receives a valid campaign ID string, but the campaign no longer exists. Where should the error be represented?
Return a tool execution error that tells the caller the campaign is unavailable. The transport and request shape succeeded, so the caller can choose another ID.
Check this when debugging. Writing tool descriptions for humans instead of for the model.
Tools are the reason most MCP servers exist: they let a model act. Everything a model knows about a tool comes from its definition, and everything it learns from using one comes from the result. A vague description gets the tool ignored or misused. A raw stack trace teaches the model nothing. This lesson builds the tools half of a server from scratch, including the type-hint magic SDKs use.
What was wrong, and what a valid id looks like
Everything a model learns from a tool comes from its result. A message that says what was wrong and how to fix it lets the model correct the call on its next try.
This rests on JSON-RPC 2.0 in depth and Discovery, capabilities and the two eras: a tool call is a JSON-RPC request, and what the server may offer was announced when the client asked. Here we look at the two messages that matter most, the definition going out and the result coming back.
Think of the instruction card taped to a rented machine: what it's called, what it's for, what you feed it. The person using it may never have seen one before, so the card has to do all the explaining. A model reading a tool is in the same position. tools/list returns definitions like this:
{
"name": "pause_campaign",
"title": "Pause a campaign",
"description": "Pause one running campaign so it stops spending. Use when
the user asks to stop or hold a campaign. Returns the campaign's new status.",
"inputSchema": {
"type": "object",
"properties": {
"campaign_id": {"type": "string", "description": "Campaign id, like cmp_103"},
"reason": {"type": "string", "description": "Short note for the audit log"}
},
"required": ["campaign_id"],
"additionalProperties": false
},
"outputSchema": {"type": "object", "properties": {"id": {"type": "string"},
"status": {"type": "string"}}},
"annotations": {"readOnlyHint": false, "destructiveHint": false,
"idempotentHint": true, "openWorldHint": false}
}
name: 1 to 128 characters of letters, digits, _, - and ., unique on this server.title: a friendly name for people. description: what it does and when to use it, written for the model.inputSchema: JSON Schema for the arguments. A tool with no arguments should use {"type": "object", "additionalProperties": false}.outputSchema (optional): the shape of the structured result, so clients can check and rely on it.annotations: hints about behavior. readOnlyHint: it changes nothing. destructiveHint: it may destroy data. idempotentHint: repeating it is harmless. openWorldHint: it reaches outside systems, such as the web.description written for?The model, which reads it to decide on a call
The description says what the tool does and when to use it, and the model has nothing else to go on.
Annotations help a host decide when to ask the user for approval. But they're the server's own claims, like a "safe for all ages" sticker the maker put on the box. So the spec says clients must treat them as untrusted unless the server itself is trusted.
tools/list takes an optional cursor and returns a page of tools, plus nextCursor if there are more. It's cacheable: results carry ttlMs (how many milliseconds the list stays fresh) and cacheScope ("public" if any cache may share it, "private" if it's per user). Return tools in a fixed order. A list that's identical every time lets clients cache it, and keeps the model's prompt identical too, so prompt caching works.
readOnlyHint: true, but the server is one you found on a forum. What should the host do?Treat the hint as untrusted and keep its normal approval rules
Annotations are self-reported. A malicious server could label a destructive tool read-only. Only a trusted server's hints should relax safety checks.
tools/call sends {"name": ..., "arguments": {...}}. The result holds a list of content blocks, the material the model will read:
| block | holds |
|---|---|
{"type": "text", "text": ...} | plain text, the most common |
{"type": "image", "data": <base64>, "mimeType": "image/png"} | an image, such as a chart |
{"type": "audio", ...} | audio data |
{"type": "resource_link", "uri": ..., "name": ...} | a pointer to a resource the client can read later |
{"type": "resource", "resource": {"uri": ..., "text": ...}} | a resource's contents, embedded |
A result can also carry structuredContent: plain JSON data for programs, matching the outputSchema. Think of a store receipt, with printed lines for you and a barcode for the scanner. Good servers send both. Code reads structuredContent reliably, and a text block with the same data as JSON serves clients and models that only read text.
result = {"content": [{"type": "text", "text": "12 sold"}],
"structuredContent": {"sold": 12}, "isError": False}
print(result["structuredContent"]["sold"] + 1)13
structuredContent holds sold as the number 12, so 12 + 1 is 13. Structured content gives programs real values, while content text is what a model reads.
A letter can come back for two reasons. "No such address" means it never got to anyone. "We don't stock that, try the blue one" means someone read it and is helping you. MCP has the same split:
"isError": true and a message in the content: a failed API call, an invalid date, "no campaign with that id". The host passes these back to the model, which can correct itself and retry.So write execution errors for the model: say what was wrong and what would work. "No campaign cmp_999; ids look like cmp_101 to cmp_106" gets fixed on the next try. "Error 500" doesn't.
In plain words: if the model could fix it, tell the model. That means a normal result with
isError: trueand a helpful message.
Real bodies from the practice server's tools. Watch the three outcomes of a call: a result, an error the model can fix, and a broken call.
get_campaign with {"id": "103"}, but ids look like cmp_103. What should the server return?A result with isError: true and a message like "No campaign 103. Ids look like cmp_103."
The call was well-formed; the value was wrong. An execution error with a helpful message lets the model fix it on the next call.
Write a sentence or two, then compare it with a good answer in the lesson.
This part builds the registry that turns a function into a definition, then the code that turns a return value into a result, and lints the descriptions.
Writing JSON Schema by hand for every tool is tedious and drifts out of date. So SDKs read the labels on your function instead, the same inspect trick FastAPI uses:
import inspect, json JSON_TYPES = {str: "string", int: "integer", float: "number", bool: "boolean", list: "array", dict: "object"} def schema_for(fn): props, required = {}, [] for name, p in inspect.signature(fn).parameters.items(): props[name] = {"type": JSON_TYPES[p.annotation]} if p.default is inspect.Parameter.empty: required.append(name) return {"type": "object", "properties": props, "required": required, "additionalProperties": False} def search_products(query: str, max_price: float = 500.0, in_stock: bool = True): """Search the catalog by keywords. Use it for questions on what the shop sells.""" print(inspect.getdoc(search_products)) print(json.dumps(schema_for(search_products), indent=1))
The docstring becomes the description, parameters without defaults become required, and the type hints become JSON types. With the official Python SDK (version 2, the first to speak the 2026-07-28 revision), a whole server looks like this:
from mcp.server import MCPServer mcp = MCPServer("shop") @mcp.tool() def search_products(query: str, max_price: float = 500.0) -> list[dict]: """Search the catalog by keywords. Use it for questions on what the shop sells.""" return catalog.search(query, max_price) mcp.run() # stdio; other transports are an argument away
SDK names and options change between versions (version 1 called this class FastMCP), so check its docs. The ideas don't change.
inputSchema is such a schema. What does this print for three sets of arguments?schema = {
"type": "object", "required": ["id"], "properties": {"id": {"type": "string"}}}
def problems(arguments):
found = [f"missing {name}" for name in schema["required"] if name not in arguments]
found += [f"{name} must be a string" for name, value in arguments.items()
if name in schema["properties"] and not isinstance(value, str)]
return found
print(problems({"id": "cmp_103"}), problems({"id": 103}), problems({}))[] ['id must be a string'] ['missing id']
The first call fits the schema. The second sends a number where the schema asks for a string, and the third leaves out a required field. A model reads the same schema to decide what to send, so a precise schema prevents most bad calls before they happen.
Strings become text. Data becomes structuredContent plus a text copy. Exceptions meant for the model become execution errors.
import json class ToolError(Exception): """Raise with a message written for the model.""" def to_result(fn, arguments): try: value = fn(**arguments) except ToolError as err: return {"resultType": "complete", "content": [{"type": "text", "text": str(err)}], "isError": True} if isinstance(value, str): return {"resultType": "complete", "content": [{"type": "text", "text": value}], "isError": False} return {"resultType": "complete", "content": [{"type": "text", "text": json.dumps(value)}], "structuredContent": value, "isError": False} def stock(sku: str): levels = {"TENT-2": 12, "MUG-1": 0} if sku not in levels: raise ToolError(f"Unknown sku {sku!r}. Known skus: {', '.join(levels)}.") return {"sku": sku, "in_stock": levels[sku]} print(to_result(stock, {"sku": "TENT-2"})) print(to_result(stock, {"sku": "tent"}))
The good call returns structured data and a JSON text copy. The bad one returns a normal result flagged isError, with a message listing the valid skus. That's everything the model needs to retry correctly.
When a model sends a bad argument, the error should say how to fix it. Write id_problem(value, prefix): return None if value is prefix + _ followed by one or more digits; otherwise return Expected an id like PREFIX_104 (PREFIX_ then digits); got VALUE, with the value shown by repr.
def id_problem(value, prefix): return None if value.startswith(prefix) else "bad id" print(id_problem("103", "cmp"))
The description isn't documentation for developers. It's the only thing the model reads when choosing what to do, so it deserves more care than any other string in your server. Treat it as a job description for someone starting today.
Compare these two:
The second says when to use it, what it takes, what comes back, and when to use something else. In practice, improving descriptions often helps more than changing the model.
When to use it, what it takes and what comes back
It also says when to use a different tool. Improving descriptions often helps more than changing the model.
The practice model is a stand-in that picks a tool by the words it shares with the question, not a language model, but real models also choose by description. The same two tools, with a vague and then a clear description for one of them:
import requests QUESTION = "Where is order ord_123, and what is its status?" SCHEMA = {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]} FIND = {"name": "find_orders", "input_schema": {"type": "object", "properties": { "email": {"type": "string"}}, "required": ["email"]}, "description": "Find a customer's orders by email address."} def picks(description): get = {"name": "get_order", "description": description, "input_schema": SCHEMA} 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, "tools": [get, FIND], "messages": [{"role": "user", "content": QUESTION}]}) block = next(b for b in reply.json()["content"] if b["type"] == "tool_use") return block["name"] print(picks("Gets order.")) print(picks("Look up one order by its id, like ord_123, and return its status, " "items and total."))
Don't return stack traces. The model can't act on one, and it may reveal your file paths and library versions.
Decide who can fix each problem. If the model can fix it, such as a mistyped date, use a normal result with isError: true and a message explaining what to change. If the call itself was malformed, that's a protocol error. Reporting a fixable problem as a protocol error means the model never sees the message, so it can't try again.
A normal result with isError: true, saying the month must be 1 to 12
The model can fix a mistyped date, so it needs to read the message. A result with isError: true reaches it, and it can try again. A protocol error is for a call that was itself malformed.
Look up one order by its id, like ord_123, and return its status, items and total.
A model chooses a tool by its description. This one says what the tool takes, an id like the one in the question, and what it returns, the status that was asked for.
Write tool_problems(tool): return a list of problems with a tool definition: "description too short" if it's under 40 characters, "say when to use it" if the description doesn't contain use (any case), and "describe PARAM" for each input property without a description, in property order.
TOOL = {
"name": "get_campaign",
"description": "Gets a campaign.",
"inputSchema": {"type": "object",
"properties": {"campaign_id": {"type": "string"}, "include_stats": {
"type": "boolean", "description": "Add spend and clicks."}}},
}
def tool_problems(tool):
return []
print(tool_problems(TOOL))
Write a sentence or two, then compare it with a good answer in the lesson.
Purpose. See your registry and to_result as the two official SDKs write them, line for line.
Both official SDKs build the definition from your code, run your function and wrap the return value. The 2026-07-28 revision is implemented by version 2 of each: the Python mcp package (version 2.3.0; FastMCP is renamed MCPServer) and the TypeScript @modelcontextprotocol/server package. Version 1 of each still gets fixes.
In an engineer's week. Every server review asks the same three questions about a tool: does the description say when to use it, does the schema stop the bad calls, and do the annotations tell the truth? What goes wrong is a tool added in a hurry with a one-line description, which the model then confuses with its neighbor, and an annotation copied from another tool.
Write a sentence or two, then compare it with a good answer in the lesson.
Build an MCP server over a small dataset you care about, so a model in any MCP host can search and use it. The starter has a working skeleton: a tool registry, a dispatcher that checks each request's _meta and answers server/discover, tools/list and tools/call, and a test transcript. Replace the trails with your own data, design the tools a model would need to answer real questions about it, and make the server robust to the bad requests models and hosts really send.
Write the tool descriptions for a model, not a person: what each tool is for, when to use it, and what it returns. When you're done, the same design moves to the official SDK in a few lines, as the lesson shows.
import json # Your data: replace this with a small dataset you care about (books, trails, recipes). TRAILS = [ {"id": "t1", "name": "Ridge loop", "km": 12.5, "climb_m": 640, "dogs": True}, {"id": "t2", "name": "Lake path", "km": 5.0, "climb_m": 40, "dogs": True}, {"id": "t3", "name": "Summit push", "km": 18.0, "climb_m": 1450, "dogs": False}, ] PV = "io.modelcontextprotocol/protocolVersion" CAPS = "io.modelcontextprotocol/clientCapabilities" SUPPORTED = ["2026-07-28"] SERVER_INFO = {"name": "trails", "version": "0.1.0"} CACHE = {"ttlMs": 300000, "cacheScope": "public"} # lists and discover carry these TOOLS = {} def tool(fn): """Register a function as a tool. Its docstring becomes the description.""" TOOLS[fn.__name__] = fn return fn @tool def find_trails(max_km: float = 100.0, dogs_allowed: bool = False): """Find trails up to max_km long. Set dogs_allowed to keep dog-friendly ones.""" return [t for t in TRAILS if t["km"] <= max_km and (t["dogs"] or not dogs_allowed)] def ok(mid, result): meta = {"io.modelcontextprotocol/serverInfo": SERVER_INFO} return {"jsonrpc": "2.0", "id": mid, "result": {"resultType": "complete", **result, "_meta": meta}} def error(mid, code, message, data=None): err = {"code": code, "message": message} if data is not None: err["data"] = data return {"jsonrpc": "2.0", "id": mid, "error": err} def handle(message): """Answer one modern request: server/discover, tools/list and tools/call.""" method, mid = message.get("method"), message.get("id") params = message.get("params", {}) if method == "initialize": # a legacy client: say what we speak asked = params.get("protocolVersion") text = "This server speaks only " + ", ".join(SUPPORTED) + "; send _meta" return error(mid, -32022, text, {"supported": SUPPORTED, "requested": asked}) meta = params.get("_meta", {}) missing = [key for key in (PV, CAPS) if key not in meta] if missing: return error(mid, -32602, "Missing _meta fields: " + ", ".join(missing)) if meta[PV] not in SUPPORTED: return error(mid, -32022, "Unsupported protocol version", {"supported": SUPPORTED, "requested": meta[PV]}) if method == "server/discover": caps = {"tools": {}} return ok(mid, {"supportedVersions": SUPPORTED, "capabilities": caps, **CACHE}) if method == "tools/list": tools = [{"name": name, "description": fn.__doc__, "inputSchema": {"type": "object"}} for name, fn in TOOLS.items()] return ok(mid, {"tools": tools, **CACHE}) if method == "tools/call": result = TOOLS[params["name"]](**params.get("arguments", {})) content = [{"type": "text", "text": json.dumps(result)}] return ok(mid, {"content": content, "isError": False}) return error(mid, -32601, f"Method not found: {method}") def request(id_, method, **params): """A modern request: every one carries its own version and capabilities.""" params["_meta"] = {PV: "2026-07-28", CAPS: {}} return {"jsonrpc": "2.0", "id": id_, "method": method, "params": params} # A test transcript: what a host would send, and what your server answers. for message in [ request(1, "server/discover"), request(2, "tools/list"), request(3, "tools/call", name="find_trails", arguments={"max_km": 13}), ]: print(json.dumps(handle(message))[:200])
Start with a short baseline or choose guided, independent, or AI-assisted practice.
Which annotation says repeating a tool call with the same arguments is harmless?
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