MCP server project · Chapter 2 of 12
stdio and the inspector
By the end of this chapter DabbaDrop's MCP server also runs the way Claude Desktop runs a server: as a child process that speaks JSON-RPC on its stdin and stdout. You know why nothing else may print to stdout, and you have your own inspector, a real MCP client that starts the server, describes it and calls its tools, with only the environment the server needs. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: The protocol
- 3 tasks
- Python
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
Why you need this
Tara uses Claude Desktop. The office manager's script from October ran on a laptop too. Assistants on a person's own computer usually do not reach a server over HTTP: they start the server themselves, as a program on the same machine, and talk to it through its input and output. That is the stdio transport. Farah's one way in has to work there too, or Tara's assistant is left out of launch week.
Chapter 1's server only answers POST /mcp. It has no way to run as a child process. And so far you have only been the client by hand: peek and the request pane send one message at a time. Before Claude Desktop ever starts DabbaDrop's server, Kunal wants a client of your own that does what it does (start the server, shake hands, list the tools, call one) and shows you the answers. The lab has no internet, so there is no inspector to download: you write it.
There is a trap on the way, and it is real. The ordering API prints a log line for every request it answers. Over HTTP that line is harmless. Over stdio it lands where the client is reading protocol messages.
The lesson
Tour of the codebase
New or changed since chapter 1:
mcp_server/__main__.py changed: python -m mcp_server --stdio calls stdio.run_stdio()
mcp_server/server.py given now: chapter 1's build_server
mcp_server/rpc.py given now: chapter 1's message, reply_of, result_of, kind
mcp_server/stdio.py yours: run_stdio (Task 1)
mcp_server/inspector.py yours: stdio_params, describe, call (Task 2), server_env (Task 3);
the command line at the bottom is given
python -m mcp_server without --stdio is still the development server on port 8000, with POST /mcp. The saved requests are chapter 1's handshake, done in full this time: initialize, "Say you are ready" (notifications/initialized, answered 202 with no body), tools/list and one find_slots call.
stdio: a conversation through a pipe
Every process has three standard streams: stdin (what it reads), stdout (what it writes) and stderr (a second output, meant for errors and logs). When one program starts another, the parent can hold the other ends of those streams. That is a child process.
The stdio transport uses exactly that. The client starts the server with a command, writes each JSON-RPC message to the server's stdin as one line of JSON, and reads each reply from the server's stdout, one line each. No port, no URL, no network: the server lives as long as the client keeps it.
Here is the finished server, driven by hand: three lines in (initialize, the initialized notification, a find_slots call), and what came out on stdout:
$ (cat three-lines.jsonl; sleep 3) | python -m mcp_server --stdio
{"jsonrpc":"2.0","id":1,"result":{"capabilities":{"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}},"instructions":"DabbaDrop delivers home-style lunch dabbas in Mumbai: ...","protocolVersion":"2025-11-25","serverInfo":{"name":"dabbadrop","title":"DabbaDrop","version":"1.0.0"}}}
{"jsonrpc":"2.0","id":2,"result":{"content":[{"text":"{\n \"slot_id\": 80,\n \"starts_at\": \"2026-11-03T12:30:00+05:30\",\n \"ends_at\": \"2026-11-03T13:00:00+05:30\",\n \"places_left\": 30\n}","type":"text"}],"isError":false,"structuredContent":{"result":[{"slot_id":80,"starts_at":"2026-11-03T12:30:00+05:30","ends_at":"2026-11-03T13:00:00+05:30","places_left":30}]}}}
The same messages as chapter 1, without HTTP around them: two replies, and nothing for the notification. There is no session id either: the process itself is the session. The sleep 3 keeps stdin open while the tool runs. Without it, stdin ends at once, the server takes that as the client hanging up, and the call is cut short:
{"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"Connection closed"}}
With the SDK, serving a server over stdio is one call, server.run("stdio"). It reads stdin and writes stdout until the client hangs up. The same MCPServer serves both ways: build_server() does not change.
stdout is the protocol
The client reads every line on stdout as a JSON-RPC message. A line that is anything else is an error on the client's side. Here is a made-up chutney server whose tool prints a log line with print:
@server.tool(name="find_chutneys", description="The chutneys a zone's kitchen makes today.")
async def find_chutneys(zone: str) -> list[str]:
print(json.dumps({"tool": "find_chutneys", "zone": zone}))
return ["Green chutney", "Imli chutney"]
Started over stdio by the SDK's client, which calls the tool once:
{'result': ['Green chutney', 'Imli chutney']}
Failed to parse JSONRPC message from server
Traceback (most recent call last):
File "/usr/local/lib/python3.13/site-packages/mcp/client/stdio.py", line 222, in _parse_line
...
pydantic_core._pydantic_core.ValidationError: 11 validation errors for union[JSONRPCRequest,JSONRPCNotification,JSONRPCResponse,JSONRPCError]
JSONRPCRequest.jsonrpc
Field required [type=missing, input_value={'tool': 'find_chutneys', 'zone': 'Dadar'}, input_type=dict]
...
The line was JSON, but not JSON-RPC: no jsonrpc, no id, no method. The client tried each kind of message and none fitted. With print(..., file=sys.stderr) the same line goes to stderr instead, the client shows it as the server's log, and nothing fails:
{"tool": "find_chutneys", "zone": "Dadar"}
{'result': ['Green chutney', 'Imli chutney']}
Notice when the bad line arrived: after the result. SDK 2.3.0 points stdout at stderr while it serves, so a stray print cannot land in the middle of a reply. But print keeps its text in Python's output buffer, and that buffer is written out when the process ends, to the real stdout, which the client is still reading. Version 1 of the SDK did not move stdout at all. Do not lean on either: only the SDK writes to stdout.
The ordering API's log is the trap
DabbaDrop's tools call the ordering API inside the same process, and the API's request log is a print of one JSON line per request. In app/main.py:
quiet = os.environ.get("LOG_REQUESTS") == "off"
app.middleware("http")(request_log(write=(lambda line: None) if quiet else print))
The variable is read once, when the API is made. The tools make it the first time they need it (ordering_api() in dabba_api.py). So run_stdio has to switch it off before anything can make the API, which is why the stub says to import build_server inside the function, after setting it.
Forget it, and the inspector, after its call worked, prints:
Failed to parse JSONRPC message from server
...
JSONRPCRequest.jsonrpc
Field required [type=missing, input_value={'id': 'df08b75f6a32470c9...: 13.5, 'user_id': None}, input_type=dict]
...
Those are the API's GET /zones and GET /zones/6/slots lines. Timed from a client that writes the three lines and then waits:
0.53s {"jsonrpc":"2.0","id":1,"result":{"capabilities":{"prompts":{"listChanged":false},"resourc
0.78s {"jsonrpc":"2.0","id":2,"result":{"content":[{"text":"{\n \"slot_id\": 79,\n \"starts_at
3.07s closing stdin
3.07s {"id": "094d08cee06845329161d333bfef4d94", "method": "GET", "path": "/zones", "status": 20
3.07s {"id": "d76f0a2061014f65947865f178f89b46", "method": "GET", "path": "/zones/6/slots", "sta
(Each line cut at 90 characters.) The replies came on time; the log lines came when the client hung up and the server stopped.
The inspector: a client of your own
The SDK has a client too, Client (from mcp import Client). Give it StdioServerParameters and it starts the server, does the whole handshake, and gives you methods for the rest. Here is a client of the chutney server:
params = StdioServerParameters(command=sys.executable, args=["chutney_stdio.py"])
async with Client(params) as client:
result = await client.call_tool("find_chutneys", {"zone": "Dadar"})
print(result.structured_content)
StdioServerParameterssays how to start the server:commandandargs(the program and its arguments),env(its environment) andcwd(the folder to start it in).sys.executableis the Python running now, so the server gets the same installed packages.async with Client(params)starts the process and sends initialize andnotifications/initialized. Inside,client.server_info(.name,.version),client.protocol_versionandclient.instructionsare already known.await client.list_tools()sends tools/list; its.toolseach have.name,.descriptionand.input_schema, a dict whose"required"lists the parameters a call must send.await client.call_tool(name, arguments)sends tools/call. A tool that fails does not raise: the result's.is_erroris true and its.contentholds the text parts. Otherwise.structured_contentis the data.
python -m mcp_server.inspector puts your functions on the command line. With all three tasks done:
$ python -m mcp_server.inspector tools
{
"server": "dabbadrop",
"version": "1.0.0",
"protocol": "2026-07-28",
"instructions": "DabbaDrop delivers home-style lunch dabbas in Mumbai: ...",
"tools": [
{
"name": "find_slots",
"description": "Wraps GET /zones/{zone_id}/slots for a day.",
"required": [
"zone",
"date"
]
}
]
}
$ python -m mcp_server.inspector call find_slots '{"zone": "Powai", "date": "2026-11-03"}'
{
"ok": false,
"error": "Error executing tool find_slots: DabbaDrop does not deliver to Powai. It delivers to Andheri West, Goregaon, Malad, Dadar, Bandra, Thane."
}
Two protocol versions
The inspector says 2026-07-28; peek and the request pane said 2025-11-25. MCP's versions are dates. A client asks for the newest version it knows, and the server answers with the version they will use. The SDK's client asks for 2026-07-28, the newest; peek and the pane ask for 2025-11-25. DabbaDrop's server speaks both, so both work. For the tools in this project, the messages you read are the same.
What the server may see
A stdio server starts with only the environment its client gives it. Give StdioServerParameters no env, and the SDK passes a small default set; in the lab that is only HOME and PATH. Then the server has no DATABASE_URL and reads its own default database, not yours. The Check says so:
stdio_params() does not give the server DATABASE_URL; pass env=server_env()
So the inspector passes some names on. Which ones is Task 3, and Kunal's question. The lab's own terminal shows why the answer matters: handing over the whole environment gives the server all of this, from the Check:
server_env() hands the server APP_ENV, APP_PORT, GPG_KEY, HOSTNAME, JWT_SECRET, LABD_CACHE, LABD_MODELS, LABD_PACK, LABD_PACKS, LABD_STORY, LAB_CHAPTER_DIR, LC_CTYPE, LOG_REQUESTS, OLDPWD, OPENAI_API_KEY, OPENAI_BASE_URL, PAYMENTS_WEBHOOK_SECRET, PGDATA, PGDATABASE, PGHOST, PGUSER, PIP_DISABLE_PIP_V
Think about what a developer's terminal holds on a normal day while an assistant runs.
Your turn
- Task 1, stdio.py,
run_stdio:LOG_REQUESTSoff first, then import and build the server, then serve it over stdio. The trap: the API made before the variable is set. - Task 2, inspector.py,
stdio_params,describe,call: how to start the server; what it says about itself and its tools; one call, as ok and a result, or not ok and the error's text. The trap: readingstructured_contentof a failed call (it is None). - Task 3, inspector.py,
server_env: only the names inPASSED_ONthat are set and not empty. Kunal will ask: why not give the server the client's whole environment,os.environ, and be done?
Try it: python -m mcp_server.inspector tools, then python -m mcp_server.inspector call find_slots '{"zone": "Thane", "date": "2026-11-03", "time": "12:30"}'. Run python -m mcp_server and send the saved requests in order to see the same handshake over HTTP. Then press Check.
What you build: 3 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
stdio.py: the server over stdio
Write run_stdio() in mcp_server/stdio.py, which python -m mcp_server --stdio calls. It sets the environment variable LOG_REQUESTS to off first (the ordering API in this process prints a log line per request to stdout otherwise), then imports build_server, makes the server and runs it over stdio with server.run("stdio").
The Check starts python -m mcp_server --stdio as a child process, writes initialize, the initialized notification and a find_slots call for Thane on its stdin, one JSON line each, and reads its stdout: every line must be a JSON-RPC message, and the call's reply must hold slots 79, 80 and 81.
- Task 2
inspector.py: a client of the server
Write stdio_params, describe and call in mcp_server/inspector.py. stdio_params() returns StdioServerParameters with command sys.executable, args -m mcp_server --stdio, env server_env() and cwd the project's folder (PROJECT, as a string). describe(client) returns {"server", "version", "protocol", "instructions", "tools": [{"name", "description", "required"}]} from the connected client. call(client, name, arguments) calls the tool and returns {"ok": True, "result": the structured content}, or {"ok": False, "error": the text parts joined with a space} when the result is an error.
The Check gives your describe and call a client of the server in memory, calls find_slots for Thane and for Powai, then starts the server over stdio with your stdio_params and describes it.
- Task 3 · interview question
Interview: inspector.py, what the server may see
Write server_env() in mcp_server/inspector.py. It returns a dict of the names in PASSED_ON (PATH, HOME, DATABASE_URL, DABBA_MCP_TOKEN) that are set and not empty in os.environ, with their values, and nothing else.
The Check sets PATH, HOME, DATABASE_URL, OPENAI_API_KEY, JWT_SECRET and PAYMENTS_WEBHOOK_SECRET, with and without DABBA_MCP_TOKEN, and reads what your server_env would hand the server.
Kunal will ask: why not give the server the client's whole environment, os.environ, and be done?
What you will learn
- stdio: standard input, output and error, and how a client talks to a child process through them, one JSON message per line.
- Why stdout is the protocol: what a client does with a line that is not JSON-RPC, shown with the ordering API's own request log.
- server.run("stdio"): the SDK serving the same server over stdio.
- The SDK's Client: StdioServerParameters, the handshake it does for you, list_tools and call_tool, and a tool error as a result.
- Protocol versions: why the SDK's client agrees 2026-07-28 and peek 2025-11-25.
- The server's environment: what a stdio server may be given, and why not everything.
More in The protocol
Build "stdio and the inspector" yourself
DabbaDrop wants AI assistants like Claude Desktop to order for its members, safely. You build the MCP server that lets them, and only as the member who allowed it. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.