MCP Server stdout: One console.log Kills the Connection
Описание и применение
Вывод в stdout в сервере MCP, использующем stdio, нарушает протокол 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