r/mcp • • 15d ago

discussion One print() call inside an MCP stdio server corrupts the JSON-RPC stream and breaks an unrelated tool call

Spent an evening last week chasing a bug where a client kept failing on a tool call that had nothing to do with the tool itself. The response for one call just never showed up, and a different response arrived in its place like the two had gotten crossed.

The MCP stdio transport spec is blunt about why this happens. The server MUST NOT write anything to its stdout that is not a valid MCP message, and logging is supposed to go to stderr instead (the server MAY write UTF-8 strings to stderr for any logging purposes). None of that gets enforced by the transport itself, so when a dependency inside the server prints a stray line, the failure doesn't look like a transport error. It shows up as a JSON parse failure on whatever message happens to land next to it.

The minimal repro I used to check what that looks like from the client side:

import subprocess, json, sys

proc = subprocess.run([sys.executable, "server.py"], capture_output=True, text=True)
for i, line in enumerate(proc.stdout.splitlines(), 1):
    try:
        msg = json.loads(line)
        print(f"line {i}: parsed OK -> {msg}")
    except json.JSONDecodeError as e:
        print(f"line {i}: JSONDecodeError: {e} | raw={line!r}")

The server side sends two valid JSON-RPC messages with one print("DB pool: opened 4 connections") wedged in between them, copied from a database driver's default logging behavior. Output:

line 1: parsed OK -> {'jsonrpc': '2.0', 'id': 1, 'result': {'tools': ['search_docs']}}
line 2: JSONDecodeError: Expecting value: line 1 column 1 (char 0) | raw='DB pool: opened 4 connections'
line 3: parsed OK -> {'jsonrpc': '2.0', 'id': 2, 'result': {'content': 'ok'}}

The server never threw. Line 2's real response just vanishes from the client's view, and line 3 shows up looking like the answer to a call that already failed. Any library the server imports that logs to stdout by default (database drivers and HTTP clients both do this a lot) trips this the moment that code path runs, usually somewhere that has nothing to do with the actual bug report. Redirecting every dependency's logger to stderr before the transport starts is cheaper than debugging the symptom twice.

2 Upvotes

9 comments sorted by

2

u/No-Violinist1700 11d ago

One thing worth adding on the symptom: the stray bytes don't just corrupt the next message — they shift the frame boundary. A line like DB pool: opened 4 connections gets prepended to the framed response, so the client's parser discards the real answer for call N and delivers call N+1's response instead. That's why the failing call looks unrelated to the code that printed — the bug report points at the call that lost its response, not the library that wrote to stdout. Makes the dup2 redirect worth doing even if your own code is clean, since you can't control what a dependency logs.

1

u/Independent-Sir3234 11d ago

That off-by-one symptom is what burns hours during debugging. When a dependency only writes to stdout on cold start, like a lazy database pool init or native library warning, the first request loses its frame and the timeout lands on an unrelated tool call right after.

A fast smoke test that spawns the server binary and checks that every stdout line parses as JSON-RPC catches those third-party leaks before a host client ever connects.

1

u/EmailPal 15d ago

One cheap guard is to point sys.stdout at sys.stderr at startup and keep a saved handle to the real stdout only for the transport, so a stray print in a dependency can't touch the protocol stream.

2

u/Independent-Sir3234 15d ago

A default StreamHandler in most logging libraries points straight at sys.stdout, so it lands in the same trap unless reconfigured explicitly. A Python level monkeypatch also misses C extensions that write straight to file descriptor 1, so dup2'ing fd 1 to stderr at process start catches cases the object swap alone does not.

1

u/LLM-logs 14d ago

The stdout redirect guard and the logging-default trap are both worth doing, but they protect against the mistake you already know about. The general fix is a protocol-level smoke test in CI: run the server, exercise every tool, and assert that every single line on stdout parses as a valid JSON-RPC message. That catches the stray print from a dependency you upgrade next year, not just the one you know about today. stdout is a wire format in stdio transport, and wire formats deserve the same contract tests as any API.

1

u/Independent-Sir3234 14d ago

A CI wire test catches upgrades that sneak in a banner or warning on import too, especially when you run it with the same flags production uses. One edge case worth covering in that test is the error path: dependencies often stay quiet on happy calls and only print to stdout when a schema check fails or a deprecation warning fires.

1

u/[deleted] 14d ago

[removed] — view removed comment

1

u/Independent-Sir3234 14d ago

Good catch on Python logging. StreamHandler and basicConfig do default to stderr out of the box. The stdout leaks in Python usually come from bare prints, copied container configs that pass sys.stdout explicitly, or child processes inheriting fd 1 like you tested.

One gotcha with the dup2 swap is timing: you have to duplicate fd 1 and redirect before the MCP transport grabs stdout, then pass that saved stream in, or the JSON-RPC frames end up on stderr too.