Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(chat): start the first model call without waiting for slow MCP servers

AdityaUmale847feeaa7498
diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.ts
index f44b396560..bbee914a75 100644
--- a/server/drivers/chat-mcp-tools.test.ts
+++ b/server/drivers/chat-mcp-tools.test.ts
@@ -6,7 +6,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { augmentedPath } from "../env-path.ts";
import { MESSAGE_FILE_MAX_BYTES } from "../message-file.ts";
import { Ajv2020 } from "ajv/dist/2020.js";
-import { ChatMcpClient, ChatToolSessionError, SAVED_RESULTS_FOLDER, SAVED_RESULTS_KEPT, chatToolNotices, directServers, mcpStartupMs, mountChatTools, trimmedToolsNotice, type ChatToolSession } from "./chat-mcp-tools.ts";
+import { ChatMcpClient, ChatToolSessionError, SAVED_RESULTS_FOLDER, SAVED_RESULTS_KEPT, chatToolNotices, directServers, joinLateChatTools, mcpStartupMs, mountChatTools, trimmedToolsNotice, type ChatToolDefinition, type ChatToolSession } from "./chat-mcp-tools.ts";
import { EXECUTOR_LIKE_TOOLS } from "../testing/executor-like-tools.ts";
import type { ToolScope } from "../../shared/tool-scope.ts";
import type { SendTurnInput } from "../contracts.ts";
@@ -1489,3 +1489,70 @@ describe("Chat MCP tool limit, fairly shared", () => {
} finally { await remote.close(); }
});
});
+
+describe("Chat MCP servers starting in the background", () => {
+ const slowStart = (ms: number) => `if (message.method === "initialize") { setTimeout(() => reply(message, {protocolVersion:"2024-11-05",capabilities:{tools:{}}}), ${ms}); continue; }`;
+ const ask: ChatToolDefinition = { type: "function", function: { name: "ask_user", description: "Ask", parameters: { type: "object" } } };
+ const background = async (integrations: SendTurnInput["integrations"], signal: AbortSignal) => {
+ const session = await mountChatTools(integrations, signal, false, undefined, undefined, undefined, undefined, undefined, undefined, true);
+ sessions.push(session);
+ return session;
+ };
+ const names = (session: ChatToolSession) => session.definitions.map((definition) => definition.function.name);
+ /** Joins until a server that was still starting has been taken in. */
+ const joined = async (session: ChatToolSession) => {
+ let lines: string[] | undefined;
+ await vi.waitFor(async () => { lines = await joinLateChatTools(session, [ask]); expect(lines).toBeDefined(); }, { timeout: 10_000, interval: 50 });
+ return lines;
+ };
+
+ it("starts the turn once the agents server is up, and lists a slow server's tools when it joins", async () => {
+ const agents = fixture();
+ const slow = fixture(slowStart(1_500));
+ const startedAt = Date.now();
+ const session = await background({ agents: agents.server, custom: { slow: slow.server } }, agents.controller.signal);
+ expect(Date.now() - startedAt).toBeLessThan(1_500);
+ session.definitions.push(ask);
+ expect(names(session)).toEqual(["agents_write", "ask_user"]);
+ expect(await joined(session)).toEqual([]);
+ expect(names(session)).toEqual(["agents_write", "slow_write", "ask_user"]);
+ await expect(session.execute("slow_write", { value: "late" }, agents.controller.signal)).resolves.toMatchObject({ ok: true, text: "recorded:late" });
+ expect(await session.join()).toBeUndefined();
+ });
+
+ it("says when a server that was still starting is skipped", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const agents = fixture();
+ const late = fixture(`if (message.method === "tools/list") { setTimeout(() => reply(message, {tools:"invalid"}), 800); continue; }`);
+ const session = await background({ agents: agents.server, custom: { late: late.server } }, agents.controller.signal);
+ expect(session.skipped).toEqual([]);
+ expect(await joined(session)).toEqual([expect.stringMatching(/^MCP server "late" was skipped for this turn: .*invalid result/)]);
+ expect(names(session)).toEqual(["agents_write"]);
+ warn.mockRestore();
+ });
+
+ it("keeps a listed tool's name when a server joining later would have taken it", async () => {
+ const agents = fixture(slowStart(300));
+ const builtIn = fixture(slowStart(1_000));
+ const configured = fixture();
+ const session = await background({ agents: agents.server, data: builtIn.server, custom: { Data: configured.server } }, agents.controller.signal);
+ expect(names(session)).toEqual(["agents_write", "data_write"]);
+ await joined(session);
+ expect(names(session)).toEqual(["agents_write", "data_write_2", "data_write"]);
+ await session.execute("data_write", { value: "same tool" }, agents.controller.signal);
+ expect(configured.read().calls.some((call) => call.method === "tools/call")).toBe(true);
+ expect(builtIn.read().calls.some((call) => call.method === "tools/call")).toBe(false);
+ });
+
+ it("waits for every server without the agents server, or when not started in the background", async () => {
+ for (const mount of [
+ (f: ReturnType<typeof fixture>) => background({ custom: { slow: f.server } }, f.controller.signal),
+ (f: ReturnType<typeof fixture>) => mountChatTools({ agents: fixture().server, custom: { slow: f.server } }, f.controller.signal).then((session) => { sessions.push(session); return session; }),
+ ]) {
+ const slow = fixture(slowStart(300));
+ const session = await mount(slow);
+ expect(names(session)).toContain("slow_write");
+ expect(await session.join()).toBeUndefined();
+ }
+ });
+});
diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.ts
index d9a7865f8f..6f70d72eb3 100644
--- a/server/drivers/chat-mcp-tools.ts
+++ b/server/drivers/chat-mcp-tools.ts
@@ -52,6 +52,9 @@ export interface ChatToolSession {
budget: ToolBudget;
/** Lists the turn's tools again within `limit`, after a provider refused that many; started servers keep running. */
refit(limit: number): Promise<void>;
+ /** Mounted with `background`: lists the turn's tools again with the servers that finished starting since the last call.
+ * The lines say which were skipped and what the tool limit did; undefined when no server finished starting. */
+ join(): Promise<string[] | undefined>;
validate(name: string, args: unknown): void;
/** Directory reads and OpenMausBot's own agents server need no card; call_tool shows the tool it runs. */
view(name: string, args: Record<string, unknown>): ChatToolCallView;
@@ -338,11 +341,24 @@ export async function refitChatTools(session: ChatToolSession, error: unknown, k
return toolLimitNotices(session);
}
+/** Between rounds, lists the tools of the servers that finished starting in the background, the runtime's own `runtime`
+ * definitions kept after them. The lines say what changed; undefined when nothing did. */
+export async function joinLateChatTools(session: ChatToolSession, runtime: readonly ChatToolDefinition[]): Promise<string[] | undefined> {
+ const kept = session.definitions.filter((definition) => runtime.includes(definition));
+ const lines = await session.join();
+ if (lines !== undefined) session.definitions.push(...kept);
+ return lines;
+}
+
+function skippedServerNotice({ server, reason }: SkippedChatMcpServer): string {
+ return `MCP server "${server}" was skipped for this turn: ${reason}`;
+}
+
/** What the person hears about a turn's MCP servers before the model runs, one line each. */
export function chatToolNotices(session: Pick<ChatToolSession, "skipped" | "trimmed" | "budget"> & Partial<Pick<ChatToolSession, "merged">>): string[] {
return [
...(session.merged ?? []).map(mergedServersNotice),
- ...session.skipped.map(({ server, reason }) => `MCP server "${server}" was skipped for this turn: ${reason}`),
+ ...session.skipped.map(skippedServerNotice),
...toolLimitNotices(session),
];
}
@@ -492,9 +508,12 @@ export function directServers(servers: ReadonlyArray<{ name: string; tools: numb
/** Under `schemaProfile` the model reads each tool's schema fitted to its provider; calls are still checked against the full one.
* A tool result over 50KB is saved whole in `resultFolder`, the bot's working folder, after `scrub` masks secrets (see savedOrBounded).
- * `toolLimit` is the most tools the provider takes in one request, ask_user included; null when it takes any number. */
+ * `toolLimit` is the most tools the provider takes in one request, ask_user included; null when it takes any number.
+ * With `background`, setup waits only for the agents server, a computer and the built-in browser; the rest keep starting
+ * and are listed by `join` once they have. Without the agents server, setup waits for every one. */
export async function mountChatTools(integrations: SendTurnInput["integrations"], signal: AbortSignal, computerUse = false, toolScope?: ToolScope, callTimeoutMs: number = DEFAULT_CALL_MS,
- schemaProfile?: ToolSchemaProfile, resultFolder?: string, scrub: (text: string) => string = redactSecretsInText, toolLimit: number | null = CHAT_TOOL_LIMIT): Promise<ChatToolSession> {
+ schemaProfile?: ToolSchemaProfile, resultFolder?: string, scrub: (text: string) => string = redactSecretsInText, toolLimit: number | null = CHAT_TOOL_LIMIT,
+ background = false): Promise<ChatToolSession> {
const parsed = parseToolScope(toolScope);
if (!parsed.ok) throw new Error(parsed.error);
const scope = parsed.scope;
@@ -565,6 +584,9 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]
const directoryNames = new Map<string, string>();
let directory: ToolDirectory | undefined;
const budget: ToolBudget = { limit: toolLimit, listed: 0, servers: [] };
+ // A tool keeps the name it was first listed under, so a server that joins later can't take it over.
+ const assigned = new Map<ChatMcpClient, Map<string, string>>();
+ const reserved = new Set<string>();
const register = (origin: ToolOrigin, tools: readonly CheckedTool[]) => {
const staged: Array<{ tool: RegisteredTool; definition: ChatToolDefinition }> = [];
for (const { tool, schema, check } of tools) {
@@ -579,13 +601,17 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]
}
const description = (typeof listed.description === "string" ? listed.description : "Configured MCP tool") +
(Object.keys(constraints).length ? " Additional argument constraints (validated before execution): " + JSON.stringify(constraints) : "");
- const name = uniqueName(chatToolName(origin.server, tool.name), (candidate) => registered.has(candidate) || staged.some((entry) => entry.definition.function.name === candidate));
+ const name = assigned.get(origin.client)?.get(tool.name)
+ ?? uniqueName(chatToolName(origin.server, tool.name), (candidate) => reserved.has(candidate) || registered.has(candidate) || staged.some((entry) => entry.definition.function.name === candidate));
staged.push({ tool: { ...origin, name: tool.name, schema }, definition: { type: "function", function: { name, description, parameters } } });
}
if (Buffer.byteLength(JSON.stringify([...definitions, ...staged.map((entry) => entry.definition)])) > CATALOG_BYTES) throw new Error("MCP tool catalog exceeds the 1MB limit");
for (const { tool, definition } of staged) {
registered.set(definition.function.name, tool);
definitions.push(definition);
+ const names = assigned.get(tool.client) ?? new Map<string, string>();
+ assigned.set(tool.client, names.set(tool.name, definition.function.name));
+ reserved.add(definition.function.name);
}
// Unlisted, so a call by an alias in an earlier tool call reaches the agents server, which runs it as its action
// tool; the server holds it to that tool's full schema.
@@ -661,10 +687,35 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]
}
budget.listed = definitions.length;
};
+ type Mounted = { origin: ToolOrigin; tools: Awaited<ReturnType<ChatMcpClient["tools"]>> };
+ const outcomes: Array<PromiseSettledResult<Mounted> | undefined> = [];
+ const consumed = new Set<number>();
+ /** Takes in, in config order, the servers that finished starting since the last call; true when any did. */
+ const absorb = async (): Promise<boolean> => {
+ let any = false;
+ for (const [index, mount] of outcomes.entries()) {
+ if (!mount || consumed.has(index)) continue;
+ if (signal.aborted || closed) throw aborted();
+ consumed.add(index);
+ any = true;
+ const name = servers[index]![0];
+ if (mount.status === "rejected") {
+ if (index >= builtIns || (OPTIONAL_BUILT_INS.has(name) && !mustHave(servers[index]![1]))) { await skip(name, mount.reason, startedAt[index]); continue; }
+ throw new Error(`MCP server "${name}" didn't start: ${mount.reason instanceof Error ? mount.reason.message : "no reason given"}`);
+ }
+ if (index < builtIns) {
+ offeredTools.push({ origin: mount.value.origin, tools: checkedTools(mount.value.tools, mount.value.origin.server) });
+ continue;
+ }
+ try { configured.push({ origin: mount.value.origin, tools: checkedTools(mount.value.tools, mount.value.origin.server) }); }
+ catch (error) { await skip(mount.value.origin.server, error, mount.value.origin.client); }
+ }
+ return any;
+ };
try {
if (signal.aborted) throw aborted();
// Concurrent starts, consumed in config order so names and collision suffixes stay stable.
- const mounts = await Promise.allSettled(servers.map(async ([name, descriptor], index) => {
+ const mounts = servers.map(async ([name, descriptor], index): Promise<Mounted> => {
if (signal.aborted || closed) throw aborted();
const client = new ChatMcpClient(descriptor, computerUse, index >= builtIns);
clients.push(client);
@@ -682,21 +733,20 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]
const origin: ToolOrigin = { client, server: name, launch, builtInBrowser: descriptor === integrations?.browser, agents: descriptor === agentsServer,
hostComputer: descriptor === integrations?.localComputer && integrations?.localComputer?.scope === "local-computer", required: index < builtIns && mustHave(descriptor), searched: searchable.has(name) };
return { origin, tools };
- }));
- for (const [index, mount] of mounts.entries()) {
- if (signal.aborted || closed) throw aborted();
- const name = servers[index]![0];
- if (mount.status === "rejected") {
- if (index >= builtIns || (OPTIONAL_BUILT_INS.has(name) && !mustHave(servers[index]![1]))) { await skip(name, mount.reason, startedAt[index]); continue; }
- throw new Error(`MCP server "${name}" didn't start: ${mount.reason instanceof Error ? mount.reason.message : "no reason given"}`);
- }
- if (index < builtIns) {
- offeredTools.push({ origin: mount.value.origin, tools: checkedTools(mount.value.tools, mount.value.origin.server) });
- continue;
- }
- try { configured.push({ origin: mount.value.origin, tools: checkedTools(mount.value.tools, mount.value.origin.server) }); }
- catch (error) { await skip(mount.value.origin.server, error, mount.value.origin.client); }
- }
+ });
+ const settled = mounts.map((mount, index) => mount.then((value) => { outcomes[index] = { status: "fulfilled", value }; },
+ (reason: unknown) => { outcomes[index] = { status: "rejected", reason }; }));
+ // Waited for in the background too: what the turn can't run without, the computer and browser a computer-use turn
+ // acts through from its first step, and a server sharing its name with another, whose tools' names depend on which
+ // of the two is listed first.
+ const waited = (index: number) => {
+ const [name, descriptor] = servers[index]!;
+ return (index < builtIns && (mustHave(descriptor) || !OPTIONAL_BUILT_INS.has(name) || descriptor === integrations?.localComputer || descriptor === integrations?.browser))
+ || servers.filter(([other]) => other === name).length > 1;
+ };
+ const waitAll = !background || !servers.some(([, descriptor]) => descriptor === agentsServer);
+ await Promise.all(settled.filter((_, index) => waitAll || waited(index)));
+ await absorb();
await layout(toolLimit);
if (signal.aborted || closed) throw aborted();
} catch (error) { await close(); throw error; }
@@ -789,6 +839,15 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]
if (closed || signal.aborted) throw new ChatToolSessionError("MCP session closed");
await layout(limit);
},
+ async join() {
+ if (closed || signal.aborted) return undefined;
+ const skippedBefore = skipped.length;
+ const limitBefore = toolLimitNotices({ trimmed, budget });
+ if (!await absorb()) return undefined;
+ await layout(budget.limit);
+ const limitAfter = toolLimitNotices({ trimmed, budget });
+ return [...skipped.slice(skippedBefore).map(skippedServerNotice), ...(limitAfter.join("\n") === limitBefore.join("\n") ? [] : limitAfter)];
+ },
async execute(name, args, callSignal) {
validate(name, args);
if (callSignal.aborted) { await close(); throw aborted(); }
diff --git a/server/drivers/openai-chat-tools.test.ts b/server/drivers/openai-chat-tools.test.ts
index b085a025a0..568b6bc27e 100644
--- a/server/drivers/openai-chat-tools.test.ts
+++ b/server/drivers/openai-chat-tools.test.ts
@@ -1505,20 +1505,37 @@ describe("a configured MCP server that cannot mount", () => {
});
describe("a turn with the person's Windows computer, the built-in browser and the agents server", () => {
- function catalog(names: readonly string[]) {
- const { dir, server } = catalogServer(names);
+ function catalog(names: readonly string[], startMs = 0) {
+ const { dir, server } = catalogServer(names, startMs);
cleanups.push(() => removeTempDir(dir));
return server;
}
const integrations = (agents: number, more: SendTurnInput["integrations"] = {}): SendTurnInput["integrations"] => ({
localComputer: { ...catalog(CUA_DRIVER_WINDOWS_TOOLS), scope: "local-computer" },
browser: catalog(syntheticToolNames("agent_browser", 32)),
- agents: catalog(syntheticToolNames("agent", agents)),
+ // Started last, so the servers that start in the background are listed from the first request.
+ agents: catalog(syntheticToolNames("agent", agents), 1_500),
composio: catalog(syntheticToolNames("router", 7)),
data: catalog(syntheticToolNames("table", 5)),
...more,
});
+ it("sends the first request without waiting for a slow server, and lists its tools from the next round", async () => {
+ let firstAt = 0;
+ const f = await fixture(async (_body, response, round) => {
+ if (round > 1) return answer(response);
+ firstAt = Date.now();
+ // Long enough for the slow server to have started before the next round.
+ await new Promise((resolve) => setTimeout(resolve, 2_000));
+ sse(response, [chunk({ tool_calls: [toolCall("agents_agent_1", "{}")] }, "tool_calls")]);
+ });
+ const startedAt = Date.now();
+ await f.start({ integrations: { agents: catalog(syntheticToolNames("agent", 1)), custom: { notes: catalog(["note"], 1_500) } } });
+ expect(await f.completed()).toMatchObject({ ok: true });
+ expect(firstAt - startedAt).toBeLessThan(1_000);
+ expect(f.requests.map((request) => request.tools!.map((tool) => tool.function.name))).toEqual([["agents_agent_1", "ask_user"], ["agents_agent_1", "notes_note", "ask_user"]]);
+ });
+
it("sends at most 128 tools, ask_user and every agents tool among them", async () => {
const f = await fixture((_body, response) => answer(response));
await f.start({ integrations: integrations(42) });
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index 86c6e718ea..073757cbf1 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -14,7 +14,7 @@ import { ASK_USER_TOOL, ASK_USER_TOOL_DEFINITION, askQuestionSummary, parseAskQu
import { allowsTool, parseToolScope } from "../../shared/tool-scope.ts";
import { redactSecretsInText } from "../redact.ts";
import { toolDetailPreview } from "../tool-summary.ts";
-import { ChatToolSessionError, chatToolNotices, mountChatTools, refitChatTools, type ChatToolDefinition, type ChatToolSession, type ChatToolResult } from "./chat-mcp-tools.ts";
+import { ChatToolSessionError, chatToolNotices, joinLateChatTools, mountChatTools, refitChatTools, type ChatToolDefinition, type ChatToolSession, type ChatToolResult } from "./chat-mcp-tools.ts";
import { noteToolBudget } from "../tool-budgets.ts";
import { chatToolLimitFor, chatToolLimitKey } from "../tool-count-limit.ts";
import { assertImageTransport, chatImageBudget, chatToolImages, chatUserContent, type ChatContentPart } from "./chat-images.ts";
@@ -609,11 +609,10 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const scope = parsed.scope;
const toolsOff = options.tools === false || options.toolUse?.(model) === false;
tools = await mountChatTools(toolsOff ? undefined : turn.integrations, abort.signal, options.computerUse, scope, turn.mcpCallTimeoutMs,
- toolSchemaProfileFor({ url: options.apiUrl, model }), turn.cwd ?? turn.toolResultFolder, safeText, chatToolLimitFor(options.apiUrl, model));
+ toolSchemaProfileFor({ url: options.apiUrl, model }), turn.cwd ?? turn.toolResultFolder, safeText, chatToolLimitFor(options.apiUrl, model), true);
noteToolBudget(turn.botId, tools.budget);
for (const message of chatToolNotices(tools)) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });
const questionAllowed = !toolsOff && allowsTool(scope, { kind: "native", name: ASK_USER_TOOL });
- let optionalQuestionOnly = questionAllowed && tools.definitions.length === 0;
// An MCP server squatting ask_user cannot shadow it (dispatch intercepts the name); skip its definition.
if (questionAllowed && !tools.definitions.some((definition) => definition.function.name === ASK_USER_TOOL)) {
tools.definitions.push(ASK_USER_TOOL_DEFINITION);
@@ -627,6 +626,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
deliveredAsides.push(...unread);
}
turnEntry.ending = round === MAX_CHAT_ROUNDS - 1;
+ // Servers still starting when the turn began join once they have, never after the tools were dropped (none left while ask_user is allowed).
+ if (!questionAllowed || tools.definitions.length) for (const message of await joinLateChatTools(tools, [ASK_USER_TOOL_DEFINITION]) ?? []) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });
native("out", options.nativeLog.outgoing(turn, messages, model, tools.definitions));
let attempt = 0;
let resized = false;
@@ -712,9 +713,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
if (!abort.signal.aborted) throw new ChatProtocolError(refusedToolCallFailure(error, seenCalls.size > 0));
}
// A structured parameter rejection executed nothing; never downgrade mounted tools or a handled call.
- if (optionalQuestionOnly && round === 0 && !streamed && !seenCalls.size && !abort.signal.aborted &&
+ if (questionAllowed && round === 0 && tools.definitions.length && tools.definitions.every((definition) => definition === ASK_USER_TOOL_DEFINITION) && !streamed && !seenCalls.size && !abort.signal.aborted &&
error instanceof UnsupportedChatToolsError && verdict.reason === "invalid_request") {
- optionalQuestionOnly = false;
tools.definitions.length = 0;
continue;
}
diff --git a/server/testing/cua-driver-tools.ts b/server/testing/cua-driver-tools.ts
index 518bc61e12..579c5c84a8 100644
--- a/server/testing/cua-driver-tools.ts
+++ b/server/testing/cua-driver-tools.ts
@@ -46,16 +46,17 @@ const names = JSON.parse(process.env.CATALOG_TOOLS);
const reply = (id, result) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result }) + "\\n");
createInterface({ input: process.stdin }).on("line", (line) => {
const request = JSON.parse(line);
- if (request.method === "initialize") reply(request.id, { protocolVersion: "2024-11-05", capabilities: { tools: {} } });
+ if (request.method === "initialize") setTimeout(() => reply(request.id, { protocolVersion: "2024-11-05", capabilities: { tools: {} } }), Number(process.env.CATALOG_START_MS ?? 0));
else if (request.method === "tools/list") reply(request.id, { tools: names.map((name) => ({ name, description: "Synthetic " + name, inputSchema: { type: "object" } })) });
else if (request.id !== undefined) reply(request.id, { content: [{ type: "text", text: "ran " + request.params?.name }] });
});
`;
-/** A stdio MCP server, as a turn's integrations take it, that lists exactly `names`. Remove `dir` when done. */
-export function catalogServer(names: readonly string[]): { dir: string; server: { command: string; args: string[]; env: Record<string, string> } } {
+/** A stdio MCP server, as a turn's integrations take it, that lists exactly `names`, `startMs` after it is asked to start.
+ * Remove `dir` when done. */
+export function catalogServer(names: readonly string[], startMs = 0): { dir: string; server: { command: string; args: string[]; env: Record<string, string> } } {
const dir = mkdtempSync(join(tmpdir(), "omb-catalog-mcp-"));
const script = join(dir, "catalog.mjs");
writeFileSync(script, CATALOG_SERVER);
- return { dir, server: { command: process.execPath, args: [script], env: { CATALOG_TOOLS: JSON.stringify(names) } } };
+ return { dir, server: { command: process.execPath, args: [script], env: { CATALOG_TOOLS: JSON.stringify(names), CATALOG_START_MS: String(startMs) } } };
}