fix(mcp-bridge): wait for backends before listing or running tools (#5238)

The bridge opens its port, then starts its stdio backends. A tools/list that
arrived in between got only the built-in tools, and MCP clients cache the
list: on a cold Cloud Run instance the chat UI offered the model 3 tools
instead of 185 for a minute, and every ruflo/ruvector call failed as
"Unknown MCP function".

tools/list on /mcp and /mcp/<group>, and executeTool, now wait for backend
start-up, capped by MCP_BACKEND_READY_WAIT_MS (default 120s) so one hung
backend cannot hold requests forever.

test-tool-policy.mjs P8 starts both bridges with a slow stub backend and
lists tools before it is up; it fails on main and passes here. The ADR-166
lock allows the one await line ahead of the permission check, and still
fails if that check is removed.

Co-authored-by: r <r@x>
This commit is contained in:
rUvandr authored and GitHub committed 2026-12-02 12:40:41 -05:00
1 parent 987efee9ee
commit c61201eb94
5 files changed
+69 -3

No files matched your search

+17 -1
View File
@@ -298,6 +298,18 @@ const BACKEND_DEFS = [
const mcpBackends = new Map();
let allBackendTools = []; // all tools from all backends (pre-filter)
// Backends start after the port opens, so a request that arrives first would
// see only the built-in tools, and MCP clients cache that short list. Tool
// listing and execution wait for start-up, capped so one hung backend cannot
// hold requests forever.
let backendsReady = Promise.resolve();
const BACKEND_READY_WAIT_MS = Number(process.env.MCP_BACKEND_READY_WAIT_MS) || 120000;
function waitForBackends() {
let timer;
const cap = new Promise((resolve) => { timer = setTimeout(resolve, BACKEND_READY_WAIT_MS); });
return Promise.race([backendsReady, cap]).finally(() => clearTimeout(timer));
}
function isBackendNeeded(backendDef) {
return backendDef.groups.some(g => TOOL_GROUPS[g]?.enabled);
}
@@ -812,6 +824,7 @@ function isToolPermitted(name) {
}
async function executeTool(name, args) {
await waitForBackends();
// Deny every tool the capability policy does not allow, on every path.
// Root cause of ADR-166 V2/V3; the policy replaced a name-pattern check.
if (!isToolPermitted(name)) {
@@ -1011,6 +1024,7 @@ function createMcpHandler(groupName) {
},
});
case "tools/list": {
await waitForBackends();
const tools = getToolsForGroup(groupName);
return res.json({ jsonrpc: "2.0", id, result: { tools } });
}
@@ -1069,6 +1083,7 @@ app.post("/mcp", asyncRoute(async (req, res) => {
},
});
case "tools/list": {
await waitForBackends();
const activeTools = getActiveTools();
return res.json({ jsonrpc: "2.0", id, result: { tools: [...BUILTIN_TOOLS, ...activeTools] } });
}
@@ -1852,7 +1867,8 @@ async function main() {
const anyBackendNeeded = BACKEND_DEFS.some(isBackendNeeded);
if (anyBackendNeeded) {
console.log("Initializing MCP backends...");
await initBackends();
backendsReady = initBackends();
await backendsReady;
}
}
+1 -1
View File
@@ -55,7 +55,7 @@ const CHECKS = [
},
{
id: "5. capability-gate-server-side",
rx: /import\s*\{\s*createToolPolicy\s*\}\s*from\s*["']\.\/tool-policy\.js["'][\s\S]*?if \(!toolPolicy\.allows\(backendName, t\._originalName\)\) continue;[\s\S]*?async function executeTool\(name, args\) \{\s*\/\/[^\n]*\n\s*\/\/[^\n]*\n\s*if \(!isToolPermitted\(name\)\) \{[\s\S]*?TOOL_DISABLED/,
rx: /import\s*\{\s*createToolPolicy\s*\}\s*from\s*["']\.\/tool-policy\.js["'][\s\S]*?if \(!toolPolicy\.allows\(backendName, t\._originalName\)\) continue;[\s\S]*?async function executeTool\(name, args\) \{\s*(?:await waitForBackends\(\);\s*)?\/\/[^\n]*\n\s*\/\/[^\n]*\n\s*if \(!isToolPermitted\(name\)\) \{[\s\S]*?TOOL_DISABLED/,
hint: "executeTool must refuse, as its first step, any tool the capability policy does not allow, and getActiveTools must filter by it (Phase 1d + 2a)",
},
{
@@ -27,6 +27,9 @@ createInterface({ input: process.stdin, terminal: false }).on("line", (line) =>
let msg;
try { msg = JSON.parse(line); } catch { return; }
if (msg.method === "initialize") {
// STUB_INIT_DELAY_MS simulates a backend that is slow to start.
const delay = Number(process.env.STUB_INIT_DELAY_MS) || 0;
if (delay) return void setTimeout(() => reply(msg.id, { protocolVersion: "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: `stub-${backend}`, version: "0" } }), delay);
reply(msg.id, { protocolVersion: "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: `stub-${backend}`, version: "0" } });
} else if (msg.method === "tools/list") {
reply(msg.id, { tools: TOOLS[backend].map((name) => ({ name, description: `stub ${name}`, inputSchema: { type: "object", properties: {} } })) });
+31
View File
@@ -16,6 +16,8 @@
* P6. nothing else reached any backend
* P7. MCP_ENABLE_TERMINAL=true still lets an operator opt into shell tools,
* while unknown and unreviewed tools stay hidden
* P8. a tools/list that arrives while backends are still starting waits for
* them instead of returning only the built-in tools
*
* node test-tool-policy.mjs
*/
@@ -177,6 +179,34 @@ async function terminalOptIn(entry, tag) {
}
}
async function slowBackendStart(entry, tag) {
const port = 20000 + Math.floor(Math.random() * 10000);
const stubLog = path.join(work, `${tag}-backend.log`);
fs.writeFileSync(stubLog, "");
const child = spawn(process.execPath, [entry], {
env: {
...process.env,
PATH: `${bin}${path.delimiter}${process.env.PATH}`,
PORT: String(port), MCP_BIND_HOST: "127.0.0.1", MCP_AUTH_TOKEN: TOKEN,
STUB_LOG: stubLog, STUB_INIT_DELAY_MS: "3000",
},
stdio: ["ignore", "ignore", "ignore"],
});
try {
const deadline = Date.now() + 10000;
let up = false;
while (!up && Date.now() < deadline) {
try { up = (await fetch(`http://127.0.0.1:${port}/health`)).ok; } catch { await sleep(50); }
}
assert(up, "P8. bridge answers before its backends finish starting");
const [all, group] = await Promise.all([listNames(port, "/mcp"), listNames(port, "/mcp/agents")]);
assert(all.includes("ruflo__task_list") && all.includes("ruvector__hooks_stats"), "P8. early /mcp tools/list waits for backends");
assert(group.includes("ruflo__task_list"), "P8. early /mcp/agents tools/list waits for backends");
} finally {
child.kill("SIGKILL");
}
}
console.log("\n# tool-policy.js copies");
assert(fs.readFileSync(path.join(HERE, "tool-policy.js"), "utf8") === fs.readFileSync(path.join(RUVOCAL, "tool-policy.js"), "utf8"),
"P1. both bridges ship the same tool-policy.js");
@@ -185,6 +215,7 @@ for (const [i, { label, entry }] of BRIDGES.entries()) {
console.log(`\n# ${label}`);
await defaultPolicy(entry, `b${i}-default`);
await terminalOptIn(entry, `b${i}-terminal`);
await slowBackendStart(entry, `b${i}-slow`);
}
fs.rmSync(work, { recursive: true, force: true });
+17 -1
View File
@@ -303,6 +303,18 @@ const BACKEND_DEFS = [
const mcpBackends = new Map();
let allBackendTools = []; // all tools from all backends (pre-filter)
// Backends start after the port opens, so a request that arrives first would
// see only the built-in tools, and MCP clients cache that short list. Tool
// listing and execution wait for start-up, capped so one hung backend cannot
// hold requests forever.
let backendsReady = Promise.resolve();
const BACKEND_READY_WAIT_MS = Number(process.env.MCP_BACKEND_READY_WAIT_MS) || 120000;
function waitForBackends() {
let timer;
const cap = new Promise((resolve) => { timer = setTimeout(resolve, BACKEND_READY_WAIT_MS); });
return Promise.race([backendsReady, cap]).finally(() => clearTimeout(timer));
}
function isBackendNeeded(backendDef) {
return backendDef.groups.some(g => TOOL_GROUPS[g]?.enabled);
}
@@ -983,6 +995,7 @@ function isToolPermitted(name) {
}
async function executeTool(name, args) {
await waitForBackends();
// Deny every tool the capability policy does not allow, on every path.
// Root cause of ADR-166 V2/V3; the policy replaced a name-pattern check.
if (!isToolPermitted(name)) {
@@ -1191,6 +1204,7 @@ function createMcpHandler(groupName) {
},
});
case "tools/list": {
await waitForBackends();
const tools = getToolsForGroup(groupName);
return res.json({ jsonrpc: "2.0", id, result: { tools } });
}
@@ -1250,6 +1264,7 @@ app.post("/mcp", asyncRoute(async (req, res) => {
},
});
case "tools/list": {
await waitForBackends();
const activeTools = getActiveTools();
return res.json({ jsonrpc: "2.0", id, result: { tools: [...BUILTIN_TOOLS, ...activeTools] } });
}
@@ -2067,7 +2082,8 @@ async function main() {
const anyBackendNeeded = BACKEND_DEFS.some(isBackendNeeded);
if (anyBackendNeeded) {
console.log("Initializing MCP backends...");
await initBackends();
backendsReady = initBackends();
await backendsReady;
}
}