Skip to content
Index Ai Academy
Phase 9 · Protocol foundations

Transports I: stdio

Newline-delimited JSON over a subprocess's standard streams.

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

What it covers7

First principles

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.

  1. Starting point

    Host writes a framed request to the server's standard input

  2. What changes

    Server dispatches it and writes diagnostics to standard error

  3. Result

    Host reads the framed reply from standard output

Compare all three steps
  1. Starting point

    Host writes a framed request to the server's standard input

  2. What changes

    Server dispatches it and writes diagnostics to standard error

  3. Result

    Host reads the framed reply from standard output

Complete and reverse the trace

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.

Compare with the worked step

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.

Check one starting point

Host writes a framed request to the server's standard input. Check that your implementation produces the result shown above.

Try it on a new case

The client gets a decode error before the first reply. The server just printed a startup banner to standard output. What should change?

Show worked reasoning

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.

Run, change, and build

Check this when debugging. Using print() for debugging inside a stdio server.

Trace the cause · MCP message and permission
  1. Mark which message crosses the client–server boundary and which check determines what the caller may do.
  2. Change the tool input or approved scope. Compare the returned message and stored state to distinguish a denial from an allowed change.
  3. Try the same reasoning on this case. The client gets a decode error before the first reply. The server just printed a startup banner to standard output. What should change?

Why it matters

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.

What you'll be able to do

  • Explain how a host runs a local MCP server as a subprocess and talks over its standard streams
  • Frame messages as newline-delimited JSON, and keep stdout clean
  • Handle cancellation and shutdown on stdio
  • Write the read-dispatch-write loop at the heart of every stdio server
Quick check
A local MCP server talks to its app through standard input and output. What happens if it prints a debug message to stdout?
  1. The app tries to read it as a protocol message and fails
  2. The message appears neatly in the app's log window
  3. Nothing: stdout is ignored by the app
  4. The server's output is just slightly slower
Show the answer

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.

The idea: three pipes and one line per message

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.

A server as a subprocess

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:

  • stdin: the host writes requests here, and the server reads them. It's the slot coming in.
  • stdout: the server writes responses and notifications here, and the host reads them. It's the slot going out.
  • stderr: the server may write log text here. Hosts usually save or show it, and never parse it as protocol. Think of it as a side notepad.

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.

Quick check
A server needs to log "started" for a human to read later. Which stream do hosts usually save or show without parsing?
  1. A third file the host creates
  2. stderr
  3. stdout
  4. stdin
Show the answer

stderr

stderr is the side notepad: hosts keep it for people. stdout is the protocol channel, and stdin carries requests in.

Framing: one message per line

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")
It runs right here in your browser, with nothing to install.
Quick check
From the lesson on JSON-RPC: a request has an id, and a notification doesn't. Here two messages are written to a stream, one per line, and read back. What does this print?
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])
  1. 2 [True, True]
  2. 2 [True, False]
  3. 4 [True, False]
  4. 1 [True]
Show the answer

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.

Quick check
What does this print?
stream = '{"id":1}\n{"id":2}\n'
print(len(stream.strip().split("\n")))
  1. 2
  2. 6
  3. 1
  4. 3
Show the answer

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.

Quick check
Why is json.dumps(msg, indent=2) a bug for a stdio MCP server?
  1. Indenting adds raw newlines, so one message spans several lines and the host can't parse it
  2. It isn't a bug: hosts accept any valid JSON, however it's laid out on the page
  3. Indented JSON is too slow to write, so the host times out waiting for each message
  4. MCP requires tabs for indentation, not spaces, so the host rejects the message
Show the answer

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.

The famous trap: print()

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:

  • Log to stderr: print(..., file=sys.stderr), or use logging, which writes to stderr by default.
  • Defend in depth: while running handlers, redirect anything they print (including what libraries print) to stderr. The exercise does exactly this.

In plain words: stdout is for protocol messages and nothing else. Everything meant for humans goes to stderr.

Quick check
A tool function has a stray print(). Why does it pass when you test the function directly, and break inside a host?
  1. The host doesn't allow the print function
  2. The host reads stdout as protocol and can't parse it
  3. The test ignores what the function returns
  4. print runs much more slowly inside a host
Show the answer

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.

Try it now

The three pipes with the exact bytes. Try the stray print on the reply line.

In your own words
How are messages framed on stdio, and why is indent=2 a bug?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: the read, dispatch, write loop

This part writes the loop at the heart of a stdio server and the two helpers that keep stdout clean.

The loop

A stdio server is a loop, like a clerk working through an in-tray:

  1. Read one line from stdin. End of input (EOF) means the host closed the pipe: exit cleanly.
  2. Skip blank lines.
  3. Dispatch the message (the dispatcher from JSON-RPC 2.0 in depth).
  4. If there's a reply, write it as one line to stdout, then flush, so it leaves the buffer now. A buffer holds output until there's enough to send, like a mail carrier waiting for a full bag. Flushing sends what's there.

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.

Drill

Split a stream into messages

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))
In the lesson, your code is checked as you write it.
Quick check
Where should a stdio MCP server write its logs?
  1. Into the tool results, so the model can read them
  2. Nowhere: a stdio server has no place to write logs
  3. To stderr, because stdout carries only protocol messages
  4. To stdout, so the host sees them along with the replies
Show the answer

To stderr, because stdout carries only protocol messages

Anything extra on stdout corrupts the message stream. stderr is free for logs.

Drill

Log where it can't break the protocol

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

A stdio session, simulated

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

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.

Cancellation and shutdown

  • Cancellation. stdio has one shared channel, so a client cancels a request by sending a notification: 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.
  • Shutdown. The client closes the server's stdin and waits. A good server exits promptly at end of input. If it doesn't, the client escalates, the way a bar does at closing time: a polite SIGTERM, then a forced SIGKILL.
  • Crashes. If the server dies, the host restarts it. Modern MCP is stateless, so nothing is lost except the requests that were in flight, and those can be retried.

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.

Quick check
How does a host ask a stdio server to shut down gracefully?
  1. It closes the server's stdin; the server should exit when it reads end of input
  2. It writes EXIT to the server's stdout, which the server watches for
  3. It deletes the server's config file, which makes the server stop
  4. It sends a shutdown request on stdin and waits for the server to reply
Show the answer

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.

In your own words
Where do a stdio server's logs go, and why?

Write a sentence or two, then compare it with a good answer in the lesson.

In the SDK and a real host: one line to run it, one line to add it

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.

Quick check
In claude mcp add ... -- uv run shop_server.py, what does everything after the double dash mean?
  1. A URL the server listens on for requests
  2. The server's name, shown in the host's list
  3. The command the host runs as the server's child process
  4. Options for the claude command itself, like --env
Show the answer

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.

Goes deeper in

In your own words
A new stdio server works under the Inspector's tool list but the host drops the connection on the first call. What do you suspect?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 3 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 8 review cards for spaced repetition

Try a quiz question

On stdio, where may a server write debug logs?

  1. stderr
  2. stdout
  3. Either one
  4. Nowhere; logging isn't allowed

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
Part of a free course 15 lessons

Build and Deploy MCP Integrations

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