Index Ai Academy
Phase 9 · Building servers

The same server with the official SDKs

Your registry and dispatcher on the SDK's decorator shape, in Python and TypeScript.

About 40 minutes · Versions checked November 2026 · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

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
Quick check
You wrote a dispatcher, a schema builder, a stdio loop and a token check by hand. In a server built with an official SDK, where do those pieces live?
  1. In the model, which parses the messages itself
  2. Inside the SDK: a decorator or a setting replaces each one
  3. In the host, which does it all for the server
  4. Nowhere: SDK servers don't need them
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 wroteThe 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.

Quick check
From the lesson on building a server's tools: a parameter without a default is required, and each Python type becomes a JSON type. What does this print?
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])
  1. ['id'] int
  2. ['id', 'days', 'detailed'] integer
  3. [] integer
  4. ['id'] integer
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.

Quick check
A host reports that a tool's description is misleading. Which layer do you look at?
  1. Your own tool function: its docstring is the description
  2. The transport layer, which moves bytes over stdio or HTTP
  3. The protocol layer, which checks each message's shape
  4. The auth hooks, which check the token on each request
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.

Quick check
Two requests arrive together. Each calls an async tool that waits 1 second for an API. In an async server, about how long until both are answered?
  1. About 1 second: the waits overlap
  2. About 0 seconds
  3. About 2 seconds: one after the other
  4. It depends on the model
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.

Quick check
Three requests start together, and each waits the time shown before it answers. In what order do the replies leave?
waits = {"a": 0.3, "b": 0.1, "c": 0.2}
order = sorted(waits, key=waits.get)
print(order)
  1. ['c', 'b', 'a']
  2. ['a', 'c', 'b']
  3. ['b', 'c', 'a']
  4. ['a', 'b', 'c']
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.

Try it now

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.

In your own words
Pick one thing you built by hand in this phase and name the SDK line that replaces it.

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

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

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.

Quick check
A server gets request 10 (wait 3 seconds) and request 11 (wait 1 second) together. In what order do the replies leave?
  1. They leave together
  2. 11, then 10
  3. Only one of them
  4. 10, then 11
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.

Drill

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))
In the lesson, your code is checked as you write it.
Drill

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"}))
In the lesson, your code is checked as you write it.
In your own words
Why does an async server return replies in a different order from the requests, and how does the client cope?

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

Quick check
The Python and TypeScript cards register the same tool. What is the main difference in how the schema is made?
  1. TypeScript reads the schema from the docstring
  2. Python has no schema, and the model writes one
  3. Python reads type hints; TypeScript takes a Zod schema
  4. Both ask the model to write the schema each time
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.

Written brief · Run report

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.
In the lesson, you write over it, 120 to 350 words, and the tutor can mark it.
In your own words
Your SDK server's schema is generated from type hints. What can the schema not tell a model, and where does that information go?

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?

  1. The function's signature and type hints
  2. The model's reply to the first request
  3. The host's config file for this server
  4. The server's log of earlier requests

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

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