Skip to content

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

fix(claude): third-party MCP tools load on demand through Claude Code's tool search (#3759)

Milind Soni95ea06adc95d
diff --git a/docs/verification/claude-tool-lifecycle.md b/docs/verification/claude-tool-lifecycle.md
index cc6c7b3623..bd2caee086 100644
--- a/docs/verification/claude-tool-lifecycle.md
+++ b/docs/verification/claude-tool-lifecycle.md
@@ -19,10 +19,14 @@ The regression fixture emits this result, then asks for WebFetch permission,
and only finishes the parent after the test releases a file gate.
The small `agents` and `ogb` MCP servers use `alwaysLoad: true` so the first
-prompt includes coordination and approval tools. Other MCP servers retain
-normal deferred loading. This prevents the deferred-lookup dependency; it
-does not magically reconnect a crashed server or override a user's denied
-tool policy.
+prompt includes coordination and approval tools; the browser does too when the
+turn plans to browse. Every other MCP server (connected apps, a bot's own
+servers, data, phone, computer and the rest) loads on demand: each turn's
+private `--settings` file sets `ENABLE_TOOL_SEARCH=true`, unless the person set
+an opt-out such as `false` or `auto:100` in the bot project's or their own
+Claude settings or the environment (`server/drivers/claude-tool-search.ts`).
+This prevents the deferred-lookup dependency; it does not magically reconnect a
+crashed server or override a user's denied tool policy.
Sources:
@@ -33,7 +37,7 @@ Sources:
Regression checks:
```sh
-pnpm exec vitest run server/drivers/claude.test.ts server/drivers/agents-proxy.test.ts server/harness-mcp-proxy.test.ts
+pnpm exec vitest run server/drivers/claude.test.ts server/drivers/claude-tool-search.test.ts server/drivers/agents-proxy.test.ts server/harness-mcp-proxy.test.ts
```
The turn boundary itself — a capability whose owning turn has been replaced
diff --git a/server/drivers/claude-tool-search.test.ts b/server/drivers/claude-tool-search.test.ts
new file mode 100644
index 0000000000..db5c68c2ed
--- /dev/null
+++ b/server/drivers/claude-tool-search.test.ts
@@ -0,0 +1,98 @@
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { removeTempDir } from "../testing/cleanup.ts";
+import { claudeToolSearchSetting, claudeToolSearchValue } from "./claude-tool-search.ts";
+
+describe("claudeToolSearchValue", () => {
+ it("turns unset and auto on", () => {
+ for (const value of [undefined, "", "auto", "auto:10", "auto:99.5", "auto:x", "auto:Infinity", "auto:1.5e1"]) {
+ expect(claudeToolSearchValue(value), String(value)).toBe("true");
+ }
+ });
+
+ it("keeps any other value, so an opt-out holds", () => {
+ // auto:N is clamped to 0..100: 100 and above is off, 0 and below already on.
+ for (const value of ["false", "0", "off", "no", " FALSE ", "auto:100", "auto:150", "auto:1e2", "auto:1_000", "auto:1,000", "true", "1", "auto:0", "auto:-5", "AUTO"]) {
+ expect(claudeToolSearchValue(value), value).toBe(value);
+ }
+ });
+});
+
+describe("claudeToolSearchSetting", () => {
+ let root: string;
+ let home: string;
+ let env: NodeJS.ProcessEnv;
+ const settingsFile = (folder: string, name: string, value: unknown) => {
+ mkdirSync(join(folder, ".claude"), { recursive: true });
+ writeFileSync(join(folder, ".claude", name), JSON.stringify({ env: { ENABLE_TOOL_SEARCH: value } }));
+ };
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), "omb-tool-search-"));
+ home = join(root, "home");
+ mkdirSync(home);
+ env = { HOME: home };
+ });
+
+ afterEach(async () => {
+ await removeTempDir(root);
+ });
+
+ it("turns tool search on when nothing sets it", () => {
+ const cwd = join(root, "bot");
+ mkdirSync(cwd);
+ expect(claudeToolSearchSetting(cwd, env)).toBe("true");
+ expect(claudeToolSearchSetting(join(root, "missing"), env)).toBe("true");
+ });
+
+ it("honours the person's own opt-out, in their settings or the process environment", () => {
+ const cwd = join(root, "bot");
+ mkdirSync(cwd);
+ settingsFile(home, "settings.json", "false");
+ expect(claudeToolSearchSetting(cwd, env)).toBe("false");
+ // A named account's settings live in its own folder.
+ const account = join(root, "account");
+ settingsFile(account, "settings.json", "auto:100");
+ expect(claudeToolSearchSetting(cwd, { ...env, CLAUDE_CONFIG_DIR: join(account, ".claude") })).toBe("auto:100");
+ expect(claudeToolSearchSetting(cwd, { HOME: join(root, "nobody"), ENABLE_TOOL_SEARCH: "0" })).toBe("0");
+ expect(claudeToolSearchSetting(cwd, { HOME: join(root, "nobody"), ENABLE_TOOL_SEARCH: "auto" })).toBe("true");
+ });
+
+ it("reads local over project over the person's own settings over the process environment", () => {
+ const cwd = join(root, "bot");
+ mkdirSync(cwd);
+ settingsFile(home, "settings.json", "auto");
+ expect(claudeToolSearchSetting(cwd, { ...env, ENABLE_TOOL_SEARCH: "false" })).toBe("true");
+ settingsFile(cwd, "settings.json", "false");
+ expect(claudeToolSearchSetting(cwd, env)).toBe("false");
+ settingsFile(cwd, "settings.local.json", "auto:20");
+ expect(claudeToolSearchSetting(cwd, env)).toBe("true");
+ // A file that is not JSON, or sets something else, is skipped.
+ writeFileSync(join(cwd, ".claude", "settings.local.json"), "{ not json");
+ expect(claudeToolSearchSetting(cwd, env)).toBe("false");
+ writeFileSync(join(cwd, ".claude", "settings.local.json"), JSON.stringify({ env: { ENABLE_TOOL_SEARCH: false } }));
+ expect(claudeToolSearchSetting(cwd, env)).toBe("false");
+ });
+
+ // On Windows Claude Code keeps the local file in the launch folder.
+ it.skipIf(process.platform === "win32")("finds the local file at a repository's root, a worktree's main checkout included", () => {
+ const repo = join(root, "repo");
+ const nested = join(repo, "packages", "app");
+ mkdirSync(join(repo, ".git", "worktrees", "wt"), { recursive: true });
+ mkdirSync(nested, { recursive: true });
+ writeFileSync(join(repo, ".git", "worktrees", "wt", "commondir"), "../..\n");
+ const worktree = join(root, "wt");
+ mkdirSync(worktree);
+ writeFileSync(join(worktree, ".git"), `gitdir: ${join(repo, ".git", "worktrees", "wt")}\n`);
+ settingsFile(home, "settings.json", "auto");
+ settingsFile(repo, "settings.local.json", "off");
+ expect(claudeToolSearchSetting(nested, env)).toBe("off");
+ expect(claudeToolSearchSetting(worktree, env)).toBe("off");
+ // The root's file wins over one an older Claude Code left in the launch folder.
+ settingsFile(nested, "settings.local.json", "auto");
+ expect(claudeToolSearchSetting(nested, env)).toBe("off");
+ });
+});
diff --git a/server/drivers/claude-tool-search.ts b/server/drivers/claude-tool-search.ts
new file mode 100644
index 0000000000..923c085a42
--- /dev/null
+++ b/server/drivers/claude-tool-search.ts
@@ -0,0 +1,118 @@
+// Claude Code can keep MCP tools out of the request until the model looks one up with its ToolSearch
+// tool: the turn carries the tool names, and a schema loads only when searched. Its `auto` mode
+// instead sends every schema while they fit under a share of the context window (a tenth by
+// default), which on a 1M-token model is nearly always: every model call pays for every connected
+// app's schemas, and a session writes them into the prompt cache again and again. Claude Code
+// 2.1.312 defers by default when nothing is set, but holds a resumed conversation that ran without
+// ToolSearch to the old way ("ENABLE_TOOL_SEARCH=true overrides this"), and OpenMausBot resumes every
+// thread. So a turn runs with ENABLE_TOOL_SEARCH=true unless the person chose otherwise.
+//
+// The value goes in the turn's private --settings file. Claude Code applies a settings file's `env`
+// over its own process environment, so a value in the project's or the person's .claude settings
+// would beat one set on the process; settings passed with --settings beat both.
+//
+// OpenMausBot's own small servers stay loaded (`alwaysLoad` in claude.ts): `ogb` (approvals and
+// questions) and `agents` (bots, rooms, jobs), plus the browser when the turn plans to browse.
+import { readFileSync, statSync } from "node:fs";
+import { homedir } from "node:os";
+import { basename, dirname, join, resolve } from "node:path";
+
+/** Only a regular file this small is read: a FIFO would hold the server's one thread. */
+const FILE_MAX_BYTES = 1024 * 1024;
+
+function smallFile(path: string): string | null {
+ try {
+ const stat = statSync(path);
+ return stat.isFile() && stat.size <= FILE_MAX_BYTES ? readFileSync(path, "utf8") : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Claude Code's reading of N in auto:N: a whole number written with an exponent ("1e2"), digits
+ * grouped by `_`, `,` or a space ("1_000"), else parseInt. */
+function claudeInteger(text: string): number {
+ const value = text.trim();
+ if (value.length <= 32 && /^[+-]?(\d+(\.\d*)?|\.\d+)[eE][+-]?\d+$/.test(value)) {
+ const number = Number(value);
+ return Number.isInteger(number) ? number : Number.NaN;
+ }
+ if (value.length <= 32 && /^[+-]?\d{1,3}([_,   ])\d{3}(?:\1\d{3})*$/.test(value)) {
+ return Number.parseInt(value.replace(/[_,   ]/g, ""), 10);
+ }
+ return Number.parseInt(value, 10);
+}
+
+/** What a turn sets ENABLE_TOOL_SEARCH to, from the value Claude Code would read otherwise. Nothing
+ * and auto become "true". Any other value is the person's own and is kept: "false", "0", "off" or
+ * auto:100 (N is clamped to 0..100) turn tool search off, and "true" or auto:0 already have it on. */
+export function claudeToolSearchValue(value: string | undefined): string {
+ if (!value || value === "auto") return "true";
+ if (!value.startsWith("auto:")) return value;
+ const percent = claudeInteger(value.slice("auto:".length));
+ // Claude Code reads an auto:N it cannot parse as plain auto.
+ if (Number.isNaN(percent)) return "true";
+ return percent > 0 && percent < 100 ? "true" : value;
+}
+
+/** ENABLE_TOOL_SEARCH in a settings file's `env`, or undefined when the file is missing, not JSON or silent. */
+function settingsValue(file: string): string | undefined {
+ const text = smallFile(file);
+ if (text === null) return undefined;
+ try {
+ const value = (JSON.parse(text) as { env?: Record<string, unknown> } | null)?.env?.ENABLE_TOOL_SEARCH;
+ return typeof value === "string" ? value : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** The main checkout of a folder holding `.git`, else null. A worktree's `.git` file points at
+ * <main>/.git/worktrees/<name>, whose commondir leads back to <main>/.git. */
+function checkoutRoot(folder: string): string | null {
+ const git = join(folder, ".git");
+ try {
+ if (!statSync(git).isFile()) return folder;
+ } catch {
+ return null;
+ }
+ const gitDir = /^gitdir:\s*(.+)$/m.exec(smallFile(git) ?? "")?.[1]?.trim();
+ if (!gitDir) return folder;
+ const worktree = resolve(folder, gitDir);
+ const commonDir = smallFile(join(worktree, "commondir"))?.trim();
+ if (!commonDir) return folder;
+ const common = resolve(worktree, commonDir);
+ return basename(common) === ".git" ? dirname(common) : folder;
+}
+
+/** Where Claude Code keeps .claude/settings.local.json: the repository's root, or the folder itself
+ * outside a repository, on Windows, or when the root is the home folder. */
+function localSettingsFolder(cwd: string, home: string): string {
+ if (process.platform === "win32") return cwd;
+ for (let folder = cwd; ; folder = dirname(folder)) {
+ const root = checkoutRoot(folder);
+ if (root !== null) return root === home ? cwd : root;
+ if (dirname(folder) === folder) return cwd;
+ }
+}
+
+/** The turn's ENABLE_TOOL_SEARCH (claudeToolSearchValue) from what Claude Code would read: the local
+ * settings over the project's over the person's own, then the process environment. The person's own
+ * settings count even when the turn leaves them out (--setting-sources project), so an opt-out made
+ * there still holds. `env` is the turn's environment, its CLAUDE_CONFIG_DIR already resolved. */
+export function claudeToolSearchSetting(cwd: string, env: NodeJS.ProcessEnv): string {
+ const home = env.HOME || env.USERPROFILE || homedir();
+ const local = localSettingsFolder(cwd, home);
+ const files = [
+ join(local, ".claude", "settings.local.json"),
+ // An older Claude Code left the local file in the launch folder; the root one wins.
+ ...(local === cwd ? [] : [join(cwd, ".claude", "settings.local.json")]),
+ join(cwd, ".claude", "settings.json"),
+ join(env.CLAUDE_CONFIG_DIR || join(home, ".claude"), "settings.json"),
+ ];
+ for (const file of files) {
+ const value = settingsValue(file);
+ if (value !== undefined) return claudeToolSearchValue(value);
+ }
+ return claudeToolSearchValue(env.ENABLE_TOOL_SEARCH);
+}
diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.ts
index 87b7862af4..b6e4818801 100644
--- a/server/drivers/claude.test.ts
+++ b/server/drivers/claude.test.ts
@@ -1688,7 +1688,7 @@ describe("ClaudeDriver turns (fake CLI)", () => {
await instance.adapter.sendTurn({ threadId: "t-auth-settings", text: "hi" });
await recorder.until((e) => e.type === "turn.completed");
const seen = JSON.parse(readFileSync(dump, "utf8"));
- expect(seen.settings).toEqual({ claudeMdExcludes: [join(homedir(), ".claude", "CLAUDE.md")], apiKeyHelper: settings.apiKeyHelper, env: { ANTHROPIC_BASE_URL: settings.env.ANTHROPIC_BASE_URL, ANTHROPIC_AUTH_TOKEN: "synthetic-token" } });
+ expect(seen.settings).toEqual({ claudeMdExcludes: [join(homedir(), ".claude", "CLAUDE.md")], apiKeyHelper: settings.apiKeyHelper, env: { ANTHROPIC_BASE_URL: settings.env.ANTHROPIC_BASE_URL, ANTHROPIC_AUTH_TOKEN: "synthetic-token", ENABLE_TOOL_SEARCH: "true" } });
expect(seen.argv[seen.argv.indexOf("--setting-sources") + 1]).toBe("project");
expect(JSON.stringify(seen.argv)).not.toContain("synthetic");
const settingsPath = seen.argv[seen.argv.indexOf("--settings") + 1];
@@ -1718,6 +1718,68 @@ describe("ClaudeDriver turns (fake CLI)", () => {
expect(after.settings.env.ANTHROPIC_API_KEY).toBe("synthetic-new");
});
+ it("loads third-party MCP tools on demand and keeps OpenMausBot's own servers loaded", async () => {
+ await create();
+ const dump = join(scratch, "tool-search.json");
+ process.env.FAKE_CLAUDE_DUMP = dump;
+ const stdio = (name: string) => ({ command: process.execPath, args: [`/fake/${name}.js`], env: {} });
+ const integrations = {
+ agents: stdio("agents"), browser: stdio("browser"), composio: stdio("composio"), composioOwn: stdio("own-apps"),
+ localComputer: stdio("computer"), phone: stdio("phone"), data: stdio("data"), highlevel: stdio("highlevel"),
+ device: stdio("device"), dweb: { url: "http://127.0.0.1:1" },
+ custom: { shop: { command: "npx", args: ["shop"], env: {} }, docs: { type: "http" as const, url: "https://docs.example.test/mcp", headers: {} } },
+ };
+ const mounted = async (threadId: string, preloadBrowserTools: boolean) => {
+ const { turnId } = await instance.adapter.sendTurn({ threadId, text: "hi", cwd: scratch, preloadBrowserTools, integrations });
+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === turnId);
+ const seen = JSON.parse(readFileSync(dump, "utf8")) as { settings: { env: Record<string, string> }; mcpConfig: { mcpServers: Record<string, { alwaysLoad?: boolean }> } };
+ const servers = Object.entries(seen.mcpConfig.mcpServers);
+ return {
+ toolSearch: seen.settings.env.ENABLE_TOOL_SEARCH,
+ alwaysLoaded: servers.filter(([, server]) => server.alwaysLoad === true).map(([name]) => name).sort(),
+ onDemand: servers.filter(([, server]) => server.alwaysLoad === undefined).map(([name]) => name).sort(),
+ };
+ };
+
+ const browsing = await mounted("t-tool-search", true);
+ expect(browsing.toolSearch).toBe("true");
+ expect(browsing.alwaysLoaded).toEqual(["agents", "browser", "ogb"]);
+ expect(browsing.onDemand).toEqual(["composio", "computer", "data", "device", "docs", "dweb", "highlevel", "own_apps", "phone", "shop"]);
+ const other = await mounted("t-tool-search-no-browse", false);
+ expect(other.alwaysLoaded).toEqual(["agents", "ogb"]);
+ expect(other.onDemand).toContain("browser");
+ });
+
+ it("honours a person who turned Claude Code's tool search off, and restarts when they change it", async () => {
+ const account = join(scratch, "account");
+ mkdirSync(account);
+ const path = join(account, "settings.json");
+ writeFileSync(path, JSON.stringify({ env: { ENABLE_TOOL_SEARCH: "false" } }));
+ const dump = join(scratch, "tool-search-off.json");
+ await create(undefined, { FAKE_CLAUDE_DUMP: dump }, { configDir: account });
+ const turn = async (text: string, cwd?: string) => {
+ const { turnId } = await instance.adapter.sendTurn({
+ threadId: "t-tool-search-off", text, ...(cwd ? { cwd } : {}),
+ integrations: { composio: { command: process.execPath, args: ["/fake/composio.js"], env: {} } },
+ });
+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === turnId);
+ return JSON.parse(readFileSync(dump, "utf8")) as { pid: number; settings: { env: Record<string, string> } };
+ };
+
+ // The turn leaves the account's settings out (--setting-sources project), so the choice travels in --settings.
+ const off = await turn("hi");
+ expect(off.settings.env.ENABLE_TOOL_SEARCH).toBe("false");
+ writeFileSync(path, JSON.stringify({ env: { ENABLE_TOOL_SEARCH: "auto" } }));
+ const on = await turn("again");
+ expect(on.settings.env.ENABLE_TOOL_SEARCH).toBe("true");
+ expect(on.pid).not.toBe(off.pid);
+ // The bot's project settings beat the account's.
+ const project = join(scratch, "project-off");
+ mkdirSync(join(project, ".claude"), { recursive: true });
+ writeFileSync(join(project, ".claude", "settings.json"), JSON.stringify({ env: { ENABLE_TOOL_SEARCH: "auto:100" } }));
+ expect((await turn("project", project)).settings.env.ENABLE_TOOL_SEARCH).toBe("auto:100");
+ });
+
it("does not mix a personal helper/endpoint with an explicitly configured OMB connection", async () => {
const account = join(scratch, "account");
mkdirSync(account);
@@ -1727,7 +1789,7 @@ describe("ClaudeDriver turns (fake CLI)", () => {
await instance.adapter.sendTurn({ threadId: "t-auth-explicit", text: "hi" });
await recorder.until((e) => e.type === "turn.completed");
const seen = JSON.parse(readFileSync(dump, "utf8"));
- expect(seen.settings).toEqual({ claudeMdExcludes: [join(homedir(), ".claude", "CLAUDE.md")] });
+ expect(seen.settings).toEqual({ claudeMdExcludes: [join(homedir(), ".claude", "CLAUDE.md")], env: { ENABLE_TOOL_SEARCH: "true" } });
expect(seen.env.ANTHROPIC_API_KEY).toBe("workspace-key");
expect(seen.env.ANTHROPIC_BASE_URL).toBeUndefined();
expect(readClaudeAuthSettings({ HOME: scratch, CLAUDE_CONFIG_DIR: join(scratch, "other-account") })).toEqual({});
diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts
index aaa0d16e36..936f5defe9 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -16,6 +16,7 @@ import { projectMcpServers } from "./claude-project-mcp.ts";
import { claudeBilling, claudeCallUsage } from "./claude-billing.ts";
import { claudeAuthFailure, claudeAuthRecovery } from "./claude-auth-recovery.ts";
import { claudeModelExtras } from "./claude-model-extras.ts";
+import { claudeToolSearchSetting } from "./claude-tool-search.ts";
import { classifyResumeFailure, mayReplay, rebuiltSessionNotice, recoveryPromptFor } from "../resume-recovery.ts";
import { ClaudeLoginController } from "./claude-login-auth.ts";
@@ -1194,7 +1195,10 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
// in the packaged app process.execPath is Electron — run the helper as node
if (process.versions.electron) env.ELECTRON_RUN_AS_NODE = "1";
}
- const settings: Record<string, unknown> = { ...authSettings };
+ const cwd = turn.cwd ?? homedir();
+ // Every MCP server without alwaysLoad loads on demand behind ToolSearch (claude-tool-search.ts).
+ const toolSearch = claudeToolSearchSetting(cwd, env);
+ const settings: Record<string, unknown> = { ...authSettings, env: { ...authSettings.env, ENABLE_TOOL_SEARCH: toolSearch } };
// Project-only settings still find the personal memory via ancestors when the bot lives under HOME.
if (isolated) settings.claudeMdExcludes = [join(homedir(), ".claude", "CLAUDE.md")];
if (hooks) settings.hooks = claudeHookSettings(HOOK_HELPER_PATH);
@@ -1204,7 +1208,6 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
if (authSettingsPath) args.push("--settings", authSettingsPath);
// Approvals and browser credentials expire at the turn boundary; native background workers must not outlive it.
env.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS = "1";
- const cwd = turn.cwd ?? homedir();
const commandCwd = permissionLaunchCwd(cwd);
const privateFileFlags = new Set(["--mcp-config", "--settings"]);
const keyArgs = args.filter((a, i) => !privateFileFlags.has(a) && !privateFileFlags.has(args[i - 1] ?? ""));
@@ -1217,6 +1220,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
base: env.ANTHROPIC_BASE_URL ?? null,
configDir: env.CLAUDE_CONFIG_DIR ?? null,
hooks: Boolean(hooks),
+ toolSearch,
// Rotating an account's key/helper must not reuse the old process.
auth: createHash("sha256").update(JSON.stringify({
settings: authSettings,