From ebcb0917bec2021c3c15ebcee542f544df0816fd Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 22:38:39 -0600 Subject: [PATCH 1/3] =?UTF-8?q?feat(mcpx):=20codedb=20shared=20daemon=20+?= =?UTF-8?q?=20stdio=20MCP=20bridge=20=E2=80=94=20lift=20the=20#2220=20park?= =?UTF-8?q?=20in=20the=20new=20shape=20(#4120)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One codedb serve daemon per project root (user systemd unit codedb-code.service for ~/git/code) replaces one index-holding codedb mcp process per session (~1.1 GB RSS warm each, #2225). bin/codedb-bridge.mjs is a stateless stdio MCP shim forwarding the daemon-backed tools (tree/outline/symbol/search/word/hot/deps) to http://127.0.0.1:7719/explore/*; arguments the daemon cannot honour are rejected by name per the #3352 contract. .mcpx.json moves codedb from disabledMcpServers to mcpServers via the bridge, CODEDB_NO_TELEMETRY=1 retained. --- .mcpx.json | 11 +- bin/codedb-bridge.mjs | 271 +++++++++++++++++++++++++++++++++++++ bin/codedb-bridge.test.mjs | 108 +++++++++++++++ 3 files changed, 384 insertions(+), 6 deletions(-) create mode 100644 bin/codedb-bridge.mjs create mode 100644 bin/codedb-bridge.test.mjs diff --git a/.mcpx.json b/.mcpx.json index c1f2698a5d..41f15e2008 100644 --- a/.mcpx.json +++ b/.mcpx.json @@ -82,14 +82,13 @@ "fff-worktree": { "command": "/home/user/.local/bin/fff-mcp", "args": ["/home/user/.local/share/opencode/worktree"] - } - }, - "disabledMcpServers": { + }, "codedb": { - "command": "/home/user/bin/codedb", - "args": ["mcp"], + "command": "node", + "args": ["/home/user/git/code/bin/codedb-bridge.mjs"], "env": { - "CODEDB_NO_TELEMETRY": "1" + "CODEDB_NO_TELEMETRY": "1", + "CODEDB_DAEMON_URL": "http://127.0.0.1:7719" } } }, diff --git a/bin/codedb-bridge.mjs b/bin/codedb-bridge.mjs new file mode 100644 index 0000000000..0b292f0842 --- /dev/null +++ b/bin/codedb-bridge.mjs @@ -0,0 +1,271 @@ +// codedb-bridge — thin stateless stdio MCP bridge to a shared codedb daemon (#4120, from the #2225 determination). +// +// Why this exists: `codedb mcp` runs one stdio process per client session +// and each process loads the whole project index (~1.1 GB RSS warm / +// ~2.1 GB cold-peak on ~/git/code, measured in #2225). `codedb serve` +// holds one index per project root as an HTTP daemon on :7719, but it +// speaks no MCP. This bridge is the per-session shim: it exposes the +// daemon-backed codedb MCP tools over stdio and forwards every call to +// http://127.0.0.1:7719. It holds no index and no state; the expensive +// part (the daemon) is shared by every session. +// +// Daemon surface (verified live against codedb 0.2.2, 2026-11-02): +// GET /health -> {"status":"ok"} +// GET /explore/tree -> {"tree":"..."} +// GET /explore/outline?path= -> {"path":...,"symbols":[...]} +// GET /explore/symbol?name= -> {"name":...,"results":[...]} +// GET /explore/search?q= -> {"query":...,"results":[...]} +// GET /explore/word?q= -> {"query":...,"hits":[...]} +// GET /explore/hot -> {"files":[...]} +// GET /explore/deps?path= -> {"path":...,"imported_by":[...]} +// The daemon has no HTTP route for codedb_read / codedb_edit / +// codedb_changes / codedb_status / codedb_snapshot / codedb_bundle / +// codedb_projects / codedb_index, so the bridge does not advertise them. +// +// Argument contract (per #3352: no silent third paths): arguments the +// daemon cannot honour are rejected by name, never silently ignored — +// `project` (the daemon serves exactly one root), `regex: true`, +// `scope: true`, `compact: true`. `max_results` / `limit` are honoured +// by slicing the daemon's full result set. `body: true` on codedb_symbol +// is served from the daemon's per-result `detail` (the definition line); +// it is not a separate fetch. +// +// Config: CODEDB_DAEMON_URL (default http://127.0.0.1:7719). + +export const DEFAULT_DAEMON_URL = 'http://127.0.0.1:7719'; + +export const parseDaemonUrl = (raw) => { + const value = raw === undefined || raw === '' ? DEFAULT_DAEMON_URL : raw; + let url; + try { + url = new URL(value); + } catch { + throw new Error(`CODEDB_DAEMON_URL="${value}" is not a valid URL`); + } + if (url.protocol !== 'http:' || (url.pathname !== '/' && url.pathname !== '')) { + throw new Error( + `CODEDB_DAEMON_URL="${value}" must be an http:// origin with no path (the bridge appends /explore/* routes itself)` + ); + } + return url.origin; +}; + +const PROJECT_ARG_NOTE = + 'Not supported by codedb-bridge: the shared daemon serves exactly one project root, so there is no per-call project to select.'; + +const tool = (name, description, properties, required = []) => ({ + name, + description, + inputSchema: { type: 'object', properties, required }, +}); + +export const CODEDB_TOOLS = [ + tool( + 'codedb_tree', + 'Get the full file tree of the indexed codebase with language detection, line counts, and symbol counts per file. Use this first to understand the project structure. Served by the shared codedb daemon (GET /explore/tree).', + {} + ), + tool( + 'codedb_outline', + 'Get the structural outline of a file: all functions, structs, enums, imports, constants with line numbers. Like an IDE symbol view. Served by the shared codedb daemon (GET /explore/outline).', + { path: { type: 'string', description: 'File path relative to project root' } }, + ['path'] + ), + tool( + 'codedb_symbol', + 'Find ALL definitions of a symbol name across the entire codebase. Returns every file and line where this symbol is defined, with the definition line as detail. Served by the shared codedb daemon (GET /explore/symbol).', + { + name: { type: 'string', description: 'Symbol name to search for (exact match)' }, + body: { + type: 'boolean', + description: + 'Accepted for compatibility; the daemon result already carries the definition line as `detail` and has no separate body fetch (default: false)', + }, + }, + ['name'] + ), + tool( + 'codedb_search', + 'Full-text search across all indexed files. Uses trigram index for fast substring matching. Returns matching lines with file paths and line numbers. Served by the shared codedb daemon (GET /explore/search). Regex, scope and compact modes have no daemon route and are rejected, not ignored.', + { + query: { type: 'string', description: 'Text to search for (substring match)' }, + max_results: { type: 'integer', description: 'Maximum results to return (sliced from the daemon result set)' }, + }, + ['query'] + ), + tool( + 'codedb_word', + 'O(1) word lookup using inverted index. Finds all occurrences of an exact word (identifier) across the codebase. Much faster than search for single-word queries. Served by the shared codedb daemon (GET /explore/word).', + { word: { type: 'string', description: 'Exact word/identifier to look up' } }, + ['word'] + ), + tool( + 'codedb_hot', + 'Get the most recently modified files in the codebase, ordered by recency. Useful to see what\'s been actively worked on. Served by the shared codedb daemon (GET /explore/hot).', + { limit: { type: 'integer', description: 'Number of files to return (sliced from the daemon result set)' } } + ), + tool( + 'codedb_deps', + 'Get reverse dependencies: which files import/depend on the given file. Useful for impact analysis. Served by the shared codedb daemon (GET /explore/deps).', + { path: { type: 'string', description: 'File path to check dependencies for' } }, + ['path'] + ), +]; + +// Map a tool call to the daemon route. Throws an Error naming the exact +// problem for unknown tools, missing required arguments, and arguments +// the daemon cannot honour — nothing is silently dropped (#3352). +export const routeForTool = (name, args = {}) => { + const rejectProject = () => { + if (args.project !== undefined) throw new Error(`argument "project": ${PROJECT_ARG_NOTE}`); + }; + const rejectTrue = (key) => { + if (args[key] === true) { + throw new Error(`argument "${key}": true is not supported by the codedb daemon route for ${name}; omit it or call codedb directly`); + } + }; + const need = (key) => { + if (typeof args[key] !== 'string' || args[key] === '') { + throw new Error(`argument "${key}" is required for ${name} and must be a non-empty string`); + } + return args[key]; + }; + switch (name) { + case 'codedb_tree': + rejectProject(); + return { route: '/explore/tree', kind: 'tree' }; + case 'codedb_outline': + rejectProject(); + rejectTrue('compact'); + return { route: `/explore/outline?path=${encodeURIComponent(need('path'))}`, kind: 'json' }; + case 'codedb_symbol': + rejectProject(); + return { route: `/explore/symbol?name=${encodeURIComponent(need('name'))}`, kind: 'json' }; + case 'codedb_search': + rejectProject(); + rejectTrue('regex'); + rejectTrue('scope'); + rejectTrue('compact'); + return { route: `/explore/search?q=${encodeURIComponent(need('query'))}`, kind: 'json', slice: ['results', args.max_results] }; + case 'codedb_word': + rejectProject(); + return { route: `/explore/word?q=${encodeURIComponent(need('word'))}`, kind: 'json' }; + case 'codedb_hot': + rejectProject(); + return { route: '/explore/hot', kind: 'json', slice: ['files', args.limit] }; + case 'codedb_deps': + rejectProject(); + return { route: `/explore/deps?path=${encodeURIComponent(need('path'))}`, kind: 'json' }; + default: + throw new Error( + `unknown tool "${name}": codedb-bridge serves only the daemon-backed tools (${CODEDB_TOOLS.map((t) => t.name).join(', ')}); the daemon has no route for the other codedb tools` + ); + } +}; + +const sliceData = (data, slice) => { + if (!slice) return data; + const [key, n] = slice; + if (n === undefined) return data; + if (!Number.isInteger(n) || n < 0) throw new Error(`slice limit must be a non-negative integer, got ${JSON.stringify(n)}`); + if (Array.isArray(data?.[key])) return { ...data, [key]: data[key].slice(0, n) }; + return data; +}; + +const textResult = (text, isError = false) => ({ + content: [{ type: 'text', text }], + ...(isError ? { isError: true } : {}), +}); + +export const createHandler = ({ fetchFn, daemonUrl }) => { + const callTool = async (params) => { + const name = params?.name; + const args = params?.arguments ?? {}; + let mapped; + try { + mapped = routeForTool(name, args); + } catch (err) { + return textResult(err.message, true); + } + let res; + try { + res = await fetchFn(`${daemonUrl}${mapped.route}`); + } catch (err) { + return textResult( + `codedb daemon unreachable at ${daemonUrl} (${err.message}). Is the codedb serve unit running for this project root? Start it with: systemctl --user start codedb-.service`, + true + ); + } + let data; + try { + data = await res.json(); + } catch { + return textResult(`codedb daemon at ${daemonUrl} returned a non-JSON response (HTTP ${res.status}) for ${mapped.route}`, true); + } + if (!res.ok || data?.error) { + return textResult(`codedb daemon error for ${name}: ${data?.error ?? `HTTP ${res.status}`}`, true); + } + try { + data = sliceData(data, mapped.slice); + } catch (err) { + return textResult(err.message, true); + } + return textResult(mapped.kind === 'tree' ? String(data.tree ?? '') : JSON.stringify(data)); + }; + + // Returns a JSON-RPC response object, or null for notifications. + const handle = async (msg) => { + if (msg === null || typeof msg !== 'object' || Array.isArray(msg)) return null; + const { id, method, params } = msg; + if (id === undefined || id === null) return null; // notification: nothing to answer + const ok = (result) => ({ jsonrpc: '2.0', id, result }); + const fail = (code, message) => ({ jsonrpc: '2.0', id, error: { code, message } }); + switch (method) { + case 'initialize': + return ok({ + protocolVersion: params?.protocolVersion ?? '2024-11-05', + capabilities: { tools: { listChanged: false } }, + serverInfo: { name: 'codedb-bridge', version: '1.0.0' }, + }); + case 'ping': + return ok({}); + case 'tools/list': + return ok({ tools: CODEDB_TOOLS }); + case 'tools/call': + return ok(await callTool(params ?? {})); + default: + return fail(-32601, `method not found: ${method}`); + } + }; + return handle; +}; + +const main = async () => { + let daemonUrl; + try { + daemonUrl = parseDaemonUrl(process.env.CODEDB_DAEMON_URL); + } catch (err) { + console.error(err.message); + process.exit(1); + } + const handle = createHandler({ fetchFn: (url) => fetch(url), daemonUrl }); + const readline = await import('node:readline'); + const rl = readline.createInterface({ input: process.stdin, terminal: false }); + for await (const line of rl) { + const trimmed = line.trim(); + if (trimmed === '') continue; + let msg; + try { + msg = JSON.parse(trimmed); + } catch { + continue; // not JSON-RPC; codedb's own stdio server ignores malformed lines the same way + } + const response = await handle(msg); + if (response !== null) process.stdout.write(`${JSON.stringify(response)}\n`); + } +}; + +import { pathToFileURL } from 'node:url'; +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + await main(); +} diff --git a/bin/codedb-bridge.test.mjs b/bin/codedb-bridge.test.mjs new file mode 100644 index 0000000000..e75d728bd8 --- /dev/null +++ b/bin/codedb-bridge.test.mjs @@ -0,0 +1,108 @@ +// Tests for the codedb MCP bridge (#4120). +// Run: node --test bin/codedb-bridge.test.mjs +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { CODEDB_TOOLS, createHandler, parseDaemonUrl, routeForTool } from './codedb-bridge.mjs'; + +test('daemon URL defaults to the codedb serve origin and rejects non-origins', () => { + assert.equal(parseDaemonUrl(undefined), 'http://127.0.0.1:7719'); + assert.equal(parseDaemonUrl(''), 'http://127.0.0.1:7719'); + assert.equal(parseDaemonUrl('http://127.0.0.1:7719/'), 'http://127.0.0.1:7719'); + assert.throws(() => parseDaemonUrl('not a url'), /CODEDB_DAEMON_URL/); + assert.throws(() => parseDaemonUrl('https://127.0.0.1:7719'), /CODEDB_DAEMON_URL/); + assert.throws(() => parseDaemonUrl('http://127.0.0.1:7719/explore'), /CODEDB_DAEMON_URL/); +}); + +test('every advertised tool maps to a verified daemon route', () => { + const args = { + codedb_tree: {}, + codedb_outline: { path: 'a/b.rs' }, + codedb_symbol: { name: 'IdentityStore' }, + codedb_search: { query: 'IdentityStore' }, + codedb_word: { word: 'IdentityStore' }, + codedb_hot: {}, + codedb_deps: { path: 'a/b.rs' }, + }; + for (const t of CODEDB_TOOLS) { + const { route } = routeForTool(t.name, args[t.name]); + assert.ok(route.startsWith('/explore/'), `${t.name} -> ${route}`); + } + assert.equal(routeForTool('codedb_search', { query: 'a b' }).route, '/explore/search?q=a%20b'); + assert.equal(routeForTool('codedb_word', { word: 'x' }).route, '/explore/word?q=x'); + assert.equal(routeForTool('codedb_symbol', { name: 'x' }).route, '/explore/symbol?name=x'); +}); + +test('unhonourable arguments are rejected by name, never silently ignored (#3352)', () => { + assert.throws(() => routeForTool('codedb_search', { query: 'x', regex: true }), /"regex"/); + assert.throws(() => routeForTool('codedb_search', { query: 'x', scope: true }), /"scope"/); + assert.throws(() => routeForTool('codedb_outline', { path: 'x', compact: true }), /"compact"/); + assert.throws(() => routeForTool('codedb_tree', { project: '/elsewhere' }), /"project"/); + assert.throws(() => routeForTool('codedb_search', {}), /"query" is required/); + assert.throws(() => routeForTool('codedb_read', { path: 'x' }), /unknown tool "codedb_read"/); +}); + +const stubFetch = (routes) => async (url) => { + const path = url.replace('http://127.0.0.1:7719', ''); + if (!(path in routes)) return { ok: false, status: 404, json: async () => ({ error: 'not found' }) }; + return { ok: true, status: 200, json: async () => routes[path] }; +}; + +const call = async (handle, name, args) => + handle({ jsonrpc: '2.0', id: 9, method: 'tools/call', params: { name, arguments: args } }); + +test('handler answers initialize, tools/list and ping; notifications get no reply', async () => { + const handle = createHandler({ fetchFn: stubFetch({}), daemonUrl: 'http://127.0.0.1:7719' }); + const init = await handle({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2024-11-05' } }); + assert.equal(init.result.serverInfo.name, 'codedb-bridge'); + assert.equal(init.result.protocolVersion, '2024-11-05'); + const list = await handle({ jsonrpc: '2.0', id: 2, method: 'tools/list' }); + assert.deepEqual(list.result.tools.map((t) => t.name), CODEDB_TOOLS.map((t) => t.name)); + assert.deepEqual((await handle({ jsonrpc: '2.0', id: 3, method: 'ping' })).result, {}); + assert.equal(await handle({ jsonrpc: '2.0', method: 'notifications/initialized' }), null); + const bad = await handle({ jsonrpc: '2.0', id: 4, method: 'resources/list' }); + assert.equal(bad.error.code, -32601); +}); + +test('tools/call forwards to the daemon and returns its payload', async () => { + const handle = createHandler({ + fetchFn: stubFetch({ + '/explore/tree': { tree: 'a/\n b.rs rust 3L 1 sym\n' }, + '/explore/search?q=IdentityStore': { + query: 'IdentityStore', + results: [ + { path: 'x.rs', line: 1, text: 'a' }, + { path: 'y.rs', line: 2, text: 'b' }, + { path: 'z.rs', line: 3, text: 'c' }, + ], + }, + '/explore/hot': { files: ['a', 'b', 'c'] }, + }), + daemonUrl: 'http://127.0.0.1:7719', + }); + const tree = await call(handle, 'codedb_tree', {}); + assert.equal(tree.result.content[0].text, 'a/\n b.rs rust 3L 1 sym\n'); + assert.equal(tree.result.isError, undefined); + const search = await call(handle, 'codedb_search', { query: 'IdentityStore', max_results: 2 }); + assert.deepEqual(JSON.parse(search.result.content[0].text).results.map((r) => r.path), ['x.rs', 'y.rs']); + const hot = await call(handle, 'codedb_hot', { limit: 1 }); + assert.deepEqual(JSON.parse(hot.result.content[0].text).files, ['a']); +}); + +test('daemon errors and an unreachable daemon surface as MCP errors naming the cause', async () => { + const handle404 = createHandler({ fetchFn: stubFetch({}), daemonUrl: 'http://127.0.0.1:7719' }); + const missing = await call(handle404, 'codedb_outline', { path: 'nope.rs' }); + assert.equal(missing.result.isError, true); + assert.match(missing.result.content[0].text, /not found/); + const down = createHandler({ + fetchFn: async () => { + throw new Error('connect ECONNREFUSED'); + }, + daemonUrl: 'http://127.0.0.1:7719', + }); + const unreachable = await call(down, 'codedb_tree', {}); + assert.equal(unreachable.result.isError, true); + assert.match(unreachable.result.content[0].text, /unreachable.*systemctl --user start codedb-/); + const badArg = await call(down, 'codedb_search', { query: 'x', regex: true }); + assert.equal(badArg.result.isError, true); + assert.match(badArg.result.content[0].text, /"regex"/); +}); From 8fb94c2a7ec5ba9b87cb7f42a462ffdd0b2762a7 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 22:45:53 -0600 Subject: [PATCH 2/3] =?UTF-8?q?fix(mcpx):=20dispatch=20bridge=20requests?= =?UTF-8?q?=20concurrently=20=E2=80=94=20no=20head-of-line=20blocking=20(P?= =?UTF-8?q?R=20#4171=20Codex=20P2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The stdio read loop awaited each daemon call, so one slow search blocked every later request in a bridge process that mcpx may share across sessions. Requests now dispatch independently and responses correlate by JSON-RPC id; the process exits only once stdin is closed and all pending calls settle. Regression test spawns the bridge against a delayed stub daemon and asserts a ping is answered before the slow search. --- bin/codedb-bridge.mjs | 34 ++++++++++++++++++++++----- bin/codedb-bridge.test.mjs | 47 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 6 deletions(-) diff --git a/bin/codedb-bridge.mjs b/bin/codedb-bridge.mjs index 0b292f0842..4b444c9c06 100644 --- a/bin/codedb-bridge.mjs +++ b/bin/codedb-bridge.mjs @@ -251,18 +251,40 @@ const main = async () => { const handle = createHandler({ fetchFn: (url) => fetch(url), daemonUrl }); const readline = await import('node:readline'); const rl = readline.createInterface({ input: process.stdin, terminal: false }); - for await (const line of rl) { + // Requests are dispatched independently, never awaited inside the read + // loop: mcpx can share one bridge process across sessions, so a slow + // daemon call must not head-of-line block unrelated calls or pings. + // Responses are correlated by their JSON-RPC id and may complete out + // of order (Codex finding on PR #4171). + let pending = 0; + let closed = false; + const maybeExit = () => { + if (closed && pending === 0) process.exit(0); + }; + rl.on('line', (line) => { const trimmed = line.trim(); - if (trimmed === '') continue; + if (trimmed === '') return; let msg; try { msg = JSON.parse(trimmed); } catch { - continue; // not JSON-RPC; codedb's own stdio server ignores malformed lines the same way + return; // not JSON-RPC; codedb's own stdio server ignores malformed lines the same way } - const response = await handle(msg); - if (response !== null) process.stdout.write(`${JSON.stringify(response)}\n`); - } + pending += 1; + handle(msg) + .then((response) => { + if (response !== null) process.stdout.write(`${JSON.stringify(response)}\n`); + }) + .catch(() => {}) // a handler failure must not kill the shared bridge; the caller times out on that one id + .finally(() => { + pending -= 1; + maybeExit(); + }); + }); + rl.on('close', () => { + closed = true; + maybeExit(); + }); }; import { pathToFileURL } from 'node:url'; diff --git a/bin/codedb-bridge.test.mjs b/bin/codedb-bridge.test.mjs index e75d728bd8..1d57cf16de 100644 --- a/bin/codedb-bridge.test.mjs +++ b/bin/codedb-bridge.test.mjs @@ -1,9 +1,15 @@ // Tests for the codedb MCP bridge (#4120). // Run: node --test bin/codedb-bridge.test.mjs import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import http from 'node:http'; +import path from 'node:path'; import test from 'node:test'; +import { fileURLToPath } from 'node:url'; import { CODEDB_TOOLS, createHandler, parseDaemonUrl, routeForTool } from './codedb-bridge.mjs'; +const binDir = path.dirname(fileURLToPath(import.meta.url)); + test('daemon URL defaults to the codedb serve origin and rejects non-origins', () => { assert.equal(parseDaemonUrl(undefined), 'http://127.0.0.1:7719'); assert.equal(parseDaemonUrl(''), 'http://127.0.0.1:7719'); @@ -88,6 +94,47 @@ test('tools/call forwards to the daemon and returns its payload', async () => { assert.deepEqual(JSON.parse(hot.result.content[0].text).files, ['a']); }); +test('a slow daemon call does not head-of-line block a later ping (PR #4171 Codex P2)', async () => { + const daemon = http.createServer((req, res) => { + const respond = () => { + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify({ query: 'x', results: [] })); + }; + if (req.url.startsWith('/explore/search')) setTimeout(respond, 1200); + else respond(); + }); + await new Promise((resolve) => daemon.listen(0, '127.0.0.1', resolve)); + const child = spawn(process.execPath, [path.join(binDir, 'codedb-bridge.mjs')], { + env: { ...process.env, CODEDB_DAEMON_URL: `http://127.0.0.1:${daemon.address().port}` }, + stdio: ['pipe', 'pipe', 'inherit'], + }); + try { + const order = []; + const done = new Promise((resolve) => { + let buf = ''; + child.stdout.on('data', (chunk) => { + buf += chunk; + for (const line of buf.split('\n')) { + if (!line.trim()) continue; + try { + order.push(JSON.parse(line).id); + } catch {} + } + buf = buf.slice(buf.lastIndexOf('\n') + 1); + if (order.length >= 2) resolve(); + }); + }); + child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'codedb_search', arguments: { query: 'x' } } })}\n`); + child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'ping' })}\n`); + await done; + assert.deepEqual(order, [2, 1], 'ping (id 2) must be answered before the slow search (id 1) completes'); + } finally { + child.stdin.end(); + child.kill(); + daemon.close(); + } +}); + test('daemon errors and an unreachable daemon surface as MCP errors naming the cause', async () => { const handle404 = createHandler({ fetchFn: stubFetch({}), daemonUrl: 'http://127.0.0.1:7719' }); const missing = await call(handle404, 'codedb_outline', { path: 'nope.rs' }); From f482cb44d06b4a05f95e93b6b688009bc450fd1f Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 22:51:43 -0600 Subject: [PATCH 3/3] fix(mcpx): flush stdout before bridge exit after stdin closes (PR #4171 Codex P2) process.exit(0) could discard pipe-queued stdout when stdin closed with a request pending, truncating the final (possibly multi-MB tree) response. Responses now settle in their write callbacks, and exit is queued behind an empty write that fires only after all prior output flushed. Regression test: stub daemon returns a ~2 MiB tree after a delay, client closes stdin immediately, full response must arrive and parse. --- bin/codedb-bridge.mjs | 25 ++++++++++++++++++------- bin/codedb-bridge.test.mjs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 7 deletions(-) diff --git a/bin/codedb-bridge.mjs b/bin/codedb-bridge.mjs index 4b444c9c06..457b62b475 100644 --- a/bin/codedb-bridge.mjs +++ b/bin/codedb-bridge.mjs @@ -259,7 +259,16 @@ const main = async () => { let pending = 0; let closed = false; const maybeExit = () => { - if (closed && pending === 0) process.exit(0); + if (!closed || pending !== 0) return; + // process.exit() discards stdout bytes still queued for a pipe, which + // truncates the final response when stdin closes mid-request (Codex + // finding on PR #4171). Queue an empty write behind everything else: + // its callback fires only once all prior output has flushed. + process.stdout.write('', () => process.exit(0)); + }; + const settle = () => { + pending -= 1; + maybeExit(); }; rl.on('line', (line) => { const trimmed = line.trim(); @@ -273,13 +282,15 @@ const main = async () => { pending += 1; handle(msg) .then((response) => { - if (response !== null) process.stdout.write(`${JSON.stringify(response)}\n`); + if (response === null) { + settle(); + return; + } + // Settle only when this response has actually flushed, so the + // exit path above can never outrun a queued write. + process.stdout.write(`${JSON.stringify(response)}\n`, settle); }) - .catch(() => {}) // a handler failure must not kill the shared bridge; the caller times out on that one id - .finally(() => { - pending -= 1; - maybeExit(); - }); + .catch(() => settle()); // a handler failure must not kill the shared bridge; the caller times out on that one id }); rl.on('close', () => { closed = true; diff --git a/bin/codedb-bridge.test.mjs b/bin/codedb-bridge.test.mjs index 1d57cf16de..57b8cd891f 100644 --- a/bin/codedb-bridge.test.mjs +++ b/bin/codedb-bridge.test.mjs @@ -135,6 +135,36 @@ test('a slow daemon call does not head-of-line block a later ping (PR #4171 Code } }); +test('closing stdin mid-request still delivers the complete final response (PR #4171 Codex P2)', async () => { + const bigTree = `root/\n${' file.rs rust 1L 0 sym\n'.repeat(80000)}`; + const daemon = http.createServer((req, res) => { + res.setHeader('content-type', 'application/json'); + if (req.url.startsWith('/explore/tree')) setTimeout(() => res.end(JSON.stringify({ tree: bigTree })), 200); + else res.end(JSON.stringify({})); + }); + await new Promise((resolve) => daemon.listen(0, '127.0.0.1', resolve)); + const child = spawn(process.execPath, [path.join(binDir, 'codedb-bridge.mjs')], { + env: { ...process.env, CODEDB_DAEMON_URL: `http://127.0.0.1:${daemon.address().port}` }, + stdio: ['pipe', 'pipe', 'inherit'], + }); + try { + let received = ''; + const exited = new Promise((resolve) => child.on('exit', resolve)); + child.stdout.on('data', (chunk) => { + received += chunk; + }); + child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'codedb_tree', arguments: {} } })}\n`); + child.stdin.end(); // close immediately, while the daemon call is still pending + await exited; + const msg = JSON.parse(received.trim()); + assert.equal(msg.id, 1); + assert.equal(msg.result.content[0].text, bigTree, 'final response must arrive complete, not truncated by process.exit'); + } finally { + child.kill(); + daemon.close(); + } +}); + test('daemon errors and an unreachable daemon surface as MCP errors naming the cause', async () => { const handle404 = createHandler({ fetchFn: stubFetch({}), daemonUrl: 'http://127.0.0.1:7719' }); const missing = await call(handle404, 'codedb_outline', { path: 'nope.rs' });