Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(serve): route all stdout logging to stderr under stdio MCP (#3844)

Garry Tan810d1c554030
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index 70bfbbc015..56f979deef 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -2,6 +2,7 @@ import { spawnSync } from 'node:child_process';
import type { BrainEngine } from '../core/engine.ts';
import { startMcpServer } from '../mcp/server.ts';
import { VERB_NAMES } from '../core/verbs.ts';
+import { redirectStdoutLoggingToStderr } from '../core/console-prefix.ts';
// Maximum time the stdio path will wait for engine.disconnect() (PGLite
// close + advisory lock release) before forcing exit. Keeps a wedged
@@ -243,6 +244,12 @@ export async function runServe(
: 'Starting GBrain MCP server (stdio)...',
);
+ // stdout is reserved for JSON-RPC frames from here on. Ops that run
+ // in-process (sync_brain -> performSync -> embed --stale) emit progress
+ // via slog/console.log, which would otherwise land on stdout and make
+ // the MCP client log "Failed to parse JSONRPC message" for every line.
+ redirectStdoutLoggingToStderr();
+
installStdioLifecycle(engine, args, opts);
const start = opts.startMcpServer ?? startMcpServer;
diff --git a/src/core/console-prefix.ts b/src/core/console-prefix.ts
index 88c06e3b35..1203eeb7ea 100644
--- a/src/core/console-prefix.ts
+++ b/src/core/console-prefix.ts
@@ -51,6 +51,54 @@ import { AsyncLocalStorage } from 'node:async_hooks';
const __prefixStore = new AsyncLocalStorage<string>();
+// MCP stdio mode: stdout is reserved for JSON-RPC frames. When the stdio
+// serve path activates this guard, every logging surface this module owns
+// (slog's console.log fallthrough, slog's prefixed process.stdout.write)
+// routes to stderr instead, and the global console.log/info/debug are
+// rebound to console.error so library code reached from op handlers
+// (performSync, runEmbedCore, importFromFile, ...) can't emit plain text
+// onto the JSON-RPC channel. One direction only — never unset at runtime
+// (the serve process is stdio-MCP for its whole lifetime).
+let __stdoutLoggingRedirected = false;
+
+/**
+ * Route ALL stdout-bound logging to stderr for the lifetime of this
+ * process. Called once by the stdio MCP serve path before the transport
+ * starts. Idempotent.
+ *
+ * Rationale: any non-JSON-RPC line on stdout makes the MCP client's
+ * parser throw ("Failed to parse JSONRPC message"). Progress output from
+ * ops that run in-process (sync_brain -> performSync -> embed) previously
+ * leaked to stdout via slog / console.log.
+ */
+export function redirectStdoutLoggingToStderr(): void {
+ if (__stdoutLoggingRedirected) return;
+ __stdoutLoggingRedirected = true;
+ // eslint-disable-next-line no-console
+ const toStderr = (...args: unknown[]): void => console.error(...args);
+ // eslint-disable-next-line no-console
+ console.log = toStderr;
+ // eslint-disable-next-line no-console
+ console.info = toStderr;
+ // eslint-disable-next-line no-console
+ console.debug = toStderr;
+}
+
+/**
+ * Read-only accessor (test seam): is the stdio stderr redirect active?
+ */
+export function isStdoutLoggingRedirected(): boolean {
+ return __stdoutLoggingRedirected;
+}
+
+/**
+ * Test-only reset. Does NOT restore the original console bindings (tests
+ * that need those should snapshot them before calling the redirect).
+ */
+export function _resetStdoutRedirectForTests(): void {
+ __stdoutLoggingRedirected = false;
+}
+
/**
* Run `fn` with an active per-source prefix `id`. Within the closure,
* `slog` and `serr` will prepend `[id] ` to every line they emit. The
@@ -84,12 +132,15 @@ export function getSourcePrefix(): string | null {
export function slog(...args: unknown[]): void {
const prefix = getSourcePrefix();
if (prefix === null) {
- // Back-compat fast path: bare console.log semantics.
+ // Back-compat fast path: bare console.log semantics. (Under the stdio
+ // MCP redirect, console.log is rebound to stderr — see
+ // redirectStdoutLoggingToStderr.)
// eslint-disable-next-line no-console
console.log(...args);
return;
}
- process.stdout.write(prefixLines(formatArgs(args), prefix) + '\n');
+ const out = __stdoutLoggingRedirected ? process.stderr : process.stdout;
+ out.write(prefixLines(formatArgs(args), prefix) + '\n');
}
/**
diff --git a/test/serve-stdio-lifecycle.test.ts b/test/serve-stdio-lifecycle.test.ts
index 2215196baa..1adbab37f4 100644
--- a/test/serve-stdio-lifecycle.test.ts
+++ b/test/serve-stdio-lifecycle.test.ts
@@ -1,4 +1,4 @@
-import { describe, test, expect } from 'bun:test';
+import { describe, test, expect, afterEach } from 'bun:test';
import { EventEmitter } from 'events';
import { spawnSync } from 'node:child_process';
import {
@@ -9,6 +9,24 @@ import {
type ServeOptions,
} from '../src/commands/serve';
import type { BrainEngine } from '../src/core/engine';
+import { _resetStdoutRedirectForTests } from '../src/core/console-prefix';
+
+// runServe's stdio path calls redirectStdoutLoggingToStderr(), which
+// rebinds the process-global console.log/info/debug. Restore the real
+// bindings after every test so files sharing this shard process (e.g.
+// test/console-prefix.test.ts, which asserts bare console.log semantics)
+// don't inherit the redirect.
+/* eslint-disable no-console */
+const __realConsoleLog = console.log;
+const __realConsoleInfo = console.info;
+const __realConsoleDebug = console.debug;
+afterEach(() => {
+ console.log = __realConsoleLog;
+ console.info = __realConsoleInfo;
+ console.debug = __realConsoleDebug;
+ _resetStdoutRedirectForTests();
+});
+/* eslint-enable no-console */
// These tests cover the stdio lifecycle hooks added to runServe so that the
// PGLite write lock is released when the parent disconnects. We don't spawn
diff --git a/test/stdio-stderr-redirect.serial.test.ts b/test/stdio-stderr-redirect.serial.test.ts
new file mode 100644
index 0000000000..485105c046
--- /dev/null
+++ b/test/stdio-stderr-redirect.serial.test.ts
@@ -0,0 +1,135 @@
+/**
+ * v0.41.38+ — MCP stdio stderr redirect.
+ *
+ * The stdio MCP transport reserves stdout for JSON-RPC frames. Ops that run
+ * in-process (sync_brain -> performSync -> runEmbedCore) emit progress via
+ * slog / console.log; pre-fix those lines landed on stdout and every one made
+ * the MCP client log "Failed to parse JSONRPC message" + a pydantic
+ * ValidationError traceback.
+ *
+ * `redirectStdoutLoggingToStderr()` (called by the stdio serve path before
+ * the transport starts) must:
+ * 1. rebind console.log / console.info / console.debug to stderr
+ * 2. route slog's PREFIXED path (process.stdout.write under
+ * withSourcePrefix) to process.stderr
+ * 3. be idempotent
+ *
+ * Serial quarantine: this file mutates the global console bindings and the
+ * module-level redirect flag. It must not share a test process with files
+ * that assert bare console.log semantics (test/console-prefix.test.ts).
+ */
+import { describe, test, expect, beforeEach, afterAll } from 'bun:test';
+import {
+ slog,
+ withSourcePrefix,
+ redirectStdoutLoggingToStderr,
+ isStdoutLoggingRedirected,
+ _resetStdoutRedirectForTests,
+} from '../src/core/console-prefix.ts';
+
+// Snapshot the real bindings ONCE, before any redirect call in this file.
+/* eslint-disable no-console */
+const realLog = console.log;
+const realInfo = console.info;
+const realDebug = console.debug;
+const realError = console.error;
+const realStderrWrite = process.stderr.write;
+const realStdoutWrite = process.stdout.write;
+
+afterAll(() => {
+ console.log = realLog;
+ console.info = realInfo;
+ console.debug = realDebug;
+ console.error = realError;
+ process.stderr.write = realStderrWrite;
+ process.stdout.write = realStdoutWrite;
+ _resetStdoutRedirectForTests();
+});
+
+beforeEach(() => {
+ console.log = realLog;
+ console.info = realInfo;
+ console.debug = realDebug;
+ console.error = realError;
+ process.stderr.write = realStderrWrite;
+ process.stdout.write = realStdoutWrite;
+ _resetStdoutRedirectForTests();
+});
+
+describe('redirectStdoutLoggingToStderr', () => {
+ test('rebinds console.log/info/debug onto console.error (stderr)', () => {
+ const errCalls: unknown[][] = [];
+ console.error = (...args: unknown[]) => {
+ errCalls.push(args);
+ };
+
+ redirectStdoutLoggingToStderr();
+
+ console.log('a', 1);
+ console.info('b');
+ console.debug('c');
+
+ expect(errCalls).toEqual([['a', 1], ['b'], ['c']]);
+ expect(isStdoutLoggingRedirected()).toBe(true);
+ });
+
+ test('slog prefixed path writes to stderr, not stdout, under redirect', async () => {
+ const stderrLines: string[] = [];
+ const stdoutLines: string[] = [];
+ process.stderr.write = ((chunk: string) => {
+ stderrLines.push(String(chunk));
+ return true;
+ }) as typeof process.stderr.write;
+ process.stdout.write = ((chunk: string) => {
+ stdoutLines.push(String(chunk));
+ return true;
+ }) as typeof process.stdout.write;
+
+ redirectStdoutLoggingToStderr();
+
+ await withSourcePrefix('vault-brain', async () => {
+ slog('projects/foo: all 12 chunks already embedded');
+ });
+
+ expect(stdoutLines).toEqual([]);
+ expect(stderrLines).toEqual([
+ '[vault-brain] projects/foo: all 12 chunks already embedded\n',
+ ]);
+ });
+
+ test('slog unprefixed fallthrough lands on stderr via the console.log rebind', () => {
+ const errCalls: unknown[][] = [];
+ console.error = (...args: unknown[]) => {
+ errCalls.push(args);
+ };
+
+ redirectStdoutLoggingToStderr();
+ slog('bare progress line');
+
+ expect(errCalls).toEqual([['bare progress line']]);
+ });
+
+ test('idempotent: second call does not re-wrap (no double stderr emission)', () => {
+ const errCalls: unknown[][] = [];
+ console.error = (...args: unknown[]) => {
+ errCalls.push(args);
+ };
+
+ redirectStdoutLoggingToStderr();
+ redirectStdoutLoggingToStderr();
+
+ console.log('once');
+ expect(errCalls).toEqual([['once']]);
+ });
+
+ test('without redirect, slog keeps bare console.log semantics (back-compat)', () => {
+ const logCalls: unknown[][] = [];
+ console.log = (...args: unknown[]) => {
+ logCalls.push(args);
+ };
+
+ slog('normal cli output');
+ expect(logCalls).toEqual([['normal cli output']]);
+ expect(isStdoutLoggingRedirected()).toBe(false);
+ });
+});