Sub topic 4
Choosing a transport: stdio or Streamable HTTP
This chapter assumes you can run the team-tools server from the earlier chapters and that you know the basics of HTTP (methods, headers, status codes). It also assumes you know that MCP messages are JSON-RPC 2.0. A transport is the channel that carries those messages between client and server. It does not change what your tools do. It changes who can reach them, how they start, and how you secure them.
MCP defines two standard transports: stdio and Streamable HTTP. Most teams start with stdio and move to Streamable HTTP when several people need one shared server.
What a transport does
The protocol layer (initialization, tools/list, tools/call) is the same on both transports. The transport only answers three questions:
- How do bytes get from client to server and back?
- Who starts and stops the server process?
- How does the server know who is calling?
Because your tool functions don't know which transport is in use, you can usually switch with a one-line change.
stdio: the server as a subprocess
With stdio, the host launches your server as a child process. The client writes JSON-RPC messages to the server's standard input. The server writes responses to its standard output. Each message is one line of JSON, so messages must not contain raw newlines.
This gives you several properties:
- One server per user. Each host instance starts its own process, so there is no shared state between users.
- No network exposure. Nothing listens on a port. Only the process that launched the server can talk to it.
- Identity comes from the OS. The server runs with the launching user's permissions and environment variables. Credentials usually arrive through environment variables set in the host configuration.
- Lifecycle is automatic. The host starts the process and ends it when the session closes.
The main failure mode is stdout pollution. A stray print() in your code, or a library that writes to stdout, injects non-protocol text into the stream and the client fails to parse it. Send all logging to stderr, as shown in the logging example earlier in this tutorial. The host may capture stderr and show it in a log view.
The other drawback is distribution. Every user needs the code, the right Python version, and the dependencies on their own machine. Updating the server means updating every machine.
Streamable HTTP: the server as a service
With Streamable HTTP, your server runs as an independent process that listens on a URL, such as https://mcp.example.com/mcp. The server exposes a single endpoint, the MCP endpoint, that accepts both POST and GET.
The flow works like this:
- The client sends each JSON-RPC message as an HTTP POST to the endpoint. The
Acceptheader lists bothapplication/jsonandtext/event-stream. - For a request, the server replies either with a single JSON body or with a
text/event-streamresponse. The stream form lets the server send progress notifications or server-initiated requests before the final result. - The client may open a GET request to the same endpoint to listen for messages the server wants to send unprompted.
- The server may assign a session by returning an
Mcp-Session-Idheader on the initialize response. The client then sends that header on every later request. After negotiation, the client also sends anMCP-Protocol-Versionheader.
The older HTTP+SSE transport used two separate endpoints. Streamable HTTP replaced it, so use Streamable HTTP for new servers. You may still see SSE in older examples and in some clients.
Running the same server on both
Here is a complete server that picks its transport from a command-line argument. The tool is the one you wrote earlier.
import argparse
import logging
import sys
from mcp.server.fastmcp import FastMCP
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
logger = logging.getLogger("team-tools")
mcp = FastMCP("team-tools", host="127.0.0.1", port=8000)
OWNERS = {"billing": "payments-team", "search": "discovery-team"}
@mcp.tool()
def get_service_owner(service: str) -> str:
"""Return the team that owns a service, given its short name."""
if service not in OWNERS:
raise ValueError(f"Unknown service: {service}")
return OWNERS[service]
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--transport", choices=["stdio", "streamable-http"], default="stdio"
)
args = parser.parse_args()
logger.info("Starting with transport %s", args.transport)
mcp.run(transport=args.transport)Start the HTTP form with python server.py --transport streamable-http. The SDK serves the endpoint at /mcp by default, so the URL is http://127.0.0.1:8000/mcp. The host and port constructor arguments are how current releases of the Python SDK configure the HTTP server. Check the SDK version you installed, because this API has changed between releases.
You can see the protocol on the wire with curl. This sends the initialize request:
curl -i http://127.0.0.1:8000/mcp \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-06-18",
"capabilities": {},
"clientInfo": {"name": "curl", "version": "0"}
}
}'The response headers include Mcp-Session-Id when the server uses sessions. You would send that value on every following request, along with an initialized notification, before calling tools. Normally a client library does all of this. The point of the exercise is to confirm that nothing in Streamable HTTP is more than HTTP carrying the same JSON-RPC.
If you leave out the Accept header, the server rejects the request, usually with a 406 status. This is a common first error.
Configuring each form in a host
A stdio server is described by the command that launches it:
{
"mcpServers": {
"team-tools": {
"command": "python",
"args": ["/absolute/path/to/server.py"],
"env": {"TEAM_API_TOKEN": "replace-me"}
}
}
}A remote server is described by its URL. The exact key names differ between hosts. Some use url with a type of http, and some require a bridge for remote servers. Check your host's documentation:
{
"mcpServers": {
"team-tools": {
"url": "https://mcp.example.com/mcp",
"headers": {"Authorization": "Bearer replace-me"}
}
}
}Treat both snippets as templates. Don't commit real tokens to a shared repository.
Comparing the two
| Concern | stdio | Streamable HTTP |
|---|---|---|
| Who starts the server | The host, per user | You, as a long-running service |
| Network exposure | None | A listening port |
| Authentication | Inherited from the OS user and env vars | You must add it (bearer tokens or OAuth) |
| Shared state across users | No | Yes |
| Updating the server | Every user's machine | One deployment |
| Debugging | Read stderr, use the Inspector | Use HTTP tools, logs, and the Inspector |
| Typical use | Personal or local tooling | Shared team tooling |
Security consequences of the choice
Choosing HTTP makes the server a network service, so the protections an ordinary web service needs now apply:
- Bind to localhost for local testing. Use
127.0.0.1, not0.0.0.0, unless you intend to expose it. The MCP specification asks servers to validate theOriginheader, because a malicious web page in a user's browser could otherwise send requests to a server on localhost (a DNS rebinding attack). - Authenticate every request. Never rely on "it's only on the internal network". The specification's authorization model for HTTP is based on OAuth 2.1. A simpler approach for a first internal deployment is a bearer token checked in front of the server, for example at a reverse proxy.
- Use TLS for anything that crosses a network.
- Decide on per-user identity. A shared server often calls internal APIs. If it uses one service account, every caller gets that account's permissions. Pass the caller's identity through, or limit the service account to what all callers may do.
stdio has fewer such concerns, but the process still runs with your user's full permissions. A tool that deletes files can do so. Least privilege applies in both cases.
Session state and scaling
The server can keep a session per client when it assigns an Mcp-Session-Id. This is convenient but affects how you deploy. If you run several instances behind a load balancer, a request carrying a session ID must reach the instance that holds that session, or the session state must live in shared storage. For servers whose tools are plain request-and-response functions, as ours are, you can run in a stateless mode and avoid this problem. Check your SDK for a stateless option, since the setting name depends on the version.
Common errors
- Garbled or hanging stdio session. Something wrote to stdout. Search for
printcalls and libraries that log to stdout, and move them to stderr. - 406 Not Acceptable over HTTP. The client did not send
Accept: application/json, text/event-stream. - 404 or "session not found". The client is sending a stale
Mcp-Session-Idafter a server restart, or the load balancer sent the request to a different instance. Re-initialize the session. - Connection refused. The server is bound to
127.0.0.1inside a container, and the client is outside it. Bind to the container's external interface and add authentication before you do. - Host ignores the remote entry. Not every host supports remote servers directly. Check the host's documentation for the supported configuration keys.
Exercise
Your team has a server that queries an internal deployment database using one shared read-only credential. Twenty engineers want to use it from their editors, and you want to update the tools without visiting each laptop. Which transport do you choose, and name two things you must add that stdio did not require.
Show answer
Choose Streamable HTTP, because it lets you run one shared service and update it in a single place. You must add authentication (for example bearer tokens or OAuth) so only your team can call the tools, and network protections such as TLS and Origin validation. Per-user identity handling is also acceptable as one of the two, since a shared credential gives every caller the same access.
Exercise
A stdio server works in the Inspector but the host reports "invalid JSON" as soon as it connects. Name the most likely cause and the fix.
Show answer
Something in the server writes non-protocol text to stdout, such as a print statement or a library that logs there. Redirect all logging and debug output to stderr.