Build and Deploy MCP Integrations
Build a Model Context Protocol client and server, then verify the integration with a compatible host.
Newline-delimited JSON over a subprocess's standard streams.
Why can a single debug print break an otherwise correct local server?
The host reads standard output as a stream of protocol messages. Keep human-facing logs on standard error so every output frame can be decoded as JSON.
Host writes a framed request to the server's standard input
Server dispatches it and writes diagnostics to standard error
Host reads the framed reply from standard output
Host writes a framed request to the server's standard input
Server dispatches it and writes diagnostics to standard error
Host reads the framed reply from standard output
Given Host writes a framed request to the server's standard input and Host reads the framed reply from standard output, write down the missing step that connects them.
Server dispatches it and writes diagnostics to standard error
Now take Server dispatches it and writes diagnostics to standard error and the result above. Write an input and an implementation that could produce this trace.
Host writes a framed request to the server's standard input. Check that your implementation produces the result shown above.
The client gets a decode error before the first reply. The server just printed a startup banner to standard output. What should change?
Move the banner to standard error and keep standard output for protocol frames. Then test the server by starting the real subprocess and decoding its first reply.
Check this when debugging. Using print() for debugging inside a stdio server.
Most MCP servers people install are local: a file system server, a git server, a database helper. They run on your own machine, started by the app you're using, and they talk over the oldest interface in computing, standard input and output. It's simple, needs no network or ports, and works in every language. It also has one famous trap that breaks more first servers than any other bug.
The app tries to read it as a protocol message and fails
On stdio, stdout carries only JSON-RPC messages, one per line. Anything else there breaks the host's parsing, so logs go to stderr.
This rests on JSON-RPC 2.0 in depth: the messages are the same four shapes. This lesson is only about the wire they travel on when the server is a program on your own machine.
Picture two people in adjoining rooms, passing notes through a slot in the wall. That's the stdio transport. A transport is how messages physically travel. With this one, the host (Claude Code, Claude Desktop, an editor) starts the server as a child process, a program it launches and controls. Every process has three standard streams:
Hosts list local servers in a config file. The shape varies by app, but it's usually a command, its arguments, and environment variables:
{
"mcpServers": {
"shop": {
"command": "uv",
"args": ["run", "shop_server.py"],
"env": {"SHOP_API_KEY": "sk_test_..."}
}
}
}
Notice how credentials arrive: through environment variables. The spec says stdio servers should take credentials from the environment, not run the OAuth flow used by remote servers. The key sits in this file as plain text, so use a test or read-only key while you build, and keep a config that holds a real key out of version control.
stderr
stderr is the side notepad: hosts keep it for people. stdout is the protocol channel, and stdin carries requests in.
A stream of bytes has no built-in message boundaries. It's a long strip of tape with no gaps. So both sides need a framing rule, which says where one message ends and the next begins. MCP's rule for stdio is the simplest possible: each message is one line of JSON, ended by a newline, and a message must never contain a raw newline inside it.
That sounds fragile, since text often contains newlines. But JSON escapes them. A newline inside a string is written as the two characters \n, so json.dumps never produces a raw line break unless you ask it to indent:
import json msg = {"jsonrpc": "2.0", "id": 1, "result": {"content": [{"type": "text", "text": "line one\nline two"}]}} line = json.dumps(msg) print(line) print("raw newlines inside:", "\n" in line) print("with indent=2:", "\n" in json.dumps(msg, indent=2), "<- never do this on stdio")
import json messages = [{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}, {"jsonrpc": "2.0", "method": "notifications/progress"}] stream = "".join(json.dumps(m) + "\n" for m in messages) received = [json.loads(line) for line in stream.splitlines()] print(len(received), ["id" in m for m in received])
2 [True, False]
json.dumps without an indent writes each message on one line, and the newline after it marks where the message ends. The reader splits on newlines and gets the two messages back: a request and a notification. That is all the framing the stdio transport has.
stream = '{"id":1}\n{"id":2}\n' print(len(stream.strip().split("\n")))
2
strip removes the last line break, and split cuts what's left into 2 lines. One JSON message per line, so the line break is the frame between messages.
json.dumps(msg, indent=2) a bug for a stdio MCP server?Indenting adds raw newlines, so one message spans several lines and the host can't parse it
The host reads one line as one message. A pretty-printed message arrives as several broken fragments.
On stdio, stdout is the protocol channel. Think of an old telegraph line, where everything on the wire gets read as the message. The server must never write anything to stdout that isn't a valid MCP message. Now picture a tool function with a friendly debug line:
def get_campaign(campaign_id): print("looking up", campaign_id) # writes to stdout! return fetch(campaign_id)
That stray text lands in the middle of the host's message stream. The host tries to parse looking up cmp_103 as JSON, fails, and typically drops the connection. The server "works" when you test the function directly, and breaks the moment it runs inside a host.
The fixes:
print(..., file=sys.stderr), or use logging, which writes to stderr by default.In plain words: stdout is for protocol messages and nothing else. Everything meant for humans goes to stderr.
The host reads stdout as protocol and can't parse it
In a direct test, the text just shows on your screen. Inside a host, it lands in the message stream, the JSON parse fails, and the connection is usually dropped.
The three pipes with the exact bytes. Try the stray print on the reply line.
Write a sentence or two, then compare it with a good answer in the lesson.
This part writes the loop at the heart of a stdio server and the two helpers that keep stdout clean.
A stdio server is a loop, like a clerk working through an in-tray:
Real SDK servers are async, so several requests can be in flight and replies can go out in a different order. The ids match them up; a simple loop like this one answers one at a time.
Reads from a pipe arrive in arbitrary pieces, so a message can be split across two reads. Write take_lines(buffer): return (messages, rest), where messages are the complete lines (each parsed with json.loads, skipping blank lines) and rest is the unfinished text after the last newline, to keep for the next read.
import json def take_lines(buffer): return [json.loads(line) for line in buffer.splitlines()], "" chunk = ('{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}\n{"jsonrpc": "2.0", ' '"id": 2, "met') print(take_lines(chunk))
To stderr, because stdout carries only protocol messages
Anything extra on stdout corrupts the message stream. stderr is free for logs.
On stdio, stdout carries only protocol messages, so logs go to stderr. Write log(stderr, level, message, **fields): write one JSON line to the stderr stream holding level, message and the extra fields, with sorted keys.
import io import json def log(stderr, level, message, **fields): print(level, message, fields) err = io.StringIO() log(err, "info", "tool called", tool="get_campaign", ms=12) print(repr(err.getvalue()))
The academy can't start subprocesses, so io.StringIO stands in for the pipes. The loop is the same as a real server's.
import io, json, sys def dispatch(line): msg = json.loads(line) if "id" not in msg: return None if msg["method"] == "tools/list": return {"jsonrpc": "2.0", "id": msg["id"], "result": {"resultType": "complete", "tools": []}} return {"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -32601, "message": "Method not found"}} stdin = io.StringIO( '{"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}\n' '\n' '{"jsonrpc": "2.0", "method": "notifications/cancelled",' ' "params": {"requestId": 1}}\n' '{"jsonrpc": "2.0", "id": 2, "method": "prompts/list", "params": {}}\n' ) stdout = io.StringIO() for line in stdin: # reading stops at end of input (EOF) if not line.strip(): continue reply = dispatch(line) if reply is not None: stdout.write(json.dumps(reply) + "\n") stdout.flush() print(stdout.getvalue())
Four lines in: a request, a blank line, a notification and another request. Two lines out, one per request. On your own machine you'd loop over sys.stdin and write to sys.stdout, and the host would see exactly these lines.
notifications/cancelled with the requestId. The server should stop that work and send nothing more for that id. A reply that was already on its way may still arrive, and clients ignore it.SIGTERM, then a forced SIGKILL.The same framing (one JSON message per line) works over any reliable two-way byte stream, such as a local socket. Only the subprocess parts, like startup and stderr, are specific to stdio.
It closes the server's stdin; the server should exit when it reads end of input
End of input is the portable signal. SIGTERM and then SIGKILL are only for servers that don't exit on their own.
Write a sentence or two, then compare it with a good answer in the lesson.
Purpose. See the two lines a real server needs: one that starts it on stdio, and one that tells a host to launch it.
With the SDK, stdio is the default transport: you call run() with no arguments, and it reads stdin, writes stdout and keeps its own logs on stderr. A host is told how to launch it, either with a command or in a config file.
The command the host runs as the server's child process
The double dash ends the host's own options. What follows is the program and its arguments, started as a subprocess with stdin and stdout as the pipes.
The Inspector (uv run mcp dev shop_server.py) launches the same server and lets you call its tools by hand. The client side of the pipe is the Python SDK's Client, which takes a stdio server's launch parameters instead of a URL (Build a client).
In an engineer's week. The first server a team writes is almost always stdio, and the first bug is always a stray print, often inside a library you called. Before anything else, point the server's own logging at stderr and run it once under the Inspector.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
On stdio, where may a server write debug logs?
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