diff --git a/.changeset/32942-stdio-host-console-to-stderr.md b/.changeset/32942-stdio-host-console-to-stderr.md new file mode 100644 index 00000000000..71baccfef9b --- /dev/null +++ b/.changeset/32942-stdio-host-console-to-stderr.md @@ -0,0 +1,13 @@ +--- +'@objectstack/cli': patch +'@objectstack/mcp': patch +--- + +fix(cli): with the stdio MCP transport on, what a host plugin writes to the console while serving a call reaches stderr + +Clause-②: no +Metadata-protocol: none + +An MCP client that spawns `os serve` or `os start` over stdio writes `initialize` at once and its first `tools/call` as soon as that is answered, so those calls are served while the server is still finishing its boot. `serve` holds back boot output during that time so the startup banner stays readable, and it held back the calls' output with it: a host plugin's `console.log`, `console.info` and `console.debug` from a tool-call interceptor or a hook reached neither stdout nor stderr. `console.warn` and `console.error` were not affected. + +The stdio transport now marks stdout when it claims it, and from that moment `serve` stops holding back console output: it goes to stderr, never to stdout, which still carries only JSON-RPC frames. Under stdio, the part of the boot that runs after the transport starts now prints its own console lines to stderr too, instead of dropping them. A boot without the stdio transport is unchanged. diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.ts index e863ec28f2d..5d4e3372486 100644 --- a/packages/cli/src/commands/serve.ts +++ b/packages/cli/src/commands/serve.ts @@ -415,6 +415,25 @@ type PortProbe = (port: number) => Promise; * skip**. ⚠️ Nearby cards have described this search as hopping over ports; it * does not, and a diagnostic written from that reading would be wrong. */ +/** + * The mark `@objectstack/mcp` leaves on `process.stdout` when its stdio + * transport claims the stream (`PROTOCOL_STDOUT_CLAIM`, + * `packages/mcp/src/protocol-stdout.ts`, which says why it is a `Symbol.for` + * key). Read here by key rather than imported, so the boot-quiet window does + * not load the MCP package to ask; the same key on both sides is pinned by + * `serve-stdio-stdout-purity.e2e.test.ts`, which boots the real transport. + */ +const PROTOCOL_STDOUT_CLAIM = Symbol.for('@objectstack/mcp:protocol-stdout-claimed'); + +/** + * Whether a stdio MCP transport has claimed this process's stdout — i.e. + * whether this process has started serving calls over stdio. `serve`'s + * boot-quiet window stops holding back the console from that moment. + */ +export function isProtocolStdoutClaimed(stream: NodeJS.WriteStream = process.stdout): boolean { + return (stream as unknown as Record)[PROTOCOL_STDOUT_CLAIM] === true; +} + export class PortSearchExhaustedError extends Error { /** The first port probed — the walk's own record of it, not the caller's. */ readonly startPort: number; @@ -2784,6 +2803,30 @@ export default class Serve extends Command { return lines.length > 0 ? { lines, dropped: bootLogs.droppedCount } : undefined; }; + /** + * Whether the boot-quiet window still holds back what is written to the + * console and to `process.stdout` — the window is open AND nothing is being + * served yet. + * + * The second half is the stdio MCP transport. Its client writes `initialize` + * at spawn and its first `tools/call` the moment that is answered, and the + * transport attaches inside `runtime.start()` — so those calls are served + * while this window is still open. Everything a host plugin + * `console.log`ged from one (an interceptor's audit line, a hook's trace) + * was dropped as boot chatter, and reached neither stream. So the window + * ends for the console once the transport has claimed stdout + * ({@link isProtocolStdoutClaimed}): from that moment a line may be a call's + * output, and the stream cannot tell it from the rest of the boot, so + * nothing is held back. It still goes to stderr — `origStdoutWrite` is the + * stderr forwarder — never to stdout, which carries the protocol only. + * + * Read per write, never once: the claim happens during the window. An + * HTTP-only boot never claims, so its window is exactly as before, and the + * console output of the boot up to the claim (every plugin's `init()`, the + * starts ahead of the MCP plugin's) is still held back under stdio too. + */ + const quietHolds = () => bootQuiet && !isProtocolStdoutClaimed(); + const restoreOutput = () => { bootQuiet = false; process.stdout.write = origStdoutWrite; @@ -2808,7 +2851,7 @@ export default class Serve extends Command { bootQuiet = !verboseBoot; if (!verboseBoot) { process.stdout.write = (chunk: any, ...rest: any[]) => { - if (bootQuiet) { + if (quietHolds()) { bootLogs.write(chunk, typeof rest[0] === 'string' ? rest[0] : undefined); // Honor the write callback so a caller awaiting drain still resumes. const cb = rest.find((a) => typeof a === 'function'); @@ -2817,8 +2860,8 @@ export default class Serve extends Command { } return (origStdoutWrite as any)(chunk, ...rest); }; - console.log = (...args: any[]) => { if (!bootQuiet) originalConsoleLog(...args); }; - console.debug = (...args: any[]) => { if (!bootQuiet) originalConsoleDebug(...args); }; + console.log = (...args: any[]) => { if (!quietHolds()) originalConsoleLog(...args); }; + console.debug = (...args: any[]) => { if (!quietHolds()) originalConsoleDebug(...args); }; } // Load configuration diff --git a/packages/cli/test/serve-stdio-stdout-purity.e2e.test.ts b/packages/cli/test/serve-stdio-stdout-purity.e2e.test.ts index 2ad84f78276..7f6e19e4bf5 100644 --- a/packages/cli/test/serve-stdio-stdout-purity.e2e.test.ts +++ b/packages/cli/test/serve-stdio-stdout-purity.e2e.test.ts @@ -105,6 +105,39 @@ export default { sharingModel: 'private', fields: { title: { type: 'text', label: 'Title' } }, }], + // A host plugin that writes through every console channel from a tool-call + // interceptor — the seam a host audits its calls through. Inert for the + // #7915 case below, which makes no tool call. FX_HOLD_FOR_CALL is set only by + // the console describe: it holds the boot (and so serve's boot-quiet window) + // open until a call has been served, so the call provably lands INSIDE the + // window instead of racing it. + plugins: [{ + name: 'fx.console-probe', + version: '1.0.0', + init: async () => { + console.log('[fx-boot-chatter] from init'); + }, + start: async (ctx) => { + let served; + const firstCall = new Promise((resolveCall) => { served = resolveCall; }); + ctx.getService('mcp').setToolInterceptor(async (call, next) => { + const tag = call.transport + ':' + call.toolName; + console.log('[fx-call] console.log ' + tag); + console.info('[fx-call] console.info ' + tag); + console.debug('[fx-call] console.debug ' + tag); + console.warn('[fx-call] console.warn ' + tag); + console.error('[fx-call] console.error ' + tag); + process.stdout.write('[fx-call] process.stdout.write ' + tag + String.fromCharCode(10)); + served(); + return next(); + }); + if (process.env.FX_HOLD_FOR_CALL === '1') { + ctx.hook('kernel:ready', async () => { + await Promise.race([firstCall, new Promise((r) => setTimeout(r, 30000))]); + }); + } + }, + }], }; `; @@ -304,90 +337,91 @@ function parseFrame(line: string): Record | undefined { } } -describe('#7915: a stdio MCP boot writes nothing but protocol frames to stdout', () => { - beforeAll(async () => { - // Build prerequisite first: the spawns below resolve `serve` from `dist/`. - requireBuiltCli(RUN_JS_RESOLVES_FROM_DIST); - - dir = mkdtempSync(join(tmpdir(), 'mcp-stdout-purity-e2e-')); - writeFileSync(join(dir, 'objectstack.config.ts'), CONFIG, 'utf8'); - writeFileSync( - join(dir, 'package.json'), - JSON.stringify({ name: 'mcp-stdout-purity-e2e-fixture', private: true, type: 'module' }, null, 2), - 'utf8', +// Shared by both describes below: one minting boot, one key, one database. +beforeAll(async () => { + // Build prerequisite first: the spawns below resolve `serve` from `dist/`. + requireBuiltCli(RUN_JS_RESOLVES_FROM_DIST); + + dir = mkdtempSync(join(tmpdir(), 'mcp-stdout-purity-e2e-')); + writeFileSync(join(dir, 'objectstack.config.ts'), CONFIG, 'utf8'); + writeFileSync( + join(dir, 'package.json'), + JSON.stringify({ name: 'mcp-stdout-purity-e2e-fixture', private: true, type: 'module' }, null, 2), + 'utf8', + ); + + // Boot 1 — mint a real key through the product route, against a FILE db so + // boot 2 sees the same row (`:memory:` would not survive the restart). + const first = await boot({ OS_DATABASE_URL: join(dir, 'probe.db') }, /Server is ready/); + const base = `http://localhost:${first.port}/api/v1`; + + // ⭐ #15898 — the fifth and last file of the family #15653 repaired. + // `boot()`'s `child.on('exit')` handler feeds the READINESS promise ONLY — it + // returns early once `settled` — so a death AFTER readiness is invisible to + // it, and the two requests below used to reach vitest as a bare + // `TypeError: fetch failed` with no exit code, no stdout and no stderr: the + // unattributable failure #15545 recorded once and could not diagnose. + // `probeThroughChild()` is where the child's fate is read instead; its own + // section in `helpers/serve-process.ts` carries the measurement, the bound + // and the fences (⛔ no skip, no quarantine, no timeout bump). + // + // Read at THROW time, so a failure carries what the child printed on its way + // down rather than the buffer as it stood at ready. + const transcript = () => + `\n--- child stdout ---\n${first.stdout()}\n--- child stderr ---\n${first.stderr()}`; + const probe = (what: string, request: () => Promise): Promise => + probeThroughChild( + { + child: first.child, + transcript, + label: 'serve-stdio-stdout-purity', + what: `${what} on port ${first.port}`, + }, + request, ); - // Boot 1 — mint a real key through the product route, against a FILE db so - // boot 2 sees the same row (`:memory:` would not survive the restart). - const first = await boot({ OS_DATABASE_URL: join(dir, 'probe.db') }, /Server is ready/); - const base = `http://localhost:${first.port}/api/v1`; - - // ⭐ #15898 — the fifth and last file of the family #15653 repaired. - // `boot()`'s `child.on('exit')` handler feeds the READINESS promise ONLY — it - // returns early once `settled` — so a death AFTER readiness is invisible to - // it, and the two requests below used to reach vitest as a bare - // `TypeError: fetch failed` with no exit code, no stdout and no stderr: the - // unattributable failure #15545 recorded once and could not diagnose. - // `probeThroughChild()` is where the child's fate is read instead; its own - // section in `helpers/serve-process.ts` carries the measurement, the bound - // and the fences (⛔ no skip, no quarantine, no timeout bump). - // - // Read at THROW time, so a failure carries what the child printed on its way - // down rather than the buffer as it stood at ready. - const transcript = () => - `\n--- child stdout ---\n${first.stdout()}\n--- child stderr ---\n${first.stderr()}`; - const probe = (what: string, request: () => Promise): Promise => - probeThroughChild( - { - child: first.child, - transcript, - label: 'serve-stdio-stdout-purity', - what: `${what} on port ${first.port}`, - }, - request, - ); - - // ⛔ The body read is INSIDE the thunk and cannot throw: a connection torn - // down mid-body rejects out of `res.json()` rather than out of `fetch()`, and - // the guard reads any throw as a transport failure — so an ASSERTION must - // never live in here or a wrong answer would be reported as a dropped socket. - const signIn = await probe('the sign-in probe', async () => { - const res = await fetch(`${base}/auth/sign-in/email`, { - method: 'POST', - headers: { 'content-type': 'application/json' }, - // `serve --dev` seeds this admin on an empty DB. - body: JSON.stringify({ email: 'admin@objectos.ai', password: 'admin123' }), - }); - let body: unknown = null; - try { body = await res.json(); } catch { /* non-JSON error body */ } - return { status: res.status, body }; + // ⛔ The body read is INSIDE the thunk and cannot throw: a connection torn + // down mid-body rejects out of `res.json()` rather than out of `fetch()`, and + // the guard reads any throw as a transport failure — so an ASSERTION must + // never live in here or a wrong answer would be reported as a dropped socket. + const signIn = await probe('the sign-in probe', async () => { + const res = await fetch(`${base}/auth/sign-in/email`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + // `serve --dev` seeds this admin on an empty DB. + body: JSON.stringify({ email: 'admin@objectos.ai', password: 'admin123' }), }); - expect(signIn.status).toBe(200); - const token = (signIn.body as { token?: string } | null)?.token; - expect(token).toBeTruthy(); - - const minted = await probe('the key-mint probe', async () => { - const res = await fetch(`${base}/keys`, { - method: 'POST', - headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` }, - body: JSON.stringify({ name: 'mcp-stdout-purity-e2e' }), - }); - let body: unknown = null; - try { body = await res.json(); } catch { /* non-JSON error body */ } - return { status: res.status, body }; + let body: unknown = null; + try { body = await res.json(); } catch { /* non-JSON error body */ } + return { status: res.status, body }; + }); + expect(signIn.status).toBe(200); + const token = (signIn.body as { token?: string } | null)?.token; + expect(token).toBeTruthy(); + + const minted = await probe('the key-mint probe', async () => { + const res = await fetch(`${base}/keys`, { + method: 'POST', + headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` }, + body: JSON.stringify({ name: 'mcp-stdout-purity-e2e' }), }); - expect(minted.status).toBe(201); - apiKey = String((minted.body as { data: { key: string } }).data.key); - expect(apiKey.startsWith('osk_')).toBe(true); + let body: unknown = null; + try { body = await res.json(); } catch { /* non-JSON error body */ } + return { status: res.status, body }; + }); + expect(minted.status).toBe(201); + apiKey = String((minted.body as { data: { key: string } }).data.key); + expect(apiKey.startsWith('osk_')).toBe(true); - await stop(first.child); - }, 240_000); + await stop(first.child); +}, 240_000); - afterAll(async () => { - for (const child of children) await stop(child); - if (dir) rmSync(dir, { recursive: true, force: true }); - }, 60_000); +afterAll(async () => { + for (const child of children) await stop(child); + if (dir) rmSync(dir, { recursive: true, force: true }); +}, 60_000); +describe('#7915: a stdio MCP boot writes nothing but protocol frames to stdout', () => { it('keeps stdout free of every non-frame byte, and keeps the diagnostics on stderr', async () => { // Wait for the banner's LAST line, not for `[MCP] Server started`. The // transport attaches inside `runtime.start()`, which the banner follows — @@ -495,3 +529,158 @@ describe('#7915: a stdio MCP boot writes nothing but protocol frames to stdout', await stop(booted.child); }, 240_000); }); + +/** + * #32942 — with the stdio MCP transport on, what a host plugin writes to the + * console while SERVING a call reaches stderr, never stdout. + * + * ## The defect, measured on `origin/main` before the fix + * + * A stdio client writes `initialize` at spawn and its first `tools/call` the + * moment that is answered. The transport attaches inside `runtime.start()`, so + * those calls are served while `serve`'s boot-quiet window is still open — and + * the window dropped `console.log` / `console.debug` outright and filtered + * `process.stdout.write` (so `console.info` too) down to kernel-logger records. + * A host interceptor's audit line therefore reached NEITHER stream, while + * `console.warn` / `console.error` (stderr) and the same plugin over HTTP were + * fine. A plugin that logs from a timer after the banner never showed it: the + * defect is the window, not the redirect. + * + * ## What is pinned + * + * 1. under stdio, a call served inside the window — `FX_HOLD_FOR_CALL` holds + * the boot open until it is, and the line is asserted to precede the + * banner — puts every console channel's line on stderr; + * 2. stdout carries nothing but JSON-RPC frames, every line parsed; + * 3. the window still holds back the boot's own chatter up to the claim + * (`[fx-boot-chatter]` from `init()`), on both streams; + * 4. CONTROL: an HTTP boot (no stdio claim) keeps its window as before — the + * boot chatter held back, a post-boot HTTP call's lines on stderr, stdout + * empty. + * + * `OS_LOG_LEVEL: 'warn'` on both boots: the #7915 case runs at `info`, which is + * a verbose level, and at a verbose level `serve` never opens the window — the + * defect would be unreachable. + */ +describe('#32942: a stdio call\'s console output reaches stderr, never stdout, even inside the boot-quiet window', () => { + /** Every console channel the interceptor writes through, as it tags them. */ + const CHANNELS = ['console.log', 'console.info', 'console.debug', 'console.warn', 'console.error', 'process.stdout.write']; + + it('stdio: the call\'s lines are on stderr before the banner, stdout is frames only, boot chatter still held', async () => { + const child = spawn(process.execPath, [CLI, 'serve', '-p', KERNEL_ASSIGNED_PORT, '--dev'], { + cwd: dir, + stdio: ['pipe', 'pipe', 'pipe'], + env: childEnv({ + NO_COLOR: '1', + OS_LOG_LEVEL: 'warn', + OS_DISABLE_CONSOLE: '1', + OS_SECRET_KEY: E2E_SECRET_KEY, + NODE_ENV: undefined, + OS_DATABASE_URL: join(dir, 'probe.db'), + OS_MCP_STDIO_ENABLED: 'true', + OS_MCP_STDIO_API_KEY: apiKey, + FX_HOLD_FOR_CALL: '1', + }), + }) as ChildProcessWithoutNullStreams; + children.push(child); + + let stdout = ''; + let stderr = ''; + let called = false; + const send = (msg: unknown) => child.stdin.write(`${JSON.stringify(msg)}\n`); + const ready = new Promise((settle) => { + const timer = setTimeout(() => settle(false), 150_000); + child.stdout.on('data', (d) => { + stdout += String(d); + // The SDK client's shape: the first call goes out the moment the + // `initialize` answer is read — the banner has not printed yet. + if (!called && stdout.split('\n').slice(0, -1).some((line) => parseFrame(line)?.id === 1)) { + called = true; + send({ jsonrpc: '2.0', method: 'notifications/initialized' }); + send({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'list_objects', arguments: {} } }); + } + }); + child.stderr.on('data', (d) => { + stderr += String(d); + if (/Press Ctrl\+C to stop/.test(stderr)) { clearTimeout(timer); settle(true); } + }); + child.on('exit', () => { clearTimeout(timer); settle(false); }); + }); + // AT SPAWN, as an MCP client does. + send({ + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'objectstack-e2e', version: '0.0.0' } }, + }); + const booted = await ready; + await new Promise((r) => setTimeout(r, 750)); + const seen = `\n--- stdout ---\n${stdout.slice(0, 4000)}\n--- stderr ---\n${stderr.slice(-6000)}`; + expect(booted, `serve never printed its banner${seen}`).toBe(true); + + // The call was answered on the channel. + const lines = stdout.split('\n').slice(0, -1).filter((line) => line.length > 0); + const answer = lines.map(parseFrame).find((msg) => msg?.id === 2); + expect(answer, `list_objects was never answered${seen}`).toBeTruthy(); + expect(answer!.error, `list_objects answered an error${seen}`).toBeUndefined(); + + // 2. stdout: every line a JSON-RPC frame. + expect(lines.filter((line) => parseFrame(line) === undefined), `stdout carries non-frame lines${seen}`).toEqual([]); + + // 1. every channel's line is on stderr — and ahead of the banner, so it was + // written while the window was open rather than after it closed. + const banner = stderr.indexOf('Server is ready'); + for (const channel of CHANNELS) { + const at = stderr.indexOf(`[fx-call] ${channel} stdio:list_objects`); + expect(at, `the ${channel} line of the stdio call is missing from stderr${seen}`).toBeGreaterThanOrEqual(0); + expect(at, `the ${channel} line landed after the banner, so the call missed the window${seen}`).toBeLessThan(banner); + } + + // 3. the boot's own chatter, before the transport claimed stdout, is still held back. + expect(stderr + stdout, `the window no longer holds back boot chatter${seen}`).not.toContain('[fx-boot-chatter]'); + + await stop(child); + }, 240_000); + + it('CONTROL — HTTP: the window holds boot chatter as before, a call\'s lines reach stderr, stdout stays empty', async () => { + const booted = await boot( + { OS_LOG_LEVEL: 'warn', OS_DATABASE_URL: join(dir, 'probe.db') }, + /Press Ctrl\+C to stop/, + ); + const url = `http://localhost:${booted.port}/api/v1/mcp`; + const call = await probeThroughChild( + { + child: booted.child, + transcript: () => `\n--- child stdout ---\n${booted.stdout()}\n--- child stderr ---\n${booted.stderr()}`, + label: 'serve-stdio-stdout-purity', + what: `the HTTP list_objects call on port ${booted.port}`, + }, + async () => { + const res = await fetch(url, { + method: 'POST', + headers: { + 'content-type': 'application/json', + accept: 'application/json, text/event-stream', + authorization: `Bearer ${apiKey}`, + }, + body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'list_objects', arguments: {} } }), + }); + let text = ''; + try { text = await res.text(); } catch { /* torn-down body */ } + return { status: res.status, text }; + }, + ); + await new Promise((r) => setTimeout(r, 750)); + const seen = `\n--- HTTP ${call.status} ${call.text.slice(0, 400)}\n--- stdout ---\n${booted.stdout().slice(0, 2000)}\n--- stderr ---\n${booted.stderr().slice(-6000)}`; + expect(call.status, `the HTTP call failed${seen}`).toBe(200); + + const stderr = booted.stderr(); + for (const channel of CHANNELS) { + expect(stderr, `the ${channel} line of the HTTP call is missing from stderr${seen}`).toContain(`[fx-call] ${channel} http:list_objects`); + } + expect(booted.stdout(), `an HTTP boot wrote to stdout${seen}`).toBe(''); + expect(stderr + booted.stdout(), `the window no longer holds back boot chatter${seen}`).not.toContain('[fx-boot-chatter]'); + + await stop(booted.child); + }, 240_000); +}); diff --git a/packages/mcp/src/protocol-stdout.test.ts b/packages/mcp/src/protocol-stdout.test.ts index d0a9f9b87d4..041888f42d9 100644 --- a/packages/mcp/src/protocol-stdout.test.ts +++ b/packages/mcp/src/protocol-stdout.test.ts @@ -16,7 +16,7 @@ */ import { describe, it, expect, afterEach } from 'vitest'; -import { protocolStdout } from './protocol-stdout.js'; +import { PROTOCOL_STDOUT_CLAIM, protocolStdout } from './protocol-stdout.js'; type StreamWrite = (chunk: string | Uint8Array, ...rest: unknown[]) => boolean; @@ -24,6 +24,7 @@ const originalWrite = process.stdout.write; afterEach(() => { process.stdout.write = originalWrite; + delete (process.stdout as unknown as Record)[PROTOCOL_STDOUT_CLAIM]; }); describe('protocolStdout (#7915)', () => { @@ -86,4 +87,19 @@ describe('protocolStdout (#7915)', () => { proto.write = protoWrite; } }); + + // A host's boot-quiet window ends for the console when it reads this mark + // (`os serve`, packages/cli/src/commands/serve.ts): a stdio call is served + // while that window is open, and its console output was dropped with the boot + // chatter. The host reads the key by `Symbol.for`, without importing this + // package, so the key's spelling is part of the contract. + it('marks process.stdout as claimed, under the shared Symbol.for key, before any frame is written', () => { + const marks = process.stdout as unknown as Record; + expect(marks[PROTOCOL_STDOUT_CLAIM]).toBeUndefined(); + + protocolStdout(); + + expect(marks[PROTOCOL_STDOUT_CLAIM]).toBe(true); + expect(PROTOCOL_STDOUT_CLAIM).toBe(Symbol.for('@objectstack/mcp:protocol-stdout-claimed')); + }); }); diff --git a/packages/mcp/src/protocol-stdout.ts b/packages/mcp/src/protocol-stdout.ts index 16b6dae0d3b..5cc99b80326 100644 --- a/packages/mcp/src/protocol-stdout.ts +++ b/packages/mcp/src/protocol-stdout.ts @@ -2,6 +2,29 @@ import type { Writable } from 'node:stream'; +/** + * The mark {@link protocolStdout} leaves on `process.stdout` when a stdio + * transport claims it: from that moment this process is SERVING, and whatever + * it writes may be the output of a call rather than of its boot. + * + * Who reads it: a host that holds its boot output back for a while. `os serve` + * keeps a boot-quiet window open until `runtime.start()` returns, so the + * banner is not buried under boot chatter (`packages/cli/src/commands/serve.ts`). + * A stdio client writes `initialize` at spawn and its first `tools/call` the + * moment that is answered, so its calls are served while that window is still + * open: everything a host plugin `console.log`ged from them was dropped with + * the chatter, on stdout and stderr alike. The window ends for a host's console + * when it reads this mark — and only then, so an HTTP-only boot keeps its quiet + * window exactly as before. + * + * Registered with `Symbol.for`, so a second copy of this package in the + * process (an ESM and a CJS load, two versions) writes the same key, and a host + * can read it without importing this package. The key is pinned on both sides + * (this package's `protocol-stdout.test.ts`, and the CLI's stdio purity e2e, + * which boots the real transport). + */ +export const PROTOCOL_STDOUT_CLAIM: unique symbol = Symbol.for('@objectstack/mcp:protocol-stdout-claimed'); + /** * The stdout channel the **stdio MCP transport** writes its JSON-RPC frames to * (#7915). @@ -50,6 +73,11 @@ export function protocolStdout(): Writable { once: (event: string, listener: (...args: unknown[]) => void) => unknown; }; + // Say so on the stream, BEFORE the transport can read its first request: the + // caller attaches stdin only after this returns, so no call can be served + // while the mark is still missing. See {@link PROTOCOL_STDOUT_CLAIM}. + (stdout as unknown as Record)[PROTOCOL_STDOUT_CLAIM] = true; + // The prototype's `write`, i.e. the one an instance-level interception // replaced. Falls back to the instance property when there is no prototype // implementation to reach (never true for Node's stdout — TTY, pipe and file