Sub topic 5
Moving messages: stdio and Streamable HTTP
This chapter covers how MCP messages travel between a client and a server. It assumes you can read the JSON-RPC messages from the previous chapter, know the host, client, and server roles, and have basic familiarity with HTTP and with processes and standard streams on the command line.
What a transport does
MCP separates the message format from the way messages are carried. The format is always JSON-RPC 2.0 in UTF-8. The carrier is called a transport. A transport has one job: deliver each JSON-RPC message from one side to the other, in both directions, without changing it.
The specification (revision 2025-06-18) defines two standard transports:
- stdio, where the client launches the server as a subprocess and the two talk over standard input and output.
- Streamable HTTP, where the server runs as an independent process and the client talks to it through HTTP requests.
Because the message format stays the same, a server's tools, resources, and prompts behave identically on either transport. Only the connection code changes. The specification also lets you define custom transports, as long as they keep the JSON-RPC format and the session lifecycle.
The stdio transport
With stdio, the client starts the server program itself. It writes messages to the server's standard input (stdin) and reads messages from the server's standard output (stdout). The server's lifetime is tied to the client: when the client closes the pipes and ends the process, the session is over.
The rules are short:
- Each message is one line of JSON, ended by a newline.
- Messages must not contain embedded newlines. A JSON serializer's compact output satisfies this.
- The server must write only valid MCP messages to stdout.
- The server may write log text to standard error (stderr). The client may capture it or ignore it.
- The client must write only valid MCP messages to the server's stdin.
Rule 3 causes the most common stdio bug. A stray print("starting up") in your server writes text to stdout, and the client fails to parse it as JSON-RPC. Send diagnostics to stderr instead.
import sys
# Wrong in a stdio server: this text lands in the protocol stream.
# print("server starting")
# Right: diagnostics go to stderr.
print("server starting", file=sys.stderr)Shutdown
The specification describes a graceful shutdown for stdio. The client closes the server's stdin, then waits for the process to exit. If it does not exit in a reasonable time, the client sends SIGTERM, and then SIGKILL if needed. A server that holds resources should release them when stdin reaches end of file.
When stdio fits
stdio suits local tools such as file access, a local database, or a command-line wrapper. It needs no ports, no network configuration, and no separate authentication step, because the server inherits the trust of the user who launched it. The costs are that each client starts its own server process, the server cannot easily be shared between users, and it only runs on the machine where the client runs.
The Streamable HTTP transport
Streamable HTTP is for servers that run on their own, possibly on another machine, and serve many clients. It replaced the older HTTP+SSE transport from the 2024-11-05 revision. The server exposes a single URL, called the MCP endpoint (for example https://example.com/mcp). That one path must support both POST and GET.
Sending messages with POST
The client sends every JSON-RPC message to the server as the body of an HTTP POST to the endpoint. The client must include an Accept header listing both application/json and text/event-stream.
What the server does next depends on the kind of message:
| Message from client | Server response |
|---|---|
| Notification or response | `202 Accepted` with no body |
| Request | Either `Content-Type: application/json` with one JSON response, or `Content-Type: text/event-stream` with an SSE stream |
SSE means Server-Sent Events, a standard format where an HTTP response stays open and the server pushes events. When the server answers a request with a stream, it may send related requests and notifications before it sends the final response for that request. The stream then closes. This lets one call report progress or ask the client a question before it completes.
A simple request and reply looks like this:
POST /mcp HTTP/1.1
Host: example.com
Content-Type: application/json
Accept: application/json, text/event-stream
MCP-Protocol-Version: 2025-06-18
Mcp-Session-Id: 1868a90c-0000-4000-8000-000000000000
{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "add", "arguments": {"a": 2, "b": 3}}}The server may answer with a plain JSON body:
HTTP/1.1 200 OK
Content-Type: application/json
{"jsonrpc": "2.0", "id": 2, "result": {"content": [{"type": "text", "text": "5"}], "isError": false}}Or it may answer with a stream, where each event's data field holds one JSON-RPC message:
HTTP/1.1 200 OK
Content-Type: text/event-stream
data: {"jsonrpc": "2.0", "method": "notifications/progress", "params": {"progressToken": "t1", "progress": 50, "total": 100}}
data: {"jsonrpc": "2.0", "id": 2, "result": {"content": [{"type": "text", "text": "5"}], "isError": false}}
A server that never needs to stream can always choose plain JSON. A server that streams must still end the stream after it sends the response to the request.
Listening with GET
The client can also open a GET request to the endpoint with Accept: text/event-stream. This gives the server a channel to send messages that are not tied to a client request, such as list-changed notifications. The server either returns an SSE stream or answers 405 Method Not Allowed if it does not offer one. Messages on this stream must not be responses to client requests, unless the stream is being resumed.
Sessions
A server may start a session during initialization by returning an Mcp-Session-Id header on the response to the initialize request. If it does, the client must send that header on every later request. The ID should be globally unique and hard to guess, such as a UUID, and should use only visible ASCII characters.
Session handling has defined failure responses:
- A request without a required session ID gets
400 Bad Request. - A request with an ID the server has ended gets
404 Not Found. The client must then start a new session by sending a freshinitializerequest. - A client that no longer needs a session should send an HTTP
DELETEto the endpoint with the header. The server may answer405if it does not allow clients to end sessions.
Protocol version header
After initialization, the client must send MCP-Protocol-Version: <version> on every HTTP request. The value is the version negotiated during initialization. If the header is missing, the server assumes 2025-03-26 for backward compatibility. An invalid or unsupported value gets 400 Bad Request.
Resumability
Connections drop. To recover, a server may attach an id to each SSE event. These IDs must be unique within the session. After a disconnect, the client sends a GET with a Last-Event-ID header holding the last ID it received, and the server may replay the messages that stream missed. The replay applies only to the stream that was broken. The server must not mix messages from different streams.
Disconnection alone does not cancel a request. To cancel, the client sends an explicit cancellation notification, covered in the utilities chapter.
Security rules for HTTP servers
An HTTP server on a developer machine can be attacked through the browser. The specification asks servers to:
- Validate the
Originheader on all incoming connections and reject unexpected values with403 Forbidden. This blocks DNS rebinding, where a malicious web page tricks the browser into sending requests to a local server. - Bind to
127.0.0.1rather than0.0.0.0when running locally. - Authenticate connections. The specification's authorization framework builds on OAuth 2.1, and a later chapter covers it with the other trust topics.
Comparing the two transports
| Question | stdio | Streamable HTTP |
|---|---|---|
| Who starts the server? | The client | An operator or hosting platform |
| Number of clients | One per process | Many at once |
| Message framing | Newline-delimited JSON | HTTP bodies and SSE events |
| Where can it run? | Same machine as the client | Anywhere reachable by URL |
| Authentication | Inherited from the launching user | HTTP-level, such as OAuth tokens or API keys |
| Logging channel | stderr | Normal server logs |
| Typical failure | Stray stdout text breaks parsing | Wrong headers, lost sessions, blocked origins |
A practical rule: use stdio for tools tied to a single user's machine, and use Streamable HTTP when the server needs to be shared, hosted, or reached across a network.
Choosing a transport in the Python SDK
In the official Python SDK, the server code from the previous chapters changes only in its run call. The FastMCP constructor and decorators stay as they were.
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("demo")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
if __name__ == "__main__":
# Local subprocess use:
# mcp.run(transport="stdio")
# Standalone HTTP server, served at /mcp by default:
mcp.run(transport="streamable-http")On the client side, the connection helper changes while the session code does not:
import asyncio
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
async def main():
async with streamablehttp_client("http://127.0.0.1:8000/mcp") as (read, write, _):
async with ClientSession(read, write) as session:
await session.initialize()
result = await session.call_tool("add", {"a": 2, "b": 3})
print(result.content)
asyncio.run(main())Everything after ClientSession(read, write) matches the stdio client. The SDK hides the framing, the headers, and the session ID. Names of helpers and defaults such as the port can change between SDK versions, so check the installed version's documentation.
Common errors
- Parse errors on stdio. Something other than JSON-RPC reached stdout. Search the server for
printcalls and for libraries that write banners to stdout. - Messages split across lines. Pretty-printed JSON breaks the one-message-per-line rule. Use compact serialization.
406 Not Acceptableor empty responses over HTTP. The client omitted one of the two requiredAccepttypes.400after initialization. The client droppedMcp-Session-IdorMCP-Protocol-Versionon a later request.404on a previously working session. The server restarted or expired the session. Start a new one withinitialize.- Server unreachable from a browser-based client. The
Origincheck rejected the page, or the server is bound to a different interface than the client expects.
Exercise
A teammate's stdio server works when run by hand, but the host reports a JSON parse error as soon as it connects. The server prints "Ready!" on startup. What is wrong, and how do you fix it?
Show answer
The server writes "Ready!" to stdout, which is the protocol stream. The client tries to parse it as JSON-RPC and fails. Send the message to stderr instead, for example print("Ready!", file=sys.stderr), or use a logging setup that writes to stderr.
Exercise
A Streamable HTTP client receives 404 on a tools/call request that worked a minute ago, and the server logs show a restart. What should the client do?
Show answer
The 404 means the server no longer recognizes the Mcp-Session-Id. The client must start a new session by sending a new initialize request without the old session ID, then repeat its work, including the failed call, using the new ID.
Exercise
Name two reasons you would choose Streamable HTTP over stdio.
Show answer
Any two of: the server must serve many clients at once, it must run on a different machine from the client, it is hosted by a platform rather than launched by the client, or it needs HTTP-level authentication such as OAuth tokens.