MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
Reach one small order server two ways, as a stdio subprocess and as a Streamable HTTP endpoint, see why a stray print to stdout breaks the session, and pick a transport by who runs the server.
What you will learn
- Explain the four layers of one MCP call: host app, client, transport and server
- Describe how stdio and Streamable HTTP carry the same JSON-RPC messages
- Keep the server's logic free of any transport so both doors share it
- Choose a transport by who runs the server and who may reach it
Before you start
- Building an MCP server: tools, resources and prompts
- Basic Python
Someone asks your app: where is order 1042? The answer lives in an order server. But how does your app reach it?
MCP has two standard ways: stdio and Streamable HTTP. Both reach the same server and carry the same messages. What changes is who starts the server and how the messages travel. In this article we reach one small server both ways, then break it with a single line.
One call, four layers
On the left is the host app: Claude Code, or your own program. Next comes the MCP client, then the transport, and last the MCP server. A tools/call with the order id goes right. The reply, order 1042: shipped, comes back the same way.
A helper at your desk, or a shop with a front door
stdio is a helper at your desk. You start the helper yourself and it lives as long as you do. You pass notes through one slot, and nobody else can reach them. Technically: a subprocess with pipes.
Streamable HTTP is a shop with a front door. It is open on its own, customers walk in through one address, and a doorman checks who comes in.
| Client side | Server side | |
|---|---|---|
| stdio | Launches the server process and writes one message per line | Reads stdin, writes stdout, one line each |
| Streamable HTTP | Sends one POST per message to one endpoint | Already running; answers each POST and can serve many clients |
In both cases the client asks first; the server never starts a request. With stdio the client owns the server's life. With HTTP the server lives on its own.
The project
The lecture's project is a deliberately small, hand-written sketch in plain Python (standard library only, localhost only). Real servers use an official MCP SDK, which also handles protocol version, metadata and capabilities. The point here is to see the transports with nothing hidden.
server_core.py: the brain, with no transport
"""The server's brain: a JSON-RPC message in, a JSON-RPC reply out."""
ORDERS = {"1042": "shipped", "1043": "packed"}
TOOLS = [{
"name": "order_status",
"description": "Looks up one shop order by its digits-only id and "
"returns its status, like shipped or packed.",
"inputSchema": {
"type": "object",
"properties": {
"order_id": {"type": "string", "pattern": "^[0-9]+$"},
},
"required": ["order_id"],
},
}]
def reply(mid, result=None, error=None):
body = {"jsonrpc": "2.0", "id": mid}
body["error" if error else "result"] = error or result
return body
def handle(msg):
"""Same code answers on every transport."""
method, mid = msg["method"], msg["id"]
if method == "tools/list":
return reply(mid, {"tools": TOOLS})
if method == "tools/call":
oid = msg["params"]["arguments"]["order_id"]
status = ORDERS.get(oid)
text = f"order {oid}: {status}" if status else f"no order {oid}"
content = [{"type": "text", "text": text}]
return reply(mid, {"content": content, "isError": status is None})
return reply(mid, error={"code": -32601, "message": "Method not found"})
Three things to notice. There is no transport anywhere in this file. A missing order comes back as a tool error (isError: true), not a crash. And an unknown method gets a JSON-RPC error reply, -32601.
stdio_server.py: the first door
"""stdio transport: the client starts this process and talks through pipes."""
import json
import sys
from server_core import handle
def serve():
print("server up", file=sys.stderr, flush=True)
for line in sys.stdin:
answer = handle(json.loads(line))
sys.stdout.write(json.dumps(answer) + "\n")
sys.stdout.flush()
print("stdin closed", file=sys.stderr, flush=True)
if __name__ == "__main__":
serve()
Logs go to stderr, never stdout. Each message is one line on stdin; each reply is one line on stdout. When the client closes stdin, the loop ends and the server exits. That is the normal shutdown.
http_server.py: the second door
"""Streamable HTTP transport: one endpoint, one POST per message."""
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from server_core import handle, reply
ALLOWED_ORIGINS = {"http://localhost:3000"}
class McpEndpoint(BaseHTTPRequestHandler):
def do_POST(self):
origin = self.headers.get("Origin")
if origin and origin not in ALLOWED_ORIGINS:
return self.send_json(403, "bad origin")
size = int(self.headers["Content-Length"])
msg = json.loads(self.rfile.read(size))
if self.headers.get("Mcp-Method") != msg["method"]:
err = {"code": -32020, "message": "Mismatch"}
body = reply(msg["id"], error=err)
return self.send_json(400, body)
self.send_json(200, handle(msg))
def send_json(self, code, body):
data = json.dumps(body).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, *args):
pass
def make_server():
return ThreadingHTTPServer(("127.0.0.1", 0), McpEndpoint)
- The Origin check. An origin that is not allowed gets a 403. The MCP spec says HTTP servers must validate the Origin header.
- One POST, one message, to a single endpoint.
- The header check. In this sketch, an
Mcp-Methodheader that does not match the body is a bad request. - The same
handle()answers as on stdio. - Bound to 127.0.0.1. Running locally, only this machine can connect. Port 0 lets the OS pick a free port.
Run the client
client.py starts the stdio server and sends four messages, then POSTs to the HTTP server, then tries a server with one mistake. The server here is real and runs on this machine; there is no model in the loop. The printout:
stdio: the client starts stdio_server.py
-> tools/list
<- order_status
-> tools/call 1042
<- order 1042: shipped
-> tools/call 9999
<- no order 9999 (isError true)
-> tools/remove
<- error -32601 Method not found
server log (stderr): server up
server log (stderr): stdin closed
stdin closed, exit code 0
http: one POST per message, to one endpoint
POST /mcp tools/list -> 200 order_status
POST /mcp tools/call -> 200 order 1042: shipped
POST /mcp from Origin http://evil.test -> 403
POST /mcp with the wrong Mcp-Method -> 400 error -32020 Mismatch
stdio: a server that prints a banner to stdout
stdout line is not JSON-RPC: Welcome to the order server!
Order 9999 is missing, so it is a tool error. The log lines arrive on stderr, and closing stdin ends the server with exit code 0. Over HTTP, the unknown origin gets 403 and the wrong header gets 400. The last block is the bug in the next section.
Break it: one stray print
noisy_server.py is the stdio server with one extra line:
"""A stdio server with one mistake: it prints a banner to stdout."""
import stdio_server
print("Welcome to the order server!")
stdio_server.serve()
On stdio, stdout is the message channel. The client reads every line as JSON-RPC, and this line is not a message, so the session breaks before any real call. The fix is to print to stderr instead. A normal print is harmless in most programs; on stdio it corrupts the protocol.
Choosing a transport
| stdio | Streamable HTTP | |
|---|---|---|
| Fits | A local tool with one user: files, scripts, your own machine | A shared or remote service: many clients, one server |
| Who starts it | The client | It runs on its own |
| Network | None, no port | One endpoint |
| Needs | Logs on stderr | Origin check and authentication |
| In Claude Code | claude mcp add --transport stdio <name> -- <command> | claude mcp add --transport http <name> <url> |
Two more words you may meet. The older SSE transport is deprecated. And stdio's line framing can run over a TCP socket, but the spec calls that a custom transport.
Authentication for the HTTP door (bearer tokens, audience and scope) is covered in Deploying and authenticating an MCP server.
Common mistakes
- Printing to stdout in a stdio server. Banners, debug prints and progress bars all break the session. Log to stderr.
- Putting transport code in the tool logic. Keep one
handle()and wrap it in each door. - A shared server on stdio. If several apps on other machines must use one server, each would launch its own copy. Use Streamable HTTP.
- An open HTTP endpoint. No Origin check and no authentication means anyone who can reach the URL can call your tools.
Recap
- The server's logic does not change with the transport.
- stdio: the client launches the server and talks in lines; logs go to stderr.
- Streamable HTTP: one endpoint, one POST per message, Origin checks and authentication.
- Pick by who runs the server and who may reach it.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)Related posts
Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
A support agent forgets the customer's name, order and contact choice after twenty turns and fails 0 of 4 checks. Measure the window, clear old tool output, compact old turns and keep a notes file, and the same chat passes 4 of 4 with 470 tokens instead of 2,945.
What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
LangChain is a box of standard parts (models, prompts, retrievers, tools, parsers) that snap together with a pipe. The same refund question through the plain Anthropic SDK (1 import, 13 lines) and a chain (3 imports, 14 lines) gives the same answer word for word. It pays off when the bot grows; for one call, the SDK is simpler, with 16 packages instead of 38.
Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
A refund assistant built three ways. The chain runs classify, retrieve, reply once: it answers an opening-hours question with the billing line, misses the 30-day window, and sends a $150 refund with approved False. Plain if/while fixes it but hides the flow; a LangGraph StateGraph puts the branch, the retry loop and the approval stop in the arrows.
LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
Two small graphs. A refund skeleton: SupportState, a classify node, a route function on a conditional edge, and an Annotated log that appends instead of overwriting. A help desk: classify and answer call a scripted test model, spam goes straight to END after one model call instead of two, and the same run read with invoke, stream values and stream updates.