What You Will Build
Before writing a server of your own, you will look at a finished one from the outside. The course supplies a read-only preview of the inventory server; you run it through the SDK's own client, in the same process, and print everything a host would learn about it: its name and version, the protocol revision, its capabilities, and then its three kinds of offering, tools, resources and prompts, each with the details a host needs. By the end you can say who in a host uses each kind, and you have the piece of asynchronous Python that every client in the course relies on.
The preview server is the shape of what you will write yourself from the tools module on. Keep its folder when you finish: the next two lessons send messages to the same file.
The Bridge: Two Things at Once
The SDK client is asynchronous: its functions are declared with
async def, and calling one gives you a coroutine that does nothing
until it is awaited. The reason is that a client spends most of its time
waiting for a server to answer, and asynchronous code lets one program
wait for several things at once
(S90). You need
four pieces of it, and a ten-line script shows all four.
Starting state: the course environment active (the setup lesson created it and taught activation).
-
Create the exercise folder. macOS and Linux:
mkdir -p ~/mcp-practice/server-tour cd ~/mcp-practice/server-tourWindows PowerShell:
mkdir $HOME\mcp-practice\server-tour cd $HOME\mcp-practice\server-tour -
Save this as
two_tasks.py:"""Bridge: two tasks that wait at the same time.""" import asyncio import time async def count(label: str, seconds: float) -> str: await asyncio.sleep(seconds) return f"{label} done after {seconds} s" async def main() -> None: started = time.perf_counter() async with asyncio.TaskGroup() as group: first = group.create_task(count("first", 1)) second = group.create_task(count("second", 2)) print(first.result()) print(second.result()) print(f"both finished after {time.perf_counter() - started:.1f} s") asyncio.run(main()) -
Before running it, predict the last line: will both tasks finish after three seconds (one wait after the other) or two (the longer of the two)? Then run it:
python two_tasks.pyfirst done after 1 s second done after 2 s both finished after 2.0 s
The four pieces:
async defdeclares a coroutine function.countandmainare both one. Callingcount("first", 1)does not run it; it makes a coroutine object that will run when something awaits or schedules it.awaitpauses the current coroutine until the awaited thing finishes, and lets other coroutines run in the meantime.await asyncio.sleep(seconds)is a wait that gives up its turn; a client'sawait client.list_tools()is a wait for the server's reply.asyncio.run(main())starts the event loop, the scheduler that switches between coroutines, runsmainto the end and stops the loop. A script has exactly one of these, at the bottom.async withopens something that needs to be closed later even if the block fails. Here it is aTaskGroup: every task created inside it is started at once, and the block ends only when all of them are done.first.result()is then available. The SDK client is also used withasync with, which opens the connection and closes it at the end.
The last line is the proof that the two waits overlapped: 2.0 seconds, not 3.0.
Hosts, Clients and Servers
The specification names three roles (S41). A host is the application the user runs: an editor, a chat application, an agent. A server is a program that offers capabilities over the protocol; yours will be one. The host keeps one client per server; the client holds the connection and speaks the protocol. A host may have many clients, and a server never sees the other servers. The host is also where consent lives: it decides whether a tool may be called and what the user is shown.

