Skip to content

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

Give npx/uvx MCP servers their start-check time in openai-compat turns

AdityaUmaled92aa550c2b5
diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.ts
index 90d5390219..78fa76ac13 100644
--- a/server/drivers/chat-mcp-tools.test.ts
+++ b/server/drivers/chat-mcp-tools.test.ts
@@ -1191,6 +1191,57 @@ describe("Chat MCP startup budgets", () => {
} finally { vi.useRealTimers(); }
});
+ /** A configured server named "npx" (a link to the fixture) that lists its tools only once the test says so, like
+ * "npx -y <package>" still checking the registry. */
+ function slowNpx() {
+ const f = fixture(`if (message.method === "tools/list") { const wait = setInterval(() => { if (!existsSync(receipt + ".go")) return; clearInterval(wait);
+ reply(message, {tools:[{name:"write",description:"Fixture write",inputSchema:schema}]}); }, 20); continue; }`);
+ const npx = join(f.dir, "npx");
+ symlinkSync(f.server.command, npx);
+ const listed = () => { try { return f.read().calls.some((call) => call.method === "tools/list"); } catch { return false; } };
+ return { ...f, server: { ...f.server, command: npx }, listed, go: () => writeFileSync(`${f.receipt}.go`, "") };
+ }
+
+ it("lets a configured server started through npx join in the background past the eight seconds, as long as its start check", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ try {
+ const agents = fixture();
+ const npx = slowNpx();
+ const mounting = watch(mountChatTools({ agents: agents.server, custom: { gitlab: npx.server } }, npx.controller.signal, false,
+ undefined, undefined, undefined, undefined, undefined, undefined, { background: true }));
+ await untilReal(() => mounting.done);
+ expect(mounting.error).toBeUndefined();
+ const session = mounting.value!;
+ sessions.push(session);
+ await untilReal(npx.listed);
+ await vi.advanceTimersByTimeAsync(17_000);
+ npx.go();
+ let lines: string[] | undefined;
+ const started = Date.now();
+ while (!lines && Date.now() - started < 15_000) {
+ lines = await joinLateChatTools(session, []);
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+ expect(lines).toEqual([]);
+ expect(session.skipped).toEqual([]);
+ expect(session.definitions.map((definition) => definition.function.name)).toEqual(["agents_write", "gitlab_write"]);
+ } finally { vi.useRealTimers(); }
+ });
+
+ it("still gives a configured server started through npx 8 seconds when the turn waits for every server", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ try {
+ const npx = slowNpx();
+ const mounting = watch(mountChatTools({ custom: { gitlab: npx.server } }, npx.controller.signal));
+ await untilReal(npx.listed);
+ await vi.advanceTimersByTimeAsync(mcpStartupMs(process.env, process.platform, false) + 100);
+ await settleWithin(1_000, () => mounting.done);
+ expect(mounting.error).toBeUndefined();
+ sessions.push(mounting.value!);
+ expect(mounting.value!.skipped).toEqual([{ server: "gitlab", reason: expect.stringMatching(/timed out/) }]);
+ } finally { vi.useRealTimers(); }
+ });
+
it("still gives a configured command server 8 seconds, on Windows too", async () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
try {
diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.ts
index a751745f8e..6f030a8cf2 100644
--- a/server/drivers/chat-mcp-tools.ts
+++ b/server/drivers/chat-mcp-tools.ts
@@ -20,6 +20,7 @@ import { CALL_TOOL, DESCRIBE_TOOL, SEARCH_TOOL, ToolDirectory, directoryCallTarg
import { AppObserver, modelVisible, withUiExtension } from "../mcp-app-observer.ts";
import { appMountFor, mcpStdioServer } from "../mcp-gate-config.ts";
import { REMOTE_MCP_STARTUP_MS, remoteMcpSpec } from "../mcp-http.ts";
+import { startCheckTimeout } from "../mcp-start-time.ts";
import { compileToolSchema, schemaProblems, serverToolValidator, type ServerToolCheck } from "../mcp-schema-validator.ts";
import { fitToolList, withoutDanglingReferences } from "../mcp-tool-schema.ts";
import { listsComputerTool } from "../computer-tool-list.ts";
@@ -766,6 +767,14 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]
};
try {
if (signal.aborted) throw aborted();
+ // 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 the order.
+ 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 = !options.background || !servers.some(([, descriptor]) => descriptor === agentsServer);
// Concurrent starts, consumed in config order so names and collision suffixes stay stable.
const mounts = servers.map(async ([name, descriptor], index): Promise<Mounted> => {
if (signal.aborted || closed) throw aborted();
@@ -781,7 +790,10 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]
const host: HostComputerStart | undefined = hostComputer
? await startHostComputer(hostComputerKey(descriptor), (record) => client.tools(signal, record, hostComputerMs), include, { quickMs: Math.min(startupMs, HOST_COMPUTER_QUICK_MS), firstMs: startupMs }, signal)
: undefined;
- const budgetMs = searchable.has(name) ? REMOTE_MCP_STARTUP_MS : index < builtIns ? (descriptor === agentsServer ? agentsMs : startupMs) : configuredStartupMs;
+ // A configured server joining in the background through a package runner gets as long as its start check gave it.
+ const joinsLater = !waitAll && !waited(index);
+ const budgetMs = searchable.has(name) ? REMOTE_MCP_STARTUP_MS : index < builtIns ? (descriptor === agentsServer ? agentsMs : startupMs)
+ : Math.max(configuredStartupMs, (joinsLater && startCheckTimeout(descriptor.command)) || 0);
const tools = host ? (host.state === "listed" || host.state === "pending" ? host.tools : []) : await client.tools(signal, include, budgetMs, observers.get(name));
if (!tools.length && scope === undefined && descriptor === integrations?.localComputer && (!host || host.state === "listed")) throw new Error("The Local VM listed no tools");
// Harness mounts are known by descriptor, never by a name a configured server could claim. A grant
@@ -793,14 +805,6 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]
});
const settled = mounts.map((mount, index) => mount.then((value) => { outcomes[index] = { status: "fulfilled", value }; },
(reason: unknown) => { outcomes[index] = { status: "rejected", reason }; }).then(() => options.onSettled?.(servers[index]![0])));
- // 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 the order.
- 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 = !options.background || !servers.some(([, descriptor]) => descriptor === agentsServer);
await Promise.all(settled.filter((_, index) => waitAll || waited(index)));
await absorb();
await layout(toolLimit);
diff --git a/server/host/mcp-servers-host.test.ts b/server/host/mcp-servers-host.test.ts
index 3b9abd9375..d270194aab 100644
--- a/server/host/mcp-servers-host.test.ts
+++ b/server/host/mcp-servers-host.test.ts
@@ -10,7 +10,8 @@ import { McpOAuthManager } from "../mcp-oauth.ts";
import { providerToolAllowKey } from "../provider-tool-allow.ts";
import { VaultStore } from "../vault-store.ts";
import { createMcpKeys } from "../vault/mcp-keys.ts";
-import { claimedNotice, createMcpServersHost, startCheckTimeout } from "./mcp-servers-host.ts";
+import { claimedNotice, createMcpServersHost } from "./mcp-servers-host.ts";
+import { startCheckTimeout } from "../mcp-start-time.ts";
import * as probeModule from "../mcp-probe.ts";
import type { BrokerPath } from "../bot-box/broker-probe.ts";
import { notMcpError, type UrlAnswer } from "./mcp-url-checks.ts";
diff --git a/server/host/mcp-servers-host.ts b/server/host/mcp-servers-host.ts
index 7a27d7c879..c0b042dc5e 100644
--- a/server/host/mcp-servers-host.ts
+++ b/server/host/mcp-servers-host.ts
@@ -4,7 +4,6 @@ import { join } from "node:path";
import { writeFileAtomic } from "../atomic.ts";
import type { AppConfig } from "../config.ts";
-import { launcherOf } from "../cloud-connections.ts";
import { customMcpServers } from "../config.ts";
import type { McpServerSpec, StdioMcpSpec } from "../contracts.ts";
import { addBotMcpServer, claimBotMcpServers, keepForBot, withoutBotMcpServers, type BotKept, type BotMcpServerAdd } from "../mcp-bot-servers.ts";
@@ -12,6 +11,7 @@ import { MCP_RESTART_ENV } from "../mcp-app-catalog.ts";
import { grantMover, grantServersMark, storedGrantSpec, type GrantServer } from "../mcp-grant-spec.ts";
import { createMcpHealth, nameList, toolLabel, type McpHealthDeps } from "../mcp-health.ts";
import { probeMcpServer } from "../mcp-probe.ts";
+import { startCheckTimeout } from "../mcp-start-time.ts";
import { isRemoteMcpServer, parseStoredMcpServer, type StoredRemoteMcpServer, type StoredStdioMcpServer } from "../mcp-registry.ts";
import type { McpKeys } from "../vault/mcp-keys.ts";
import { canUseMcpServer } from "../../shared/tool-scope.ts";
@@ -52,11 +52,6 @@ export interface McpServersHostDeps {
const CLAIMED_FILE = (dataDir: string) => join(dataDir, "mcp-bot-servers.json");
-/** A package runner fetches its program the first time it starts, and later starts are quick: its check waits for that. */
-const PACKAGE_RUNNERS: ReadonlySet<string> = new Set(["uvx", "npx", "bunx", "pipx", "pnpm", "uv"]);
-const PACKAGE_START_MS = 120_000;
-export const startCheckTimeout = (command: string): number | undefined => (PACKAGE_RUNNERS.has(launcherOf(command)) ? PACKAGE_START_MS : undefined);
-
/** What the person hears once when servers in one bot's folder became that bot's own. */
export function claimedNotice(botName: string, names: readonly string[]): string {
const tools = names.toSorted().map(toolLabel);
diff --git a/server/mcp-start-time.ts b/server/mcp-start-time.ts
new file mode 100644
index 0000000000..ed47b2ab57
--- /dev/null
+++ b/server/mcp-start-time.ts
@@ -0,0 +1,8 @@
+import { launcherOf } from "./cloud-connections.ts";
+
+/** A package runner fetches its program the first time it starts, and later starts are quick: its check waits for that. */
+const PACKAGE_RUNNERS: ReadonlySet<string> = new Set(["uvx", "npx", "bunx", "pipx", "pnpm", "uv"]);
+const PACKAGE_START_MS = 120_000;
+
+/** How long a command server that starts through a package runner gets to start, or undefined for any other command. */
+export const startCheckTimeout = (command: string): number | undefined => (PACKAGE_RUNNERS.has(launcherOf(command)) ? PACKAGE_START_MS : undefined);