Sub topic 5
Choosing a transport: stdio or Streamable HTTP
This chapter assumes you have read the earlier chapters on hosts, clients, servers, and JSON-RPC messages. A transport is the channel that carries those JSON-RPC messages between client and server. MCP defines two standard transports: stdio and Streamable HTTP. The messages are identical on both. What changes is who starts the server, who can reach it, and how you authenticate.
What a transport does
The protocol layer defines requests such as tools/list and tools/call. The transport only moves the bytes. Because of this split, your agent loop does not change when you change transports. Only the code that opens the connection changes. After that, you pass the read and write streams to ClientSession as before.
stdio: a local subprocess
With stdio, the client launches the server as a child process. The client writes JSON-RPC messages to the server's standard input, and the server writes its messages to standard output. Each message is one line of JSON, with no embedded newlines.
This has practical consequences:
- The client controls the server's lifetime. When the client closes the connection, the server process ends.
- There is no network port, so nothing else on the network can reach the server.
- The server runs with your application's operating system permissions, and inherits whatever environment you pass it.
- Each client gets its own server process. Two applications cannot share one stdio server.
The main pitfall is that stdout belongs to the protocol. A stray print() in a stdio server corrupts the message stream. Write logs to stderr or to a file instead.
Streamable HTTP: a network service
With Streamable HTTP, the server is an independent process that exposes one HTTP endpoint, for example https://tools.example.com/mcp. It replaces the older HTTP+SSE transport. The endpoint supports two methods:
- POST carries each client-to-server message. The server replies either with a single JSON body or with a
text/event-streamresponse (Server-Sent Events). It uses a stream when it needs to send several messages before the final response, such as progress notifications. - GET optionally opens a stream that the server uses to send requests and notifications that are not tied to a client request.
The server may assign a session by returning an Mcp-Session-Id header on the initialize response. The client then sends that header on every later request. Clients also send an MCP-Protocol-Version header with the negotiated version. A client can end a session by sending DELETE to the endpoint. Servers that stream events with IDs can let a client resume after a dropped connection by sending the Last-Event-ID header.
Because the server outlives any one client, many clients can share it, and it can run on another machine. This also means you must handle authentication, origin checks, and network exposure, which stdio avoids.
Comparing the two
| Concern | stdio | Streamable HTTP |
|---|---|---|
| Who starts the server | The client, as a subprocess | You, or a deployment platform |
| Number of clients | One per process | Many |
| Reach | Same machine only | Local or remote |
| Authentication | None on the channel; credentials usually come from environment variables | HTTP-level, with OAuth-based authorization in the spec |
| Failure signals | Process exit, broken pipe | HTTP status codes, dropped streams, session expiry |
| Scaling | One process per client | Standard HTTP techniques, but sessions may need sticky routing |
| Debugging | Logs on stderr | Ordinary HTTP tooling such as `curl` and proxies |
Deciding between them
Use stdio when you are building a desktop tool, a developer utility, or a prototype, and the server is a local program such as a filesystem or Git server. Use Streamable HTTP when the server belongs to another team or vendor, needs to be shared, holds long-lived state, or must run close to the data it serves. A common pattern is to develop a server over stdio and deploy the same code over HTTP.
Running the same server on both transports
The FastMCP helper from the SDK selects the transport at run() time. This version of server.py accepts the transport name as a command-line argument.
import sys
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("calc")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two integers."""
return a + b
if __name__ == "__main__":
transport = sys.argv[1] if len(sys.argv) > 1 else "stdio"
mcp.run(transport=transport)Start it for HTTP with python server.py streamable-http. In the SDK versions that provide FastMCP, this serves the endpoint at http://127.0.0.1:8000/mcp by default. Defaults can differ between SDK releases, so check the startup output.
The client changes only in how it opens the connection:
import asyncio
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
async def main():
url = "http://127.0.0.1:8000/mcp"
async with streamablehttp_client(url) as (read, write, get_session_id):
async with ClientSession(read, write) as session:
await session.initialize()
print("session id:", get_session_id())
result = await session.call_tool("add", {"a": 2, "b": 3})
print(result.isError, [c.text for c in result.content if c.type == "text"])
asyncio.run(main())Note the third value, get_session_id, which the stdio client does not provide. After initialize(), everything works as in the stdio client: list_tools(), call_tool(), and your agent loop. The helper's name has changed in some newer SDK releases, so check the import path against your installed version.
Edge cases and failure modes
- Process lifetime with stdio. If the server crashes, your client sees a closed stream and later calls fail. Decide whether to restart the subprocess or end the conversation. Do not let the agent loop wait indefinitely.
- Startup cost. A stdio server starts for each connection. If it imports heavy libraries, startup adds latency, so create the session once per application run and not once per user message.
- Session expiry over HTTP. A server may discard a session. It then answers with HTTP 404 for requests that carry the old session ID. The client must start a new session by initializing again.
- Load balancers. If the server keeps session state in memory, requests must reach the same instance. Use sticky routing or keep the server stateless.
- DNS rebinding. A local HTTP server that accepts any
Originheader can be attacked by a web page in the user's browser. ValidateOrigin, and bind to127.0.0.1and not0.0.0.0when serving locally. - Credentials. For stdio, pass secrets through the subprocess environment. For HTTP, send authorization in the
Authorizationheader. Never put tokens in the URL.
Legacy HTTP+SSE
Older servers may still expose the HTTP+SSE transport, which used two separate endpoints. It is deprecated in favor of Streamable HTTP. If you must connect to such a server, the SDK still provides a client for it. For new servers, choose Streamable HTTP.
Exercise
Your team has a Git-inspection MCP server that only your desktop application uses, and it reads the user's local repositories. A second team wants to call a shared company "ticket search" server from many applications. Which transport fits each case, and what is one extra concern for the shared server?
Show answer
Use stdio for the Git server. The app launches it as a subprocess, no network port is exposed, and it runs with the user's local file permissions. Use Streamable HTTP for the shared ticket server, because many clients must reach one long-running process. The extra concern is authentication and exposure: the endpoint needs authorization, origin validation, and possibly sticky routing if it keeps session state.
Exercise
A stdio server works when you run it by hand but your client fails with a JSON parse error right after initialize(). The server code contains print("starting up"). What is wrong, and how do you fix it?
Show answer
The print writes to stdout, which carries the JSON-RPC stream, so the client reads a line that is not valid JSON. Send the message to stderr instead, for example with print("starting up", file=sys.stderr) or the logging module configured for stderr.