MCP Server stdout: One console.log Kills the Connection
说明与用途
在使用 stdio 的 MCP 服务器中,向 stdout 打印会破坏 JSON‑RPC 协议。将所有 console.log 和 print 重定向到 stderr,以保持流的完整性。
问题
A console.log statement written to stdout in an MCP server over stdio corrupts the JSON-RPC protocol stream, causing the client to crash.
结果
Redirecting all console output to stderr (or configuring logging to stderr) prevents protocol corruption, restoring stable client-server communication.
工作流
- 1. Launch MCP server via stdio transport. 2. Server writes JSON-RPC messages to stdout. 3. Developer adds console.log("fetching", url) inside a tool handler. 4. The log line is written to stdout, interleaving with JSON messages. 5. Client reads the second line, attempts JSON parse, fails. 6. Client tears down the connection and reports server failure.
- 7. Fix: redirect console.log and other console methods to stderr at entry point (Node) or configure logging to stderr (Python).
- 8. Ensure no other stdout writes (dependencies, child processes, shell scripts, spinners).
- 9. Test by piping server stdout through jq to validate each line is valid JSON.
- 10. Restart server and verify stable operation.
证据
Any console.log, print(), banner, spinner, or echo that lands on stdout injects a non‑JSON line and the client's parser blows up.
Fix in Node: alias console.log to console.error at the top of your entry file.
- 记录日期: 2026-09-17T05:45:28.405Z