One host, one client per server. Local servers run as child processes over standard input and output; remote ones answer over HTTP.
A server can be local or remote. A local server is started by the host as a child process and talks over its standard input and output, which the next lesson does by hand. A remote server listens for HTTP requests, which the transports module covers. The messages are the same either way (S59).
A server offers three kinds of thing, and the difference between them is who decides to use it (S05):
| Primitive | Controlled by | What it is | Example on the preview server |
|---|---|---|---|
| Tool | The model | A function the model may ask to call, described by a name, a description and an input schema | stock_level, list_parts, recount_bin |
| Resource | The application | Content the host reads and places in context, named by a URI, with a MIME type | inventory://summary; the template inventory://bins/{bin_id} |
| Prompt | The user | A prepared request the user picks, with named arguments, returned as messages | reorder_report, bin_audit |
Two rules apply to tools from the first time you see them. First, the specification expects a human in the loop: a host should get the user's consent before a tool runs, and a server must assume it will be called only after that (S47). Second, a tool's name, description and results come from the server and are untrusted input to the host and its model: a server could describe a tool misleadingly, and a host must not trust descriptions blindly. The security lesson shows a poisoned description in a server written for that purpose; for now, remember that your descriptions are read by a model and must be honest and precise.
Exercise: the Tour
Goal: run the preview server through the SDK client and print what a host would learn about it, then classify what you see.
Starting state: the course environment active, in
~/mcp-practice/server-tour, with two_tasks.py from the bridge.
Effects: creates two scripts in the folder. The client runs the server in the same process, so nothing is started separately and no network is used.
-
Save this as
preview_server.py:"""A preview of the inventory server: read-only tools, resources and prompts. Supplied by the course for the tour; you write your own server from the tools module onward. """ import json from mcp.server import MCPServer from mcp.server.mcpserver import Context, UserMessage from mcp.server.mcpserver.exceptions import ResourceNotFoundError, ToolError PARTS = { "bolt-m4": {"name": "Hex bolt M4", "bin": "A1", "quantity": 120, "reorder_level": 40, "unit": "each"}, "bolt-m6": {"name": "Hex bolt M6", "bin": "A1", "quantity": 15, "reorder_level": 40, "unit": "each"}, "nut-m4": {"name": "Hex nut M4", "bin": "A2", "quantity": 80, "reorder_level": 25, "unit": "each"}, "washer-m4": {"name": "Flat washer M4", "bin": "A2", "quantity": 0, "reorder_level": 20, "unit": "each"}, "belt-m6": {"name": "Drive belt M6", "bin": "B1", "quantity": 7, "reorder_level": 10, "unit": "each"}, "cable-m4": {"name": "Control cable M4", "bin": "B2", "quantity": 42, "reorder_level": 10, "unit": "metre"}, } mcp = MCPServer("inventory-preview", version="0.1.0", instructions="Read-only view of a workshop parts inventory.") @mcp.tool() def stock_level(sku: str) -> str: """Report how many units of one part are in stock and where.""" part = PARTS.get(sku) if part is None: raise ToolError(f"Unknown part {sku!r}; known parts: {sorted(PARTS)}") return f"{sku}: {part['quantity']} {part['unit']} in bin {part['bin']}" @mcp.tool() def list_parts(bin_id: str | None = None) -> str: """List parts, optionally only those in one bin.""" rows = [f"{sku}: {part['quantity']} {part['unit']}, bin {part['bin']}" for sku, part in PARTS.items() if bin_id is None or part["bin"] == bin_id] return "\n".join(rows) or "no parts match" @mcp.tool() async def recount_bin(bin_id: str, ctx: Context) -> str: """Recount one bin, reporting progress part by part.""" skus = [sku for sku, part in PARTS.items() if part["bin"] == bin_id] for done, sku in enumerate(skus, start=1): await ctx.report_progress(done, total=len(skus), message=f"counted {sku}") return f"bin {bin_id}: {len(skus)} parts counted" @mcp.resource("inventory://summary") def summary() -> str: """Totals for the whole inventory.""" total = sum(part["quantity"] for part in PARTS.values()) low = sum(1 for part in PARTS.values() if part["quantity"] < part["reorder_level"]) return f"{len(PARTS)} parts, {total} units in stock, {low} below their reorder level" @mcp.resource("inventory://bins/{bin_id}", mime_type="application/json") def bin_contents(bin_id: str) -> str: """The parts stored in one bin, as JSON.""" rows = {sku: part["quantity"] for sku, part in PARTS.items() if part["bin"] == bin_id} if not rows: raise ResourceNotFoundError(f"inventory://bins/{bin_id}") return json.dumps(rows) @mcp.prompt() def reorder_report(threshold: str = "20") -> str: """Ask for a reorder proposal for parts below a quantity.""" return f"List every part with fewer than {threshold} units and propose an order quantity for each." @mcp.prompt() def bin_audit(bin_id: str) -> list[UserMessage]: """Ask for an audit of one bin.""" return [UserMessage(f"Audit bin {bin_id}: compare the recorded quantities with a physical count and report differences.")] if __name__ == "__main__": mcp.run()You do not need to understand the server yet; the tools module teaches each decorator. Notice only its shape: one
MCPServerobject namedmcp, three functions marked@mcp.tool(), two marked@mcp.resource(...)and two marked@mcp.prompt(), and a main guard that starts it over standard input and output when run directly. -
Save this as
client_tour.py:"""Tour the preview server through the SDK client, in memory.""" import asyncio from mcp import Client import preview_server async def main() -> None: async with Client(preview_server.mcp) as client: print("server:", client.server_info.name, client.server_info.version) print("protocol:", client.protocol_version) print("instructions:", client.instructions) print("capabilities:", client.server_capabilities.model_dump(exclude_none=True)) print("\n== tools (the model may call these)") for tool in (await client.list_tools()).tools: params = ", ".join(tool.input_schema.get("properties", {})) or "no parameters" print(f" {tool.name}({params}): {tool.description}") print("\n== resources (the application reads these)") for resource in (await client.list_resources()).resources: print(f" {resource.uri} [{resource.mime_type}]: {resource.description}") for template in (await client.list_resource_templates()).resource_templates: print(f" {template.uri_template} [{template.mime_type}]: {template.description}") print("\n== prompts (the user picks these)") for prompt in (await client.list_prompts()).prompts: args = ", ".join(f"{a.name}{'' if a.required else '?'}" for a in prompt.arguments or []) print(f" {prompt.name}({args}): {prompt.description}") print("\n== one of each") result = await client.call_tool("stock_level", {"sku": "belt-m6"}) print("tool result:", result.content[0].text) contents = await client.read_resource("inventory://summary") print("resource text:", contents.contents[0].text) rendered = await client.get_prompt("bin_audit", {"bin_id": "A1"}) print("prompt message:", rendered.messages[0].role, "->", rendered.messages[0].content.text) asyncio.run(main()) -
Run the tour:
python client_tour.pyserver: inventory-preview 0.1.0 protocol: 2026-07-28 instructions: Read-only view of a workshop parts inventory. capabilities: {'prompts': {'list_changed': True}, 'resources': {'subscribe': True, 'list_changed': True}, 'tools': {'list_changed': True}} == tools (the model may call these) stock_level(sku): Report how many units of one part are in stock and where. list_parts(bin_id): List parts, optionally only those in one bin. recount_bin(bin_id): Recount one bin, reporting progress part by part. == resources (the application reads these) inventory://summary [text/plain]: Totals for the whole inventory. inventory://bins/{bin_id} [application/json]: The parts stored in one bin, as JSON. == prompts (the user picks these) reorder_report(threshold?): Ask for a reorder proposal for parts below a quantity. bin_audit(bin_id): Ask for an audit of one bin. == one of each tool result: belt-m6: 7 each in bin B1 resource text: 6 parts, 264 units in stock, 3 below their reorder level prompt message: user -> Audit bin A1: compare the recorded quantities with a physical count and report differences.
Success: the four header lines, three tools, one resource, one template, two prompts, and the three results, exactly as above. Nothing appears on standard error for an in-memory client.
How the Client Works
Client(preview_server.mcp) is given the server object itself, so the
client and the server run in one process with no child process and no
port; the SDK's client accepts a server object, a command to launch or a
URL (S28). async with
opens the connection and, because the client opens in its default mode,
asks the server to describe itself before the block starts. That is where
the four header attributes come from: server_info (name and version),
protocol_version (the revision both sides are speaking),
instructions (a sentence the server offers to the model) and
server_capabilities (which features the server supports).
Inside the block, every call is awaited. list_tools(),
list_resources(), list_resource_templates() and list_prompts()
return result objects with a list attribute each; the script prints the
parts a host would show. call_tool(name, arguments),
read_resource(uri) and get_prompt(name, arguments) exercise one of
each kind.
The client exposes the wire's names in Python style: the server sends
listChanged, the client attribute is list_changed; the server sends
inputSchema, the client attribute is input_schema. The next lesson
shows the wire spellings.
Reading the Output
Tools, for the model. Each line shows the name, the parameter names
from the input schema, and the description. A host passes all three to
its model, which chooses a tool and fills its arguments; the host then
asks the user and calls it. recount_bin is declared async def and
reports progress while it runs, which the next lesson shows on the wire.
Resources, for the application. inventory://summary is a fixed
resource with a plain-text MIME type. inventory://bins/{bin_id} is a
template: the braces mark a part of the URI the host fills in, so one
declaration covers every bin, and its contents are JSON
(S48).
A host reads resources when its application logic decides to, for
example to attach the summary to a conversation; the model does not call
them.
Prompts, for the user. A prompt has named arguments; the ? the
script prints marks an optional one (threshold has a default on the
server). Getting a prompt returns messages with a role, here one user
message, ready to be placed into a conversation
(S49).
A host shows prompts in a menu or as commands for the user to pick.
Capabilities. The server declares tools, resources and prompts
with list_changed: True and resources.subscribe: True. The SDK
declares these by default; they mean the server may send change
notifications and accept subscriptions, which the staying-in-sync module
teaches. A host reads this dictionary to know what to expect.
Three more things a server can do appear later and are worth naming now, because the understanding check uses them. Elicitation is a server asking the user a question in the middle of a tool call (the server initiates it, the host shows it); logging is a server sending log messages to the host; a notification is a one-way message with no reply, which either side may send, such as "my tool list changed". The inside-the-handler and staying-in-sync modules build each one.
When It Goes Wrong
| Symptom | Cause | Fix |
|---|---|---|
ModuleNotFoundError: No module named 'preview_server' | The client was run from another folder; the import needs both files in the current folder | cd into server-tour |
python preview_server.py prints nothing and does not return | The server is running over standard input and output, waiting for a client; nothing is wrong | Press Ctrl+C; the next lesson talks to it that way |
RuntimeError: Client must be used within an async context manager (or similar wording) | A method was called on a Client that was created without async with | Put the calls inside the async with Client(...) as client: block |
RuntimeWarning: coroutine '...' was never awaited and an empty result | A client method was called without await | Add await |
both finished after 3.0 s | The second task was awaited before the first was created (sequential), not created inside the group | Create both tasks in the TaskGroup block before the block ends |
Your Turn: a Third Task and Six Situations
-
Predict the last line if a third task sleeping for 1.5 seconds joins the group. Then save this as
three_tasks.pyand run it:"""Your turn: a third task joins the group.""" import asyncio import time async def count(label: str, seconds: float) -> str: await asyncio.sleep(seconds) return f"{label} done after {seconds} s" async def main() -> None: started = time.perf_counter() async with asyncio.TaskGroup() as group: first = group.create_task(count("first", 1)) second = group.create_task(count("second", 2)) third = group.create_task(count("third", 1.5)) print(first.result()) print(second.result()) print(third.result()) print(f"all finished after {time.perf_counter() - started:.1f} s") asyncio.run(main()) -
For each situation, say which listed item on the preview server a host would use, and who initiates it: (a) the model wants to know how many
bolt-m6are left; (b) the application attaches an overview of the inventory to the start of every conversation; (c) the user types a slash command to start an audit of bin A1; (d) the application wants the parts in bin B2 as data it can parse; (e) the model wants to recount a bin and the host wants to show a progress bar; (f) the user wants a reorder proposal for parts under 15 units.
Reset and Clean Up
Both scripts are stateless: run them as often as you like. Keep the
folder: the next two lessons copy preview_server.py from it, and the
versions lesson removes it at the end of the module. Only confirm that
the shared folders are still there. macOS and Linux:
cd ~/mcp-practice
ls
Windows PowerShell:
cd $HOME\mcp-practice
ls
.venv, data and server-tour are listed.
Check Your Understanding
Classify each described feature as a tool, a resource, a prompt, an elicitation, logging or a notification, and name who initiates it:
- The server tells the host "the list of tools has changed" without being asked.
- The host's model asks for the stock level of one part.
- Halfway through deleting a bin, the server asks the user "Really delete bin C2 and its 7 parts?".
- The host's application reads
inventory://summaryto put it in the first message of a conversation. - The user picks "Reorder report" from a menu and types a threshold.
- The server sends "recount of bin A1 took 0.4 s" at level
infofor the host to record.
Answer and Reasoning
Your turn
-
all finished after 2.0 s: the three waits overlap, so the group takes as long as its longest member (2 seconds), not the sum (4.5). The output is:first done after 1 s second done after 2 s third done after 1.5 s all finished after 2.0 s -
(a) the tool
stock_level, initiated by the model (with the host's consent step); (b) the resourceinventory://summary, initiated by the application; (c) the promptbin_auditwithbin_idA1, initiated by the user; (d) the resource templateinventory://bins/{bin_id}filled in asinventory://bins/B2, initiated by the application, with JSON contents; (e) the toolrecount_bin, initiated by the model, whose progress messages the host turns into a bar; (f) the promptreorder_reportwiththreshold15, initiated by the user.
Understanding check
- A notification, initiated by the server; it has no reply.
- A tool call, initiated by the model, carried out by the host after consent.
- An elicitation, initiated by the server during a tool call and shown to the user by the host.
- A resource read, initiated by the application.
- A prompt, initiated by the user; the host sends the argument and receives messages.
- Logging, initiated by the server; the host records or shows it.