Skip to content

fix: redirect console logging to stderr for MCP stdio transport#6

Open
Jasper-1222 wants to merge 1 commit into
agent-network-protocol:mainfrom
Jasper-1222:fix/stdio-log-to-stderr
Open

fix: redirect console logging to stderr for MCP stdio transport#6
Jasper-1222 wants to merge 1 commit into
agent-network-protocol:mainfrom
Jasper-1222:fix/stdio-log-to-stderr

Conversation

@Jasper-1222
Copy link
Copy Markdown

Summary

修复 stdio 模式下日志输出污染 MCP 协议通道的问题。

现象

启动 mcp2anp stdio 模式后,list_tools 可以正常工作,但 call_tool 偶尔失败。错误原因是 structlog 的 ConsoleRenderer 将彩色格式的日志行输出到了 stdout,与 MCP JSON-RPC 协议帧混合,导致客户端解析 JSON-RPC 消息失败。

根因

setup_logging 函数在 mcp2anp/utils/logging.py 第 33 行配置了 StreamHandler(sys.stdout)。MCP stdio 传输协议要求 stdout 只传输 JSON-RPC 协议帧,所有诊断输出必须走 stderr。这是 Python 社区的标准约定。

修复

StreamHandler(sys.stdout) 改为 StreamHandler(sys.stderr)

  • 文件日志继续写入 logs/mcp2anp.log(不受影响)
  • console 日志重定向到 stderr(符合 Python 约定)
  • 行数变化:2 行

Verification

本地测试通过,8/8 MCP bridge tests pass。

Risk

低风险。仅影响日志输出流,不涉及业务逻辑。

The setup_logging function configured StreamHandler(sys.stdout), which
interleaves log lines with MCP JSON-RPC protocol messages on stdout.
This violates the MCP stdio transport specification, which requires
uncontaminated stdout for JSON-RPC wire format frames.

Changed to sys.stderr so structured logs go to stderr while stdout
remains clean for the MCP protocol. This is the Python convention:
stdout for program data, stderr for diagnostics.

The file handler continues to write to logs/mcp2anp.log as before.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant