The same server with the official SDKs
Your registry and dispatcher on the SDK's decorator shape, in Python and TypeScript.
What it covers7
Why it matters
Almost every real MCP server is built with an official SDK, and the SDK is the set of pieces you have already written, packaged. The dispatcher, the schema from type hints, the URI templates, the stdio loop and the token check each become one line or one decorator. Knowing what hides behind each line is how you debug a server that misbehaves in a host, and how you judge a library before you depend on it.
What you'll be able to do
- Map each piece you built by hand (dispatcher, schema_for, templates, stdio loop, token check) onto the SDK line that replaces it
- Write a small server with the SDK's decorator shape: tool, resource, prompt and run
- Run an async tool and two overlapping requests, and say why SDK servers are async
- Read the same server in Python and in TypeScript, and run it under the Inspector
Show the answer
Inside the SDK: a decorator or a setting replaces each one
The SDK is those pieces, packaged. You still need to know what they do, because that is how you debug a server in a host.
The idea: the SDK is the pieces you already wrote
This rests on Resources and prompts: a server offers tools, resources and prompts, and one dispatcher routes every method to them. The official SDKs do exactly that, and add the transports, the version rules and the authorization hooks around it.
| You wrote | The SDK line that replaces it |
|---|---|
| the dispatcher with its six checks (JSON-RPC 2.0 in depth) | built in: it parses, checks the shape and _meta, and routes |
schema_for(fn) | @mcp.tool() reads the signature and the docstring |
a URI template and match_template | @mcp.resource("docs://help/{id}") |
| a prompt and its arguments | @mcp.prompt() |
| the read, dispatch, write loop (Transports I: stdio) | mcp.run() |
| the HTTP handler (Transports II: Streamable HTTP) | mcp.run(transport="streamable-http") |
| the token check (Securing remote servers with OAuth) | a token verifier and auth settings |
your Session (Build a client) | the SDK's Client |
Two things the SDK adds that your versions didn't have. It is async: a request may wait on a database or an API, and while it waits the server answers other requests. And it follows the protocol's version rules for you, so one server can answer more than one revision.
import inspect JSON_TYPES = {str: "string", int: "integer", float: "number", bool: "boolean"} def get_campaign(id: str, days: int = 7, detailed: bool = False): pass params = inspect.signature(get_campaign).parameters print([n for n, p in params.items() if p.default is inspect.Parameter.empty], JSON_TYPES[params["days"].annotation])
Show the answer
['id'] integer
Only id has no default, so only id is required. The annotation int is looked up in the table and becomes the JSON Schema type integer. The decorator does this for every tool.
What each layer does for you
Think of the SDK as four layers stacked on your tool functions. The protocol layer parses each message, checks its shape and _meta, picks the method and builds the reply with the right id and result type. The server layer is the decorators: it keeps the registry of tools, resources and prompts, builds their definitions and answers tools/list, resources/read and prompts/get. The transport layer reads and writes bytes: stdin and stdout for a child process, or one POST per message over HTTP. The auth layer is optional: it calls your token verifier before any of the above sees the request.
Your code lives at the top, in the functions the decorators wrap. When something goes wrong, work down the stack: a wrong description is yours, a missing _meta is the host's, a stray byte on stdout is a transport problem, and a refused token is auth.
This map is also how you read an SDK's documentation. Each page of it is about one layer, and knowing which one tells you where to look first when a host reports an error.
Show the answer
Your own tool function: its docstring is the description
Work down the stack from the top. The description comes from your function's docstring, so a wrong one is yours to fix.
Why the SDK is async
Concurrency and async showed that waiting is cheap if you let something else run meanwhile. A tool that calls an API waits most of its time. In a blocking server, one slow call holds up every other request. In an async server, the slow tool awaits, and the server answers the next request in the gap. You write async def for a tool that waits, and a plain def for one that doesn't.
Show the answer
About 1 second: the waits overlap
While the first request waits, the server starts the second. The two waits overlap, so the total is about the longest wait, not the sum.
waits = {"a": 0.3, "b": 0.1, "c": 0.2}
order = sorted(waits, key=waits.get)
print(order)Show the answer
['b', 'c', 'a']
The shortest wait finishes first, so b leaves first, then c, then a. The replies are not in request order, and the ids say which reply answers which request.
The messages your MiniMCP sends, run for real in the next part. An SDK server sends the same fields for the same function (it may add a few, such as a title). Compare with the Inspector on your own machine.
Write a sentence or two, then compare it with a good answer in the lesson.
In Python: MiniMCP, a server with the SDK's shape
Here is a small server with the SDK's decorator shape, about 60 lines, built on the dispatcher you already know. It is in this lesson's setup, so every cell starts with it: MiniMCP, with tool, resource, prompt and run. Open the setup above the first cell to read it.
Setup (runs before every cell) · 78 lines
The lesson runs this once, before its first cell, and every cell, drill and example starts with what it defines. A cell that changes a setup object changes it for the cells after it, until the page reloads.
import asyncio import inspect import json PV = "io.modelcontextprotocol/protocolVersion" CAPS = "io.modelcontextprotocol/clientCapabilities" JSON_TYPES = {str: "string", int: "integer", float: "number", bool: "boolean"} class MiniMCP: def __init__(self, name): self.name = name self.tools, self.resources, self.prompts = {}, {}, {} def tool(self): def register(fn): sig = inspect.signature(fn).parameters schema = {"type": "object", "properties": {n: {"type": JSON_TYPES[p.annotation]} for n, p in sig.items()}, "required": [n for n, p in sig.items() if p.default is inspect.Parameter.empty]} self.tools[fn.__name__] = (fn, {"name": fn.__name__, "description": inspect.getdoc(fn) or "", "inputSchema": schema}) return fn return register def resource(self, uri): def register(fn): self.resources[uri] = fn return fn return register def prompt(self): def register(fn): self.prompts[fn.__name__] = fn return fn return register async def handle(self, msg): if "id" not in msg: return None method, params = msg["method"], msg.get("params", {}) meta = params.get("_meta", {}) if PV not in meta or CAPS not in meta: return self._error(msg, -32602, "Missing _meta") if method == "tools/list": return self._ok(msg, tools=[d for _, d in self.tools.values()]) if method == "tools/call": fn = self.tools[params["name"]][0] value = fn(**params.get("arguments", {})) if inspect.isawaitable(value): value = await value return self._ok(msg, content=[{"type": "text", "text": json.dumps(value)}], isError=False) if method == "resources/read": text = self.resources[params["uri"]]() return self._ok(msg, contents=[{"uri": params["uri"], "text": text}]) if method == "prompts/get": text = self.prompts[params["name"]](**params.get("arguments", {})) return self._ok(msg, messages=[{"role": "user", "content": {"type": "text", "text": text}}]) return self._error(msg, -32601, f"Method not found: {method}") def _ok(self, msg, **result): return {"jsonrpc": "2.0", "id": msg["id"], "result": {"resultType": "complete", **result}} def _error(self, msg, code, text): error = {"code": code, "message": text} return {"jsonrpc": "2.0", "id": msg["id"], "error": error} def run(self, lines): async def serve(): replies = await asyncio.gather(*(self.handle(json.loads(x)) for x in lines)) return [json.dumps(r) for r in replies if r is not None] return asyncio.run(serve())
mcp = MiniMCP("shop") @mcp.tool() def get_campaign(id: str, days: int = 7): """Get one campaign's metrics by id, such as cmp_101.""" return {"id": id, "days": days} @mcp.resource("docs://help/shipping") def shipping(): return "We ship in 2 to 4 business days." @mcp.prompt() def review(campaign_id: str): return f"Review campaign {campaign_id} in three sentences." meta = {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}} def line(id_, method, **params): return json.dumps({"jsonrpc": "2.0", "id": id_, "method": method, "params": {**params, "_meta": meta}}) for reply in mcp.run([line(1, "tools/call", name="get_campaign", arguments={"id": "cmp_103"}), line(2, "resources/read", uri="docs://help/shipping"), line(3, "prompts/get", name="review", arguments={"campaign_id": "cmp_103"})]): print(reply[:96])
Two requests at once
A tool that waits, called twice together. The replies come back in the order the waits finish, not the order the requests were sent. The ids say which is which.
Uses the setup above, 78 lines.
import asyncio mcp = MiniMCP("shop") @mcp.tool() async def slow_stock(sku: str, delay: float): """Check stock after a wait, like a call to a slow API.""" await asyncio.sleep(delay) return {"sku": sku, "in_stock": 12} meta = {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}} def call(id_, sku, delay): return {"jsonrpc": "2.0", "id": id_, "method": "tools/call", "params": {"name": "slow_stock", "arguments": {"sku": sku, "delay": delay}, "_meta": meta}} async def main(): first = asyncio.ensure_future(mcp.handle(call(10, "TENT-2", 0.03))) second = asyncio.ensure_future(mcp.handle(call(11, "MUG-1", 0.01))) order = [] for done in asyncio.as_completed([first, second]): order.append((await done)["id"]) return order print(asyncio.run(main()))
Request 10 was sent first but waits 0.03 seconds, and request 11 waits 0.01. The server starts both, and 11 finishes first. On a browser without JSPI, asyncio.run may not work; the output is the same on your own computer. This is why the pending table in the client matches by id.
Show the answer
11, then 10
The server starts both. The shorter wait finishes first, so reply 11 goes out first. The client matches replies by id.
Which parameters are required?
Write required_params(fn): return the list of parameter names that have no default, in order. This is what @mcp.tool() puts in the schema's required.
Uses the setup above, 78 lines.
import inspect def required_params(fn): return [] def demo(a: str, b: int = 1, c: bool = False): pass print(required_params(demo))
Which arguments did the call leave out?
Write missing_arguments(definition, arguments): definition is a tool definition with an inputSchema that has a required list. Return the required names that arguments doesn't contain, in the schema's order.
Uses the setup above, 78 lines.
def missing_arguments(definition, arguments): return [] schema = {"type": "object", "required": ["sku", "warehouse"]} print(missing_arguments({"inputSchema": schema}, {"sku": "TENT-2"}))
Write a sentence or two, then compare it with a good answer in the lesson.
In the SDK and a real host: Python and TypeScript, side by side
Purpose. Read the same server in the two main SDKs, and run it under the Inspector on your own machine.
Version 2 of each SDK implements the 2026-07-28 revision: the Python mcp package (version 2.3.0, with MCPServer where version 1 had FastMCP) and the TypeScript @modelcontextprotocol/server. Version 1 of each still gets fixes. Below, the Python card is your MiniMCP with the real names, and the TypeScript card is the same idea with the schema written in Zod.
The Inspector launches your server and lets you call its tools by hand: uv run mcp dev shop_server.py.
In an engineer's week. A team picks an SDK before it writes a single tool, and the choice mostly follows the language the team already uses. What goes wrong is trusting the SDK to enforce what only you know: that a tool is read-only, that an id belongs to the caller, that a result is small enough. The decorator builds the schema. It doesn't check your logic. So the review of an SDK server is the review of its tool functions: their descriptions, their limits and what each one is allowed to touch. The framework around them is the part that someone else has already tested, which is exactly why it is safe to stop writing it.
Goes deeper in
- Testing, designing and shipping servers: test a server like this one at three levels.
- Build a client: the client side of the SDK, and the
Sessionit replaces. - A tool registry for agents: a harness that loads these servers' tools.
Show the answer
Python reads type hints; TypeScript takes a Zod schema
Python's decorator inspects the signature. TypeScript's registerTool takes an explicit Zod object, and returns content blocks itself.
Run your server under the Inspector
Write the SDK version of a tool you care about, run it on your own computer under the Inspector, and report what you saw. The report is what you would hand a teammate who has to trust that it works.
It must
- Names the tool and its signature
- Gives the exact commands used
- Pastes the Inspector's tools/list entry
- Pastes one tools/call result
- Names one difference from MiniMCP
Go further
- Adds a resource or a prompt and shows it in the Inspector
The template
## The tool\nWhat it does, in one sentence, and its signature.\n\n## How I ran it\nThe exact commands.\n\n## What the Inspector showed\nPaste the tools/list entry and one tools/call result.\n\n## One thing that surprised me\nA difference from MiniMCP, or a bug I fixed.
Write a sentence or two, then compare it with a good answer in the lesson.
Practice what you just read
- 2 code examples you can edit and run
- a practice exercise that checks your code
- a 5-question quiz
- 9 review cards for spaced repetition
Try a quiz question
In the Python SDK, what does the @mcp.tool() decorator read to build a tool's inputSchema?
Before this lesson
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
- JSON-RPC 2.0 in depth FreeRequests, notifications, errors and a dispatcher built from scratch.35 min
- Versions and stateless requestsRevisions by date, the legacy handshake, per-request _meta and version negotiation.30 min
- Discovery, capabilities and the two erasserver/discover, declared capabilities, and talking to legacy and modern software alike.30 min
- Transports I: stdioNewline-delimited JSON over a subprocess's standard streams.30 min
- Transports II: Streamable HTTPOne endpoint, required headers, JSON or event-stream replies.40 min
- Build a server: toolsTool definitions, schemas from type hints, results and two kinds of error.45 min
- Resources and promptsReadable data, URI templates and reusable prompt templates.40 min
- The same server with the official SDKsYour registry and dispatcher on the SDK's decorator shape, in Python and TypeScript.40 min
- Build a clientMetadata on every request, version fallback, paging and caching.40 min
- Hosts: connecting servers to a modelMany servers, one agent: namespacing, routing and approvals.40 min
- Progress, subscriptions and multi-round-trip requestsLong-running work, change notifications and asking the user mid-call.45 min
- Securing remote servers with OAuthProtected resource metadata, PKCE, audiences and scope challenges.45 min
- MCP securityTool poisoning, rug pulls, confused deputies and local-server risks.40 min
- Lab: attack and defend a hostPoisoned tools, injected results, token replay and the defenses that stop each.40 min
- Testing, designing and shipping serversConformance checks, tool design for models, SDKs and deployment.40 min
- 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
- Capstone: a production MCP serverA complete, tested server for the practice shop.45 min
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