Skip to content

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

fix(chat-mcp): reach servers past the tool limit through the directory, and show the bot's tool budget

milind-soniffd126e540c8
diff --git a/docs/custom-mcp-servers.md b/docs/custom-mcp-servers.md
index 9102159a5b..234257b3ae 100644
--- a/docs/custom-mcp-servers.md
+++ b/docs/custom-mcp-servers.md
@@ -291,9 +291,19 @@ Known limits:
Codex lets a server's read-only tools run without asking, but here every
tool runs through the one tool that runs them all, which cannot carry each
tool's own read-only hint. Each Whop call shows a card, naming the tool.
-- **Command servers are not searched yet.** Only URL servers are. A command
- server with hundreds of tools is still listed whole, and API-model bots
- refuse more than 128 tools in one turn.
+- **Command servers are searched only on API models.** On other engines a
+ command server with hundreds of tools is still listed whole.
+
+API-model bots take at most 128 tools in one turn, and every server of the
+turn shares them with the built-in tools. When a bot's servers offer more,
+the turn lists as many whole servers as fit, in the order they are set up
+after the built-ins, and reaches the rest through one tool search of three
+tools (`mcp_search_tools`, `mcp_describe_tool`, `mcp_call_tool`) that count
+toward the 128. No server is left out for the limit; the chat says in one
+line which servers were reached through the search. The bot's MCP servers
+card in Access shows the last turn's count against the limit and those
+servers, and a server's **Test** says when it alone has more tools than the
+limit, or half of it or more.
### Which engines reach which servers
@@ -469,7 +479,10 @@ servers gets the enabled tools on its next task.
- **Testing is bounded.** A command is stopped after the handshake (or eight
seconds), its output is capped, and its stderr is never sent to the UI. It
inherits none of OpenMausBot's workspace or provider credentials; only the
- environment variables configured for that MCP server are added. A test
+ environment variables configured for that MCP server are added. Where bots
+ are boxed, a command server is tested in the box, as a bot's turn starts
+ it, and its configured variables pass the box's allow-list there, in the
+ test and in an API-model bot's turn alike. A test
reads at most 32 MB (Whop's tool list alone is 1.2 MB), and a URL test
reports only the HTTP status of a refusal.
- **Addresses are checked.** A URL server needs a full `http://` or
diff --git a/docs/verification/openai-tools.md b/docs/verification/openai-tools.md
index c978ab85df..2c40883054 100644
--- a/docs/verification/openai-tools.md
+++ b/docs/verification/openai-tools.md
@@ -71,6 +71,17 @@ steps so far already ran, so ask only for what's left (retrying the whole task
would repeat them). A batch that would pass 200 runs none of its calls. There
is no per-bot or per-thread setting for either number.
+A turn whose MCP servers offer more than the 128 tools a request may carry
+lists whole servers in turn order and reaches the rest through the
+`mcp_search_tools` / `mcp_describe_tool` / `mcp_call_tool` directory, whose
+three tools count toward the limit; no server is skipped for it. The bot's
+last budget is read at `GET /api/bots/ID/tool-budget`. The driver tests
+cover it with real stdio servers:
+
+```sh
+pnpm exec vitest run server/drivers/chat-mcp-tools.test.ts server/drivers/openai-chat-tools.test.ts
+```
+
The harness proves the OpenAI-compatible adapter and the shared execution
path. It does not establish that every third-party model supports tools, or
that live Grok and MiniMax services accept a particular schema. Model support
diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.ts
index 59ad0098a2..3b3dec7907 100644
--- a/server/drivers/chat-mcp-tools.test.ts
+++ b/server/drivers/chat-mcp-tools.test.ts
@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { augmentedPath } from "../env-path.ts";
-import { ChatToolSessionError, mountChatTools, trimmedToolsNotice, type ChatToolSession } from "./chat-mcp-tools.ts";
+import { ChatToolSessionError, chatToolNotices, directServers, mountChatTools, trimmedToolsNotice, type ChatToolSession } from "./chat-mcp-tools.ts";
import type { ToolScope } from "../../shared/tool-scope.ts";
import { catalogServer, CUA_DRIVER_WINDOWS_TOOLS, syntheticToolNames } from "../testing/cua-driver-tools.ts";
import { startFakeHttpMcp } from "../testing/fake-http-mcp-server.ts";
@@ -13,11 +13,16 @@ import { wideSchema } from "../testing/oversized-tool-schema.ts";
import { schemaBytes, toolSchemaProfile } from "../tool-schema-profile.ts";
const killProbe = vi.hoisted(() => ({ override: false, stopped: false, budgets: [] as number[] }));
+const spawned = vi.hoisted(() => [] as Array<{ owner?: string; opts: { env?: NodeJS.ProcessEnv; box?: unknown } }>);
vi.mock("../procs.ts", async (importOriginal) => {
const actual = await importOriginal<typeof import("../procs.ts")>();
return {
...actual,
// Always runs the real kill for cleanup; the override only forces the verdict and records the budget.
+ spawnCli: (...args: Parameters<typeof actual.spawnCli>) => {
+ spawned.push({ owner: args[3], opts: args[2] });
+ return actual.spawnCli(...args);
+ },
killCliTree: (child: Parameters<typeof actual.killCliTree>[0], budget = 5_000) => {
killProbe.budgets.push(budget);
const run = actual.killCliTree(child, budget);
@@ -240,6 +245,17 @@ describe("Chat MCP session", () => {
for (const name of secrets) expect(seen).not.toHaveProperty(name);
});
+ it("lets a configured server's own environment, a token included, through the bot box, and no built-in's", async () => {
+ const own = fixture(); const agents = fixture();
+ own.server.env = { ...own.server.env, OP_SERVICE_ACCOUNT_TOKEN: "ops_synthetic" };
+ spawned.length = 0;
+ const session = await mountChatTools({ agents: agents.server, custom: { onepassword: own.server } }, own.controller.signal);
+ sessions.push(session);
+ const of = (receipt: string) => spawned.find((entry) => entry.opts.env?.RECEIPT === receipt)!;
+ expect(of(own.receipt)).toMatchObject({ owner: "bot", opts: { box: { allowEnv: ["RECEIPT", "OP_SERVICE_ACCOUNT_TOKEN"] } } });
+ expect(of(agents.receipt).opts.box).toBeUndefined();
+ });
+
it("mounts only supported descriptors and preserves conversations with no tools", async () => {
const controller = new AbortController();
controllers.push(controller);
@@ -269,7 +285,7 @@ describe("Chat MCP session", () => {
it.each([
["repeated cursor", `reply(message, {tools:[],nextCursor:"same"});`],
- ["too many tools", `reply(message, {tools:Array.from({length:129},(_,i)=>({name:"tool"+i,inputSchema:schema}))});`],
+ ["too many tools", `reply(message, {tools:Array.from({length:2001},(_,i)=>({name:"tool"+i,inputSchema:schema}))});`],
["duplicate tool", `reply(message, {tools:[{name:"same",inputSchema:schema},{name:"same",inputSchema:schema}]});`],
["invalid RPC", `process.stdout.write('{"result":1}\\n');`],
["oversized incomplete frame", `process.stdout.write("x".repeat(2*1024*1024+1));`],
@@ -282,7 +298,7 @@ describe("Chat MCP session", () => {
});
it.each([
- ["too many tools", `reply(message, {tools:Array.from({length:129},(_,i)=>({name:"tool"+i,inputSchema:schema}))});`],
+ ["too many tools", `reply(message, {tools:Array.from({length:2001},(_,i)=>({name:"tool"+i,inputSchema:schema}))});`],
["invalid RPC", `process.stdout.write('{"result":1}\\n');`],
])("still fails startup for a harness mount and awaits child cleanup for %s", async (_label, response) => {
const f = fixture(`if (message.method === "tools/list") { ${response} continue; }`);
@@ -662,20 +678,109 @@ describe("Chat MCP tool limit", () => {
} finally { warn.mockRestore(); }
});
- it("still skips a configured server that does not fit beside the built-ins, leaving room for ask_user", async () => {
+ it("reaches a configured server that does not fit beside the built-ins through the tool search, leaving room for ask_user", async () => {
+ const fits = await mount(windowsTurn(42, { custom: { notes: catalog(syntheticToolNames("note", 13)) } }));
+ expect(fits.names).toHaveLength(127);
+ expect(fits.session.skipped).toEqual([]);
+ expect(fits.session.budget.servers).toEqual([{ name: "notes", tools: 13, direct: true }]);
+ const over = await mount(windowsTurn(42, { custom: { notes: catalog(syntheticToolNames("note", 14)) } }));
+ expect(over.names).toHaveLength(117);
+ expect(over.names.slice(-3)).toEqual(["mcp_search_tools", "mcp_describe_tool", "mcp_call_tool"]);
+ expect(over.session.skipped).toEqual([]);
+ expect(over.session.trimmed).toEqual([]);
+ expect(over.session.budget).toEqual({ limit: 128, listed: 117, servers: [{ name: "notes", tools: 14, direct: false }] });
+ await expect(over.session.execute("mcp_call_tool", { name: "notes_note_14", arguments: {} }, new AbortController().signal)).resolves.toEqual({ ok: true, text: "ran note_14" });
+ });
+
+ it("keeps room for the tool search when built-ins alone would fill the limit", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
- const fits = await mount(windowsTurn(42, { custom: { notes: catalog(syntheticToolNames("note", 13)) } }));
- expect(fits.names).toHaveLength(127);
- expect(fits.session.skipped).toEqual([]);
- const over = await mount(windowsTurn(42, { custom: { notes: catalog(syntheticToolNames("note", 14)) } }));
- expect(over.names).toHaveLength(114);
- expect(over.session.skipped).toEqual([{ server: "notes", reason: "MCP tool count exceeds the 128-tool limit" }]);
- expect(over.session.trimmed).toEqual([]);
+ const { session, names } = await mount({ agents: catalog(syntheticToolNames("agent", 51)), localComputer: catalog(syntheticToolNames("vm", 100)), custom: { notes: catalog(syntheticToolNames("note", 5)) } });
+ expect(names).toHaveLength(127);
+ expect(names.filter((name) => name.startsWith("agents_"))).toHaveLength(51);
+ expect(session.trimmed).toEqual([{ server: "computer", listed: 73, of: 100 }]);
+ expect(names.slice(-3)).toEqual(["mcp_search_tools", "mcp_describe_tool", "mcp_call_tool"]);
+ expect(session.budget.servers).toEqual([{ name: "notes", tools: 5, direct: false }]);
} finally { warn.mockRestore(); }
});
});
+describe("Chat MCP servers past the tool limit", () => {
+ function catalog(names: readonly string[]) {
+ const { dir, server } = catalogServer(names);
+ dirs.push(dir);
+ return server;
+ }
+ async function mount(custom: Record<string, { command: string; args: string[]; env: Record<string, string> }>, toolScope?: ToolScope) {
+ const controller = new AbortController();
+ controllers.push(controller);
+ const session = await mountChatTools({ custom }, controller.signal, false, toolScope);
+ sessions.push(session);
+ return { session, signal: controller.signal, names: session.definitions.map((tool) => tool.function.name) };
+ }
+
+ it("lists whole servers that fit in turn order, and reaches the rest through the tool search in the same turn", async () => {
+ const audit = fixture();
+ const { session, signal, names } = await mount({ notes: catalog(syntheticToolNames("note", 124)), extra: catalog(syntheticToolNames("extra", 3)), audit: audit.server });
+ expect(names).toHaveLength(127);
+ expect(names).toEqual([...syntheticToolNames("notes_note", 124), "mcp_search_tools", "mcp_describe_tool", "mcp_call_tool"]);
+ expect(session.skipped).toEqual([]);
+ expect(session.budget).toEqual({ limit: 128, listed: 127, servers: [
+ { name: "notes", tools: 124, direct: true }, { name: "extra", tools: 3, direct: false }, { name: "audit", tools: 1, direct: false },
+ ] });
+ expect(chatToolNotices(session)).toEqual(['To fit the model\'s 128-tool limit, the tools of "extra" and "audit" are reached through the tool search this turn.']);
+ expect(session.definitions.at(-3)!.function.description).toContain('the MCP servers "extra", "audit"');
+
+ const found = JSON.parse((await session.execute("mcp_search_tools", { query: "fixture write" }, signal)).text);
+ expect(found.matches[0]).toMatchObject({ name: "audit_write", input: "{ value: string }" });
+ expect(session.view("mcp_search_tools", { query: "fixture write" })).toEqual({ title: "mcp_search_tools", input: { query: "fixture write" }, ask: false });
+ await expect(session.execute("mcp_describe_tool", { name: "audit_write" }, signal)).resolves.toMatchObject({ ok: true, text: expect.stringContaining('"required":["value"]') });
+
+ const call = { name: "audit_write", arguments: { value: "through search" } };
+ expect(session.view("mcp_call_tool", call)).toEqual({ title: "audit_write", input: { value: "through search" }, ask: true, grant: grantFor("audit", "write") });
+ const misfit = { name: "audit_write", arguments: { value: 7 } };
+ expect(session.view("mcp_call_tool", misfit).ask).toBe(false);
+ const refused = await session.execute("mcp_call_tool", misfit, signal);
+ expect(refused.ok).toBe(true);
+ expect(JSON.parse(refused.text).problems).toEqual(["value: must be string"]);
+ expect(audit.read().calls.some((entry) => entry.method === "tools/call")).toBe(false);
+ await expect(session.execute("mcp_call_tool", call, signal)).resolves.toEqual({ ok: true, text: "recorded:through search" });
+ expect(audit.read().calls.at(-1)).toMatchObject({ method: "tools/call", params: { name: "write", arguments: { value: "through search" } } });
+ await expect(session.execute("mcp_call_tool", { name: "extra_extra_2", arguments: {} }, signal)).resolves.toEqual({ ok: true, text: "ran extra_2" });
+
+ const unknown = { name: "audit_teleport", arguments: {} };
+ expect(session.view("mcp_call_tool", unknown).ask).toBe(false);
+ await expect(session.execute("mcp_call_tool", unknown, signal)).resolves.toMatchObject({ ok: true, text: expect.stringContaining("search_tools") });
+ });
+
+ it("searches a server that alone offers more than the limit, and lists only the search's three tools", async () => {
+ const { session, signal, names } = await mount({ big: catalog(syntheticToolNames("op", 300)) });
+ expect(names).toEqual(["mcp_search_tools", "mcp_describe_tool", "mcp_call_tool"]);
+ expect(session.budget).toEqual({ limit: 128, listed: 3, servers: [{ name: "big", tools: 300, direct: false }] });
+ await expect(session.execute("mcp_call_tool", { name: "big_op_300", arguments: {} }, signal)).resolves.toEqual({ ok: true, text: "ran op_300" });
+ });
+
+ it("finds and runs only tools in the bot's selection through the tool search", async () => {
+ const allow = ["mcp:notes:*", "mcp:big:op_1", "mcp:big:op_2"];
+ const { session, names } = await mount({ notes: catalog(syntheticToolNames("note", 126)), big: catalog(syntheticToolNames("op", 200)) }, { allow, deny: ["mcp:notes:note_126"] });
+ expect(names).toEqual([...syntheticToolNames("notes_note", 125), "big_op_1", "big_op_2"]);
+ const crowded = await mount({ notes: catalog(syntheticToolNames("note", 130)), big: catalog(syntheticToolNames("op", 200)) }, { allow, deny: ["mcp:notes:note_130"] });
+ expect(crowded.names).toEqual(["big_op_1", "big_op_2", "mcp_search_tools", "mcp_describe_tool", "mcp_call_tool"]);
+ const found = JSON.parse((await crowded.session.execute("mcp_search_tools", { query: "note 130", limit: 20 }, crowded.signal)).text);
+ expect(found.matches.map((match: { name: string }) => match.name)).not.toContain("notes_note_130");
+ await expect(crowded.session.execute("mcp_call_tool", { name: "notes_note_130", arguments: {} }, crowded.signal)).resolves.toMatchObject({ text: expect.stringContaining("No tool named") });
+ await expect(crowded.session.execute("mcp_call_tool", { name: "notes_note_129", arguments: {} }, crowded.signal)).resolves.toEqual({ ok: true, text: "ran note_129" });
+ expect(session.budget.servers.every((server) => server.direct)).toBe(true);
+ });
+
+ it("keeps the tool search's own three tools inside the room it divides", () => {
+ expect([...directServers([{ name: "a", tools: 10 }, { name: "b", tools: 3 }], 13)]).toEqual(["a", "b"]);
+ expect([...directServers([{ name: "a", tools: 12 }, { name: "b", tools: 5 }], 13)]).toEqual(["b"]);
+ expect([...directServers([{ name: "a", tools: 4 }, { name: "b", tools: 40 }, { name: "c", tools: 6 }], 13)]).toEqual(["a", "c"]);
+ expect([...directServers([{ name: "a", tools: 4 }], 3)]).toEqual([]);
+ });
+});
+
describe("Chat MCP startup budgets", () => {
/** Lets real I/O run, the faked clock standing still, until `condition`. */
async function untilReal(condition: () => boolean): Promise<void> {
@@ -843,6 +948,32 @@ describe("Chat MCP schema validation", () => {
expect(() => session.validate("audit_write", {value:invalid})).toThrow("input schema");
});
+ const unknownField = { $id: "/schemas/unknown", title: "unknown" };
+ it.each([
+ ["OpenAPI's example", { type: "object", properties: { value: { type: "string", example: "hello" } }, required: ["value"] }],
+ ["a vendor x- extension and OpenAPI's discriminator", { type: "object", "x-generator": "openapi", discriminator: { propertyName: "value" }, properties: { value: { type: "string", "x-order": 1 } }, required: ["value"] }],
+ ["VS Code's markdownDescription", { type: "object", properties: { value: { type: "string", markdownDescription: "**Value**" } }, required: ["value"] }],
+ ["Effect Schema's repeated $id", { $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { value: { type: "string" }, a: unknownField, b: unknownField }, required: ["value"] }],
+ ["draft-07 named without its #", { $schema: "http://json-schema.org/draft-07/schema", type: "object", properties: { value: { type: "string" } }, required: ["value"] }],
+ ])("mounts a server whose schema carries %s, and still enforces every constraint", async (_label, toolSchema) => {
+ const f = fixture("", toolSchema);
+ const session = await f.mount();
+ expect(session.skipped).toEqual([]);
+ expect(session.definitions[0]!.function.parameters).toEqual(toolSchema);
+ expect(() => session.validate("audit_write", { value: "ok" })).not.toThrow();
+ expect(() => session.validate("audit_write", { value: 7 })).toThrow("input schema");
+ expect(() => session.validate("audit_write", {})).toThrow("input schema");
+ });
+
+ it("keeps a property named like a dropped keyword", async () => {
+ const f = fixture("", { type: "object", properties: { example: { type: "string" }, unknownAssertion: { type: "string", unrecognizedAssertion: true } } });
+ await expectSkipped(f, /schema could not be validated/);
+ const g = fixture("", { type: "object", properties: { example: { type: "string", example: "x" } }, required: ["example"] });
+ const session = await g.mount();
+ expect(() => session.validate("audit_write", { example: "ok" })).not.toThrow();
+ expect(() => session.validate("audit_write", {})).toThrow("input schema");
+ });
+
it.each([
{ type: "object", properties: {value:{type:"string",format:"unregistered-format"}} },
{ type: "object", properties: {value:{$ref:"https://example.invalid/private-schema"}} },
diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.ts
index 12909ee587..39fb03379c 100644
--- a/server/drivers/chat-mcp-tools.ts
+++ b/server/drivers/chat-mcp-tools.ts
@@ -9,17 +9,18 @@ import { killCliTree, spawnCli } from "../procs.ts";
import { AGENTS_TOOL_ALIASES } from "../../shared/agents-tool-names.ts";
import { bridgedCallTarget, unbridgedServer } from "./agents-bridge.ts";
import { chatImage, type ChatImagePart } from "./chat-images.ts";
-import { CALL_TOOL, directoryCallTarget, isDirectoryTool } from "../mcp-directory.ts";
+import { CALL_TOOL, DESCRIBE_TOOL, SEARCH_TOOL, ToolDirectory, directoryCallTarget, isDirectoryTool, type CatalogTool, type DirectoryResult } from "../mcp-directory.ts";
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 { compileToolSchema } from "../mcp-schema-validator.ts";
+import { compileServerToolSchema, compileToolSchema, schemaProblems } from "../mcp-schema-validator.ts";
import { fitToolList } from "../mcp-tool-schema.ts";
import { listsComputerTool } from "../computer-tool-list.ts";
import { capToolList, shareToolBudget } from "../tool-count-limit.ts";
import type { ToolSchemaProfile } from "../tool-schema-profile.ts";
import { allowsTool, canUseMcpServer, parseToolScope, type ToolScope } from "../../shared/tool-scope.ts";
import { OWN_APPS_SERVER } from "../../shared/own-apps.ts";
+import { CHAT_TOOL_LIMIT, type ToolBudget } from "../../shared/tool-budget.ts";
export interface ChatToolDefinition {
type: "function";
@@ -38,6 +39,7 @@ export interface ChatToolSession {
definitions: ChatToolDefinition[];
skipped: SkippedChatMcpServer[];
trimmed: TrimmedChatMcpServer[];
+ budget: ToolBudget;
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;
@@ -54,10 +56,14 @@ const STARTUP_MS = 8_000;
const DEFAULT_CALL_MS = 10 * 60_000;
const FRAME_BYTES = 2 * 1024 * 1024;
const OUTPUT_BYTES = 50 * 1024;
-const TOOL_COUNT = 128;
+const TOOL_COUNT = CHAT_TOOL_LIMIT;
/** ask_user, which the runtime lists after the MCP tools. */
const RUNTIME_TOOLS = 1;
const MCP_TOOL_COUNT = TOOL_COUNT - RUNTIME_TOOLS;
+/** Past the limit a server is searched, not listed, so this only bounds what one server may offer. */
+const SERVER_TOOLS_MAX = 2_000;
+const DIRECTORY_SERVER = "mcp";
+const DIRECTORY_TOOL_COUNT = 3;
const MAX_PAGES = 100;
const SCHEMA_BYTES = 64 * 1024;
const CATALOG_BYTES = 1024 * 1024;
@@ -86,12 +92,14 @@ export class ChatMcpClient {
private closing?: Promise<void>;
private pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>();
- constructor(server: Server, computerUse = false) {
+ /** `configured`: a server the person set up, whose own environment passes the bot box as theirs. */
+ constructor(server: Server, computerUse = false, configured = false) {
this.frameBytes = computerUse ? 32 * 1024 * 1024 : FRAME_BYTES;
try {
// The desktop shell inherits Finder's bare PATH, where `npx`-style servers cannot find `node`.
this.child = spawnCli(server.command, server.args, {
stdio: ["pipe", "pipe", "pipe"], env: chatMcpEnvironment(server.env),
+ ...(configured ? { box: { allowEnv: Object.keys(server.env) } } : {}),
}, "bot");
} catch { throw new Error("MCP server could not start; check its command and installation"); }
this.child.stdout.setEncoding("utf8");
@@ -230,7 +238,7 @@ export class ChatMcpClient {
if (!object(result) || !Array.isArray(result.tools)) throw new Error("MCP tools/list returned an invalid result");
observer?.listed(result);
tools.push(...result.tools.filter((tool) => modelVisible(tool) && include(tool)));
- if (tools.length > TOOL_COUNT) throw new Error("MCP tool count exceeds the 128-tool limit");
+ if (tools.length > SERVER_TOOLS_MAX) throw new Error(`MCP server offers more than ${SERVER_TOOLS_MAX} tools`);
if (result.nextCursor === undefined) return tools;
if (typeof result.nextCursor !== "string" || !result.nextCursor || cursors.has(result.nextCursor)) throw new Error("MCP tools/list returned an invalid pagination cursor");
cursors.add(result.nextCursor);
@@ -246,6 +254,21 @@ export function trimmedToolsNotice(trimmed: readonly TrimmedChatMcpServer[]): st
return `${servers} to fit the model's ${TOOL_COUNT}-tool limit; the rest are left out of this turn.`;
}
+export function searchedServersNotice(budget: ToolBudget): string | undefined {
+ const names = budget.servers.filter((server) => !server.direct).map((server) => `"${server.name}"`);
+ if (!names.length) return undefined;
+ const listed = names.length === 1 ? names[0] : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
+ return `To fit the model's ${budget.limit}-tool limit, the tools of ${listed} are reached through the tool search this turn.`;
+}
+
+/** 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">): string[] {
+ return [
+ ...session.skipped.map(({ server, reason }) => `MCP server "${server}" was skipped for this turn: ${reason}`),
+ trimmedToolsNotice(session.trimmed), searchedServersNotice(session.budget),
+ ].filter((line): line is string => line !== undefined);
+}
+
function boundedText(value: string): string {
const bytes = Buffer.from(value);
if (bytes.length <= OUTPUT_BYTES) return value;
@@ -267,6 +290,41 @@ function omitBlankDefaults(builtInBrowser: boolean, tool: string, args: unknown)
}
}
+type CheckedTool = { tool: Record<string, unknown> & { name: string; inputSchema: Record<string, unknown> }; schema: ValidateFunction };
+type ToolOrigin = Omit<RegisteredTool, "name" | "schema">;
+const ARGUMENTS_MISFIT = "Tool arguments do not match the advertised input schema; use its required fields and types";
+
+function checkedTools(tools: readonly unknown[]): CheckedTool[] {
+ const names = new Set<string>();
+ return tools.map((tool) => {
+ if (!object(tool) || typeof tool.name !== "string" || !tool.name.trim() || names.has(tool.name)) throw new Error("MCP server advertised an invalid or duplicate tool name");
+ names.add(tool.name);
+ if (!object(tool.inputSchema) || tool.inputSchema.type !== "object") throw new Error("MCP tools require an object input schema");
+ if (Buffer.byteLength(JSON.stringify(tool.inputSchema)) > SCHEMA_BYTES) throw new Error("MCP tool schema exceeds the 64KB limit");
+ return { tool: tool as CheckedTool["tool"], schema: compileServerToolSchema(tool.inputSchema) };
+ });
+}
+
+function uniqueName(base: string, taken: (name: string) => boolean): string {
+ let name = base;
+ for (let index = 2; taken(name); index += 1) { const suffix = `_${index}`; name = base.slice(0, 64 - suffix.length) + suffix; }
+ return name;
+}
+
+/** The configured servers a turn lists whole within `room` tools, in turn order. When not all fit, the tool search's own
+ * tools take their place in the room first, and the rest are reached through it. */
+export function directServers(servers: ReadonlyArray<{ name: string; tools: number }>, room: number): Set<string> {
+ if (servers.reduce((sum, server) => sum + server.tools, 0) <= room) return new Set(servers.map((server) => server.name));
+ let left = room - DIRECTORY_TOOL_COUNT;
+ const direct = new Set<string>();
+ for (const server of servers) {
+ if (server.tools > left) continue;
+ direct.add(server.name);
+ left -= server.tools;
+ }
+ return direct;
+}
+
/** Under `schemaProfile` the model reads each tool's schema fitted to its provider; calls are still checked against the full one. */
export async function mountChatTools(integrations: SendTurnInput["integrations"], signal: AbortSignal, computerUse = false, toolScope?: ToolScope, callTimeoutMs: number = DEFAULT_CALL_MS,
schemaProfile?: ToolSchemaProfile): Promise<ChatToolSession> {
@@ -301,7 +359,6 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]
}
if (servers.length > 32) throw new Error("MCP server count exceeds the 32-server limit");
const clients: ChatMcpClient[] = [];
- const skippable = new Set(Object.keys(integrations?.custom ?? {}));
const skipped: SkippedChatMcpServer[] = [];
const trimmed: TrimmedChatMcpServer[] = [];
const started = new Map<string, ChatMcpClient>();
@@ -320,12 +377,48 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]
signal.addEventListener("abort", cancel, { once: true });
const definitions: ChatToolDefinition[] = [];
const registered = new Map<string, RegisteredTool>();
+ const catalog = new Map<string, RegisteredTool>();
+ const directoryNames = new Map<string, string>();
+ let directory: ToolDirectory | undefined;
+ const budget: ToolBudget = { limit: TOOL_COUNT, listed: 0, servers: [] };
+ const register = (origin: ToolOrigin, tools: readonly CheckedTool[]) => {
+ const staged: Array<{ tool: RegisteredTool; definition: ChatToolDefinition }> = [];
+ for (const { tool, schema } of tools) {
+ const [listed] = schemaProfile ? fitToolList([tool], schemaProfile, (line) => console.warn(`chat-mcp: ${origin.server}: ${line}`)) : [tool];
+ if (!object(listed) || !object(listed.inputSchema)) continue;
+ const parameters = { ...listed.inputSchema };
+ const constraints: Record<string, unknown> = {};
+ if (computerUse) {
+ for (const key of ["anyOf", "oneOf", "allOf", "not"]) {
+ if (key in parameters) { constraints[key] = parameters[key]; delete parameters[key]; }
+ }
+ }
+ 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));
+ 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);
+ }
+ // 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.
+ if (origin.agents) {
+ for (const [alias, { tools: targets }] of Object.entries(AGENTS_TOOL_ALIASES)) {
+ const listed = staged.find((entry) => targets.includes(entry.tool.name));
+ const name = chatToolName(origin.server, alias);
+ if (listed && !registered.has(name)) registered.set(name, { ...listed.tool, name: alias, schema: compileToolSchema({ type: "object" }) });
+ }
+ }
+ };
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]) => {
+ const mounts = await Promise.allSettled(servers.map(async ([name, descriptor], index) => {
if (signal.aborted || closed) throw aborted();
- const client = new ChatMcpClient(descriptor, computerUse);
+ const client = new ChatMcpClient(descriptor, computerUse, index >= builtIns);
clients.push(client);
started.set(name, client);
const computer = descriptor === integrations?.localComputer;
@@ -337,135 +430,156 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]
// Harness mounts are known by descriptor, never by a name a configured server could claim. A grant
// hashes the descriptor (no credential kept); machine bridges mint a bearer per turn, so theirs last a turn.
const launch = createHash("sha256").update(JSON.stringify(descriptor)).digest("hex");
- return { name, client, launch, builtInBrowser: descriptor === integrations?.browser, agents: descriptor === agentsServer,
- hostComputer: descriptor === integrations?.localComputer && integrations?.localComputer?.scope === "local-computer", tools };
+ const origin: ToolOrigin = { client, server: name, launch, builtInBrowser: descriptor === integrations?.browser, agents: descriptor === agentsServer,
+ hostComputer: descriptor === integrations?.localComputer && integrations?.localComputer?.scope === "local-computer", searched: searchable.has(name) };
+ return { origin, tools };
}));
- // The agents server keeps its whole list first; a configured server fits in what the built-ins leave, or is skipped.
- const shares = shareToolBudget(mounts.flatMap((mount, index) => index < builtIns && mount.status === "fulfilled"
- ? [{ name: String(index), tools: mount.value.tools.length, agents: mount.value.agents }] : [])
- .sort((a, b) => Number(b.agents) - Number(a.agents)), MCP_TOOL_COUNT);
+ const skip = async (server: string, error: unknown) => {
+ const reason = error instanceof Error ? error.message : "MCP server failed to start";
+ skipped.push({ server, reason });
+ console.warn(`chat-mcp: skipping MCP server "${server}" for this turn: ${reason}`);
+ await started.get(server)?.close();
+ };
+ const offered: Array<{ origin: ToolOrigin; tools: unknown[] }> = [];
+ const configured: Array<{ origin: ToolOrigin; tools: CheckedTool[] }> = [];
for (const [index, mount] of mounts.entries()) {
- const configured = servers[index]![0];
if (signal.aborted || closed) throw aborted();
- const skip = async (error: unknown) => {
- const reason = error instanceof Error ? error.message : "MCP server failed to start";
- skipped.push({ server: configured, reason });
- console.warn(`chat-mcp: skipping MCP server "${configured}" for this turn: ${reason}`);
- await started.get(configured)?.close();
- };
- if (mount.status === "rejected") {
- if (!skippable.has(configured)) throw mount.reason;
- await skip(mount.reason);
+ if (index < builtIns) {
+ if (mount.status === "rejected") throw mount.reason;
+ offered.push(mount.value);
continue;
}
- const { name: server, client, launch, builtInBrowser, agents, hostComputer, tools: offered } = mount.value;
- const tools = capToolList(offered, shares.get(String(index)));
- if (tools.length < offered.length) {
- trimmed.push({ server, listed: tools.length, of: offered.length });
- console.warn(`chat-mcp: "${server}" listed ${tools.length} of ${offered.length} tools to fit the model's ${TOOL_COUNT}-tool limit`);
- }
- const staged: Array<{ tool: RegisteredTool; definition: ChatToolDefinition }> = [];
- try {
- const originalNames = new Set<string>();
- for (const tool of tools) {
- if (!object(tool) || typeof tool.name !== "string" || !tool.name.trim() || originalNames.has(tool.name)) throw new Error("MCP server advertised an invalid or duplicate tool name");
- originalNames.add(tool.name);
- if (definitions.length + staged.length >= MCP_TOOL_COUNT) throw new Error("MCP tool count exceeds the 128-tool limit");
- if (!object(tool.inputSchema) || tool.inputSchema.type !== "object") throw new Error("MCP tools require an object input schema");
- if (Buffer.byteLength(JSON.stringify(tool.inputSchema)) > SCHEMA_BYTES) throw new Error("MCP tool schema exceeds the 64KB limit");
- const schema = compileToolSchema(tool.inputSchema);
- const [listed] = schemaProfile ? fitToolList([tool], schemaProfile, (line) => console.warn(`chat-mcp: ${server}: ${line}`)) : [tool];
- if (!object(listed) || !object(listed.inputSchema)) continue;
- const parameters = { ...listed.inputSchema };
- const constraints: Record<string, unknown> = {};
- if (computerUse) {
- for (const key of ["anyOf", "oneOf", "allOf", "not"]) {
- if (key in parameters) { constraints[key] = parameters[key]; delete parameters[key]; }
- }
- }
- 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 base = chatToolName(server, tool.name);
- let name = base;
- const taken = (candidate: string) => registered.has(candidate) || staged.some((entry) => entry.definition.function.name === candidate);
- for (let index = 2; taken(name); index += 1) { const suffix = `_${index}`; name = base.slice(0, 64 - suffix.length) + suffix; }
- staged.push({ tool: { client, server, launch, builtInBrowser, agents, hostComputer, name: tool.name, schema, searched: searchable.has(server) },
- 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");
- } catch (error) {
- if (!skippable.has(server)) throw error;
- await skip(error);
- continue;
+ if (mount.status === "rejected") { await skip(servers[index]![0], mount.reason); continue; }
+ try { configured.push({ origin: mount.value.origin, tools: checkedTools(mount.value.tools) }); }
+ catch (error) { await skip(mount.value.origin.server, error); }
+ }
+ const wanted = [...offered, ...configured].reduce((sum, server) => sum + server.tools.length, 0);
+ const searchRoom = configured.some((server) => server.tools.length) && wanted > MCP_TOOL_COUNT ? DIRECTORY_TOOL_COUNT : 0;
+ // The agents server keeps its whole list first; configured servers fit in what the built-ins leave.
+ const shares = shareToolBudget(offered.map(({ origin, tools }, index) => ({ name: String(index), tools: tools.length, agents: origin.agents }))
+ .sort((a, b) => Number(b.agents) - Number(a.agents)), MCP_TOOL_COUNT - searchRoom);
+ for (const [index, { origin, tools: listed }] of offered.entries()) {
+ const tools = capToolList(listed, shares.get(String(index)));
+ if (tools.length < listed.length) {
+ trimmed.push({ server: origin.server, listed: tools.length, of: listed.length });
+ console.warn(`chat-mcp: "${origin.server}" listed ${tools.length} of ${listed.length} tools to fit the model's ${TOOL_COUNT}-tool limit`);
}
- for (const { tool, definition } of staged) {
- registered.set(definition.function.name, tool);
- definitions.push(definition);
+ register(origin, checkedTools(tools));
+ }
+ const direct = directServers(configured.map(({ origin, tools }) => ({ name: origin.server, tools: tools.length })), MCP_TOOL_COUNT - definitions.length);
+ const searched: typeof configured = [];
+ for (const server of configured) {
+ if (signal.aborted || closed) throw aborted();
+ if (!direct.has(server.origin.server)) searched.push(server);
+ else {
+ try { register(server.origin, server.tools); }
+ catch (error) { await skip(server.origin.server, error); continue; }
}
- // 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.
- if (agents) {
- for (const [alias, { tools: targets }] of Object.entries(AGENTS_TOOL_ALIASES)) {
- const listed = staged.find((entry) => targets.includes(entry.tool.name));
- const name = chatToolName(server, alias);
- if (listed && !registered.has(name)) registered.set(name, { ...listed.tool, name: alias, schema: compileToolSchema({ type: "object" }) });
+ budget.servers.push({ name: server.origin.server, tools: server.tools.length, direct: direct.has(server.origin.server) });
+ }
+ if (searched.length) {
+ const entries: CatalogTool[] = [];
+ for (const { origin, tools } of searched) {
+ for (const { tool, schema } of tools) {
+ const name = uniqueName(chatToolName(origin.server, tool.name), (candidate) => catalog.has(candidate));
+ catalog.set(name, { ...origin, name: tool.name, schema });
+ entries.push({ ...tool, name });
}
}
+ directory = new ToolDirectory(entries, { check: (tool, args) => {
+ const validate = catalog.get(tool.name)!.schema;
+ return validate(args) ? undefined : schemaProblems(validate.errors);
+ } });
+ for (const tool of directory.listed({ server: DIRECTORY_SERVER, servers: searched.map(({ origin }) => origin.server) })) {
+ const name = uniqueName(chatToolName(DIRECTORY_SERVER, tool.name as string), (candidate) => registered.has(candidate) || directoryNames.has(candidate));
+ directoryNames.set(name, tool.name as string);
+ definitions.push({ type: "function", function: { name, description: tool.description as string, parameters: tool.inputSchema as Record<string, unknown> } });
+ }
}
+ budget.listed = definitions.length;
if (signal.aborted || closed) throw aborted();
} catch (error) { await close(); throw error; }
const target = (tool: { name: string; searched: boolean }, args: unknown) => tool.searched ? directoryCallTarget(tool.name, args) : tool.name;
+ const excludes = (server: string, runs: string | undefined, runArgs: unknown) => scope !== undefined && runs !== undefined
+ && !allowsTool(scope, { kind: "mcp", server, name: runs }, runArgs);
+ const selectionExcludes = (tool: RegisteredTool, args: unknown) => {
+ const inner = object(args) ? args.arguments ?? {} : {};
+ // A directory mistake ran nothing and must not end the turn as a failed call.
+ const directoryTool = tool.searched && isDirectoryTool(tool.name);
+ // Security: should a bridged agents server answer here, use_tool is also judged by the tool it names.
+ if (!directoryTool && (excludes(tool.server, tool.name, args ?? {}) || (tool.agents && excludes(tool.server, bridgedCallTarget(tool.name, args), inner)))) return true;
+ return tool.searched && excludes(tool.server, target(tool, args), inner);
+ };
+ const searchedCall = (args: unknown) => {
+ const call = directory && object(args) ? directory.call(args) : undefined;
+ return call && !("answer" in call) ? { tool: catalog.get(call.name)!, args: call.arguments } : undefined;
+ };
const validate = (name: string, args: unknown) => {
if (closed || signal.aborted) throw new ChatToolSessionError("MCP session closed");
+ const listedAs = directoryNames.get(name);
+ if (listedAs) {
+ const call = listedAs === CALL_TOOL ? searchedCall(args) : undefined;
+ if (call && selectionExcludes(call.tool, call.args)) throw new Error("Tool selection excludes this tool");
+ if (!object(args)) throw new Error(ARGUMENTS_MISFIT);
+ return;
+ }
const tool = registered.get(name);
if (!tool) throw new Error("The requested tool was not advertised for this turn");
- const inner = object(args) ? args.arguments ?? {} : {};
- const excluded = (runs: string | undefined, runArgs: unknown = args ?? {}) => scope !== undefined && runs !== undefined
- && !allowsTool(scope, { kind: "mcp", server: tool.server, name: runs }, runArgs);
- // A directory mistake ran nothing and must not end the turn as a failed call.
- const directory = tool.searched && isDirectoryTool(tool.name);
- // Security: should a bridged agents server answer here, use_tool is also judged by the tool it names.
- if (!directory && (excluded(tool.name) || (tool.agents && excluded(bridgedCallTarget(tool.name, args), inner)))) throw new Error("Tool selection excludes this tool");
+ if (selectionExcludes(tool, args)) throw new Error("Tool selection excludes this tool");
omitBlankDefaults(tool.builtInBrowser, tool.name, args);
- if (!object(args) || (!directory && !tool.schema(args))) throw new Error("Tool arguments do not match the advertised input schema; use its required fields and types");
- if (tool.searched && excluded(target(tool, args), inner)) throw new Error("Tool selection excludes this tool");
+ if (!object(args) || (!(tool.searched && isDirectoryTool(tool.name)) && !tool.schema(args))) throw new Error(ARGUMENTS_MISFIT);
+ };
+ const viewOf = (tool: RegisteredTool, args: Record<string, unknown>, title: string): ChatToolCallView => {
+ const runs = target(tool, args);
+ if (runs === undefined || tool.agents) return { title, input: args, ask: false };
+ const grant = !tool.hostComputer ? JSON.stringify([tool.server, tool.launch, runs]) : undefined;
+ if (!tool.searched || tool.name !== CALL_TOOL) return { title, input: args, ask: true, ...(grant ? { grant } : {}) };
+ return { title: chatToolName(tool.server, runs), input: object(args.arguments) ? args.arguments : {}, ask: true, ...(grant ? { grant } : {}) };
};
const view = (name: string, args: Record<string, unknown>): ChatToolCallView => {
+ if (directoryNames.has(name)) {
+ const call = directoryNames.get(name) === CALL_TOOL ? searchedCall(args) : undefined;
+ return call ? viewOf(call.tool, call.args, chatToolName(call.tool.server, call.tool.name)) : { title: name, input: args, ask: false };
+ }
const tool = registered.get(name);
- const runs = tool ? target(tool, args) : name;
- if (runs === undefined || tool?.agents) return { title: name, input: args, ask: false };
- const grant = tool && !tool.hostComputer ? JSON.stringify([tool.server, tool.launch, runs]) : undefined;
- if (!tool?.searched || tool.name !== CALL_TOOL) return { title: name, input: args, ask: true, ...(grant ? { grant } : {}) };
- return { title: chatToolName(tool.server, runs), input: object(args.arguments) ? args.arguments : {}, ask: true, ...(grant ? { grant } : {}) };
+ return tool ? viewOf(tool, args, name) : { title: name, input: args, ask: true };
};
+ const run = async (tool: RegisteredTool, args: Record<string, unknown>, callSignal: AbortSignal): Promise<ChatToolResult> => {
+ try {
+ const result = await tool.client.call("tools/call", { name: tool.name, arguments: args }, AbortSignal.any([signal, callSignal]), callTimeoutMs);
+ if (signal.aborted || callSignal.aborted) throw aborted();
+ if (!object(result) || !Array.isArray(result.content) || (result.isError !== undefined && typeof result.isError !== "boolean")) throw new Error("MCP tool returned an invalid result; execution outcome may be uncertain");
+ observers.get(tool.server)?.returned({ name: tool.name, arguments: args }, result);
+ const parts: string[] = [];
+ const images: ChatImagePart[] = [];
+ let unsupported = 0;
+ for (const item of result.content) {
+ if (!object(item) || typeof item.type !== "string" || (item.type === "text" && typeof item.text !== "string")) throw new Error("MCP tool returned invalid content; execution outcome may be uncertain");
+ if (item.type === "text") parts.push(item.text as string);
+ else if (computerUse && item.type === "image") images.push(chatImage(item));
+ else unsupported += 1;
+ }
+ if (result.structuredContent !== undefined) parts.push(JSON.stringify(result.structuredContent));
+ if (unsupported) parts.unshift(`[${unsupported} unsupported MCP content item(s) omitted. The operation may have taken effect, but its full result cannot be represented; inspect its state before retrying.]`);
+ return { text: boundedText(parts.join("\n") || (images.length ? "Screenshot captured." : "(empty result)")), ok: result.isError !== true && unsupported === 0,
+ ...(images.length ? { images } : {}) };
+ } catch (error) {
+ await close();
+ throw new ChatToolSessionError(error instanceof Error ? error.message : "MCP transport failed; execution outcome may be uncertain");
+ }
+ };
+ const answer = (result: DirectoryResult): ChatToolResult => ({ text: boundedText(result.content.map((part) => part.text).join("\n")), ok: result.isError !== true });
return {
- definitions, skipped, trimmed, validate, view, close,
+ definitions, skipped, trimmed, budget, validate, view, close,
async execute(name, args, callSignal) {
validate(name, args);
if (callSignal.aborted) { await close(); throw aborted(); }
- const tool = registered.get(name)!;
- try {
- const result = await tool.client.call("tools/call", { name: tool.name, arguments: args }, AbortSignal.any([signal, callSignal]), callTimeoutMs);
- if (signal.aborted || callSignal.aborted) throw aborted();
- if (!object(result) || !Array.isArray(result.content) || (result.isError !== undefined && typeof result.isError !== "boolean")) throw new Error("MCP tool returned an invalid result; execution outcome may be uncertain");
- observers.get(tool.server)?.returned({ name: tool.name, arguments: args }, result);
- const parts: string[] = [];
- const images: ChatImagePart[] = [];
- let unsupported = 0;
- for (const item of result.content) {
- if (!object(item) || typeof item.type !== "string" || (item.type === "text" && typeof item.text !== "string")) throw new Error("MCP tool returned invalid content; execution outcome may be uncertain");
- if (item.type === "text") parts.push(item.text as string);
- else if (computerUse && item.type === "image") images.push(chatImage(item));
- else unsupported += 1;
- }
- if (result.structuredContent !== undefined) parts.push(JSON.stringify(result.structuredContent));
- if (unsupported) parts.unshift(`[${unsupported} unsupported MCP content item(s) omitted. The operation may have taken effect, but its full result cannot be represented; inspect its state before retrying.]`);
- return { text: boundedText(parts.join("\n") || (images.length ? "Screenshot captured." : "(empty result)")), ok: result.isError !== true && unsupported === 0,
- ...(images.length ? { images } : {}) };
- } catch (error) {
- await close();
- throw new ChatToolSessionError(error instanceof Error ? error.message : "MCP transport failed; execution outcome may be uncertain");
- }
+ const listedAs = directoryNames.get(name);
+ if (!listedAs) return run(registered.get(name)!, args, callSignal);
+ if (listedAs === SEARCH_TOOL) return answer(await directory!.search(args));
+ if (listedAs === DESCRIBE_TOOL) return answer(directory!.describe(args));
+ const call = directory!.call(args);
+ return "answer" in call ? answer(call.answer) : run(catalog.get(call.name)!, call.arguments, callSignal);
},
};
}
diff --git a/server/drivers/openai-chat-tools.test.ts b/server/drivers/openai-chat-tools.test.ts
index 9b56942738..6a9aba7ea9 100644
--- a/server/drivers/openai-chat-tools.test.ts
+++ b/server/drivers/openai-chat-tools.test.ts
@@ -15,6 +15,7 @@ import { recordEvents } from "../testing/events.ts";
import { catalogServer, CUA_DRIVER_WINDOWS_TOOLS, syntheticToolNames } from "../testing/cua-driver-tools.ts";
import { startFakeHttpMcp } from "../testing/fake-http-mcp-server.ts";
import { whopLikeCatalog } from "../testing/whop-like-catalog.ts";
+import { toolBudgetOf } from "../tool-budgets.ts";
import { GrokDriver } from "./grok.ts";
import { CerebrasDriver } from "./cerebras.ts";
import { MinimaxDriver } from "./minimax.ts";
@@ -1374,6 +1375,18 @@ describe("a turn with the person's Windows computer, the built-in browser and th
message: `"data" listed 2 of 5 tools, "device" listed 0 of 23 tools to fit the model's 128-tool limit; the rest are left out of this turn.` }));
expect(f.recorder.events.some((event) => event.type === "runtime.error")).toBe(false);
});
+
+ it("reaches a configured server past the limit through the tool search, says so in one line, and keeps the bot's tool budget", async () => {
+ const f = await fixture((_body, response) => answer(response));
+ await f.start({ botId: "mira", integrations: integrations(42, { custom: { notes: catalog(syntheticToolNames("note", 14)) } }) });
+ expect(await f.completed()).toMatchObject({ ok: true });
+ const names = f.requests[0].tools!.map((tool) => tool.function.name);
+ expect(names).toHaveLength(118);
+ expect(names.slice(-4)).toEqual(["mcp_search_tools", "mcp_describe_tool", "mcp_call_tool", "ask_user"]);
+ expect(f.recorder.events.filter((event) => event.type === "runtime.notice").map((event) => (event as { message: string }).message))
+ .toEqual([`To fit the model's 128-tool limit, the tools of "notes" are reached through the tool search this turn.`]);
+ expect(toolBudgetOf("mira")).toEqual({ limit: 128, listed: 117, servers: [{ name: "notes", tools: 14, direct: false }] });
+ });
});
describe("a provider that streams whole tool calls without an index", () => {
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index 5ba170bb3d..fe0f864457 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -13,7 +13,8 @@ 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, mountChatTools, trimmedToolsNotice, type ChatToolDefinition, type ChatToolSession, type ChatToolResult } from "./chat-mcp-tools.ts";
+import { ChatToolSessionError, chatToolNotices, mountChatTools, type ChatToolDefinition, type ChatToolSession, type ChatToolResult } from "./chat-mcp-tools.ts";
+import { noteToolBudget } from "../tool-budgets.ts";
import { assertImageTransport, chatImageBudget, chatToolImages, chatUserContent, type ChatContentPart } from "./chat-images.ts";
import { promptHalves, volatileContextNote, withContextNote } from "./prompt-split.ts";
import { createChatToolApproval, refusal } from "./chat-tool-approval.ts";
@@ -644,11 +645,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const scope = parsed.scope;
tools = await mountChatTools(options.tools === false ? undefined : turn.integrations, abort.signal, options.computerUse, scope, turn.mcpCallTimeoutMs,
toolSchemaProfileFor({ url: options.apiUrl, model }));
- for (const { server, reason } of tools.skipped) {
- emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: `MCP server "${server}" was skipped for this turn: ${safeText(reason)}` });
- }
- const trimmedNotice = trimmedToolsNotice(tools.trimmed);
- if (trimmedNotice) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: trimmedNotice });
+ noteToolBudget(turn.botId, tools.budget);
+ for (const message of chatToolNotices(tools)) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });
const questionAllowed = options.tools !== false && 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.
diff --git a/server/host/mcp-servers-host.test.ts b/server/host/mcp-servers-host.test.ts
index cc40f79ac0..163c028daf 100644
--- a/server/host/mcp-servers-host.test.ts
+++ b/server/host/mcp-servers-host.test.ts
@@ -108,3 +108,11 @@ it("never makes a server the own of a deleted bot whose folder was left behind",
it("says it in one plain line per bot", () => {
expect(claimedNotice("Iris", ["blender"])).toBe("The Blender tool only works for Iris, so it's off for your other bots.");
});
+
+it("tests a command server as its bot's turns start it, from that bot's own folder, and any other as any bot's", () => {
+ const { host, data } = setup();
+ expect(host.probeAs({})).toEqual({});
+ expect(host.probeAs({ bot: "paul" })).toEqual({ id: "paul", cwd: data });
+ mkdirSync(join(data, "workspaces", "iris"), { recursive: true });
+ expect(host.probeAs({ bot: "iris" })).toEqual({ id: "iris", cwd: join(data, "workspaces", "iris") });
+});
diff --git a/server/host/mcp-servers-host.ts b/server/host/mcp-servers-host.ts
index 8da54e81ed..5a87b1f01d 100644
--- a/server/host/mcp-servers-host.ts
+++ b/server/host/mcp-servers-host.ts
@@ -56,9 +56,12 @@ export function createMcpServersHost(deps: McpServersHostDeps) {
const configured = (bot: Bot): Record<string, McpServerSpec> => deps.policy(customMcpServers(deps.cfg(), bot.mcpServers, bot.id));
/** None on an AI that starts no servers, and only those its tool selection reaches. */
const started = (bot: Bot): string[] => (deps.startsServers(bot.id) ? Object.keys(configured(bot)).filter((name) => canUseMcpServer(bot.toolScope, name)) : []);
- const start: McpHealthDeps["start"] = deps.start ?? (async (_name, server, botId) => {
+ const asBot = (botId: string) => {
const own = join(deps.dataDir, "workspaces", botId);
- const result = await probeMcpServer({ ...server, enabled: true }, undefined, undefined, { asBot: { id: botId, cwd: existsSync(own) ? own : deps.dataDir } });
+ return { id: botId, cwd: existsSync(own) ? own : deps.dataDir };
+ };
+ const start: McpHealthDeps["start"] = deps.start ?? (async (_name, server, botId) => {
+ const result = await probeMcpServer({ ...server, enabled: true }, undefined, undefined, { asBot: asBot(botId) });
return result.ok ? { ok: true } : { ok: false, error: result.error };
});
const health = createMcpHealth({
@@ -71,6 +74,8 @@ export function createMcpServersHost(deps: McpServersHostDeps) {
return {
health,
+ /** How Test starts a command server: as the turns of its bot, or of any bot. */
+ probeAs: (server: { bot?: string }) => (server.bot ? asBot(server.bot) : {}),
mounted: (bot: Bot): Record<string, McpServerSpec> => health.usable(bot.id, configured(bot)),
prepare: (bot: Bot): Promise<void> => health.prepare(bot.id, started(bot)),
off: (bot: Bot) => health.off(bot.id, started(bot)),
diff --git a/server/index.ts b/server/index.ts
index 6a9f2fae23..87a79cf8e1 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -12535,7 +12535,7 @@ ROUTES.push(createMcpServerRoutes({
fallbackPublicUrl: FALLBACK_PUBLIC_URL,
mcpConfigBusy: { get: () => mcpConfigBusy, set: (busy) => { mcpConfigBusy = busy; } },
mcpServerResponse, mcpPolicyRefusal, persistMcpServers, savedCustomDomain, appCatalog: chatAppsMcp, forgetPeople: (name) => teamConnections.forgetServer(name), health: mcpServersHost.health, botsPath: () => brokerPath(botBox),
- connectionsChanged: (change) => void routineHolds?.connections(change) }));
+ connectionsChanged: (change) => void routineHolds?.connections(change), probeAs: mcpServersHost.probeAs }));
ROUTES.push(createSetupImportRoutes({ local: DESKTOP_MANAGED && !CLOUD_HOME && !HOSTED_WORKSPACE, cfg, mcpPolicyRefusal, persistMcpServers,
mcpConfigBusy: { get: () => mcpConfigBusy, set: (busy) => { mcpConfigBusy = busy; } } }));
ROUTES.push(createComputerRoutes({
diff --git a/server/mcp-directory.ts b/server/mcp-directory.ts
index 242019ba99..f107be124e 100644
--- a/server/mcp-directory.ts
+++ b/server/mcp-directory.ts
@@ -408,6 +408,8 @@ const COMPACTIONS = [
export interface DirectoryContext {
server: string;
+ /** A directory over several servers' tools, named in place of `server`. */
+ servers?: readonly string[];
title?: string;
instructions?: string;
}
@@ -438,7 +440,8 @@ export class ToolDirectory {
}
listed(context: DirectoryContext): Json[] {
- const who = `the "${context.server}" MCP server${context.title && context.title !== context.server ? ` (${oneLine(context.title, 80)})` : ""}`;
+ const who = context.servers?.length ? `the MCP servers ${context.servers.map((server) => `"${server}"`).join(", ")}`
+ : `the "${context.server}" MCP server${context.title && context.title !== context.server ? ` (${oneLine(context.title, 80)})` : ""}`;
const about = oneLine(context.instructions, ABOUT_CHARS);
const nameField = { type: "string", description: `The tool's exact name, as ${SEARCH_TOOL} gave it.` };
return [
diff --git a/server/mcp-probe.test.ts b/server/mcp-probe.test.ts
index 0441172132..c84a3337fb 100644
--- a/server/mcp-probe.test.ts
+++ b/server/mcp-probe.test.ts
@@ -23,6 +23,12 @@ function whopSizedCatalog() {
return tools;
}
+const spawned = vi.hoisted(() => [] as Array<{ opts: { cwd?: unknown; box?: unknown } }>);
+vi.mock("./procs.ts", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("./procs.ts")>();
+ return { ...actual, spawnCli: (...args: Parameters<typeof actual.spawnCli>) => { spawned.push({ opts: args[2] }); return actual.spawnCli(...args); } };
+});
+
const fakeServer = fileURLToPath(new URL("./testing/fake-mcp-server.ts", import.meta.url));
/** Bounded by real time, not a count of turns: a loaded CI runner can need far more turns for the same round trips. */
@@ -55,6 +61,25 @@ describe("custom MCP probe", () => {
});
});
+ it("starts a command as a bot's turn would: in the box, its configured environment vouched for, and from the bot's folder when it is one bot's", async () => {
+ const server = { command: process.execPath, args: ["--experimental-strip-types", fakeServer], env: { OP_SERVICE_ACCOUNT_TOKEN: "ops_synthetic" }, enabled: false };
+ const opts = async (options: Parameters<typeof probeMcpServer>[3]) => {
+ spawned.length = 0;
+ await expect(probeMcpServer(server, 5_000, undefined, options)).resolves.toMatchObject({ ok: true });
+ return spawned[0]!.opts;
+ };
+ const anyBot = await opts({ asBot: {} });
+ expect(anyBot.box).toEqual({ allowEnv: ["OP_SERVICE_ACCOUNT_TOKEN"] });
+ expect(anyBot).not.toHaveProperty("cwd");
+ const folder = mkdtempSync(join(tmpdir(), "omb-probe-bot-"));
+ try {
+ expect(await opts({ asBot: { id: "ada", cwd: folder } })).toMatchObject({ cwd: folder, box: { botId: "ada", allowEnv: ["OP_SERVICE_ACCOUNT_TOKEN"] } });
+ } finally { await removeTempDir(folder); }
+ const plain = await opts({});
+ expect(plain).not.toHaveProperty("box");
+ expect(plain.cwd).toBe(process.cwd());
+ });
+
it("times out a server that never completes initialization", async () => {
await expect(probeMcpServer({
command: process.execPath,
diff --git a/server/mcp-probe.ts b/server/mcp-probe.ts
index 882eaf07ee..13e270a899 100644
--- a/server/mcp-probe.ts
+++ b/server/mcp-probe.ts
@@ -31,8 +31,9 @@ const UNAUTHORIZED = /unauthori[sz]ed|forbidden|not authenticated|authentication
export interface McpProbeOptions {
extension?: boolean;
observe?(info: { tools: unknown[]; uiExtension: "ok" | "refused" | "unknown" }): void;
- /** Start a command server as this bot's AI would: in its box where turns are boxed, from its own folder. */
- asBot?: { id: string; cwd: string };
+ /** Start a command server as a bot's turn would: in the bot box where turns are boxed, its configured environment
+ * passing the box's allow-list, from the bot's own folder when the server is one bot's (`id`). */
+ asBot?: { id?: string; cwd?: string };
/** Reach a URL server as a bot's turn does: at `url` with `fetch` and no headers of its own (the credential broker adds
* them, server/bot-box/broker-probe.ts). A sign-in is still looked for at the server's own address. */
via?: { url: string; fetch: typeof fetch };
@@ -164,10 +165,10 @@ function probeStdioMcpServer(
let child: ReturnType<typeof spawnCli>;
try {
child = spawnCli(server.command, server.args, {
- cwd: options.asBot?.cwd ?? process.cwd(),
+ ...(options.asBot ? (options.asBot.cwd ? { cwd: options.asBot.cwd } : {}) : { cwd: process.cwd() }),
env: probeEnvironment(server),
stdio: ["pipe", "pipe", "pipe"],
- ...(options.asBot ? { box: { botId: options.asBot.id, allowEnv: Object.keys(server.env) } } : {}),
+ ...(options.asBot ? { box: { ...(options.asBot.id ? { botId: options.asBot.id } : {}), allowEnv: Object.keys(server.env) } } : {}),
});
} catch {
resolve({ ok: false, error: publicProbeError("spawn") });
diff --git a/server/mcp-schema-validator.ts b/server/mcp-schema-validator.ts
index 3dc6c4036d..60a44bf23a 100644
--- a/server/mcp-schema-validator.ts
+++ b/server/mcp-schema-validator.ts
@@ -30,6 +30,53 @@ export function compileToolSchema(schema: Record<string, unknown>, options: { al
catch { throw new Error("MCP tool schema could not be validated; check its constraints, formats, and references"); }
}
+/** A configured server's tool schema. Where strict compilation refuses it, its copy without what asserts nothing is
+ * compiled instead, so a refusal still means a constraint this checker cannot hold. */
+export function compileServerToolSchema(schema: Record<string, unknown>): ValidateFunction {
+ try { return compileToolSchema(schema); }
+ catch (error) {
+ const plain = withoutNonAssertions(schema);
+ if (!plain) throw error;
+ return compileToolSchema(plain);
+ }
+}
+
+const DRAFT_07 = "http://json-schema.org/draft-07/schema#";
+/** What tool generators emit that never asserts: OpenAPI's `example`, `discriminator`, `externalDocs` and `xml`, and VS
+ * Code's editor hints. Vendor `x-` extensions too, except the two compileToolSchema checks. */
+const NON_ASSERTIONS = new Set(["example", "discriminator", "externalDocs", "xml", "markdownDescription", "markdownEnumDescriptions", "enumDescriptions"]);
+const CHECKED_EXTENSIONS = new Set(["x-mcp-header", "x-google-enum-descriptions"]);
+const SCHEMA_KEYWORD_MAPS = ["properties", "$defs", "definitions", "dependentSchemas", "patternProperties"];
+
+function localRefsOnly(schema: unknown, depth = 0): boolean {
+ if (Array.isArray(schema)) return schema.every((child) => localRefsOnly(child, depth + 1));
+ if (!isRecord(schema) || depth > 64) return true;
+ if (typeof schema.$ref === "string" && !schema.$ref.startsWith("#/") && schema.$ref !== "#") return false;
+ return Object.values(schema).every((child) => localRefsOnly(child, depth + 1));
+}
+
+/** Embedded `$id`s go too when every `$ref` is a JSON pointer: Effect Schema gives each `unknown` field the same
+ * `"$id": "/schemas/unknown"`, and Ajv refuses a schema holding one id twice. Undefined when nothing would change. */
+function withoutNonAssertions(schema: Record<string, unknown>): Record<string, unknown> | undefined {
+ const dropIds = localRefsOnly(schema);
+ let changed = false;
+ const visit = (node: unknown, depth: number): unknown => {
+ if (Array.isArray(node)) return node.map((child) => visit(child, depth));
+ if (!isRecord(node) || depth > 64) return node;
+ const copy: Json = {};
+ for (const [key, value] of Object.entries(node)) {
+ if (NON_ASSERTIONS.has(key) || (key.startsWith("x-") && !CHECKED_EXTENSIONS.has(key)) || (dropIds && depth > 0 && key === "$id")) { changed = true; continue; }
+ if (SCHEMA_KEYWORD_MAPS.includes(key) && isRecord(value)) copy[key] = Object.fromEntries(Object.entries(value).map(([name, child]) => [name, visit(child, depth + 1)]));
+ else if (SCHEMA_LISTS.includes(key) || SCHEMA_ONE.includes(key)) copy[key] = visit(value, depth + 1);
+ else copy[key] = value;
+ }
+ return copy;
+ };
+ const plain = visit(schema, 0) as Json;
+ if (plain.$schema === DRAFT_07.slice(0, -1)) { plain.$schema = DRAFT_07; changed = true; }
+ return changed ? plain : undefined;
+}
+
export function schemaProblems(errors: readonly ErrorObject[] | null | undefined, max = 8): string[] {
const lines = (errors ?? []).map((error) => {
const where = error.instancePath ? `${error.instancePath.slice(1).replace(/\//g, ".")}: ` : "";
diff --git a/server/routes/mcp-servers.test.ts b/server/routes/mcp-servers.test.ts
index e6491204d4..2cdb045626 100644
--- a/server/routes/mcp-servers.test.ts
+++ b/server/routes/mcp-servers.test.ts
@@ -3,6 +3,7 @@ import { createServer, request as httpRequest, type RequestOptions, type Server
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { fileURLToPath } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import { openCredentialBroker, type CredentialBroker } from "../bot-box/broker.ts";
@@ -13,6 +14,7 @@ import type { TeamConnectionsHost } from "../host/team-connections-host.ts";
import { McpOAuthManager } from "../mcp-oauth.ts";
import { listMcpServers } from "../mcp-registry.ts";
import { startFakeHttpMcp, type FakeHttpMcp } from "../testing/fake-http-mcp-server.ts";
+import { forgetToolBudgets, noteToolBudget } from "../tool-budgets.ts";
import { createMcpServerRoutes } from "./mcp-servers.ts";
import { dispatchRoutes } from "./table.ts";
@@ -25,7 +27,7 @@ afterEach(async () => {
type Bot = { id: string; mcpServers?: string[] };
-async function serve(options: { botsPath?: () => BrokerPath | null; bots?: Bot[]; listed?: Record<string, Record<string, unknown>> } = {}) {
+async function serve(options: { botsPath?: () => BrokerPath | null; bots?: Bot[]; listed?: Record<string, Record<string, unknown>>; probeAs?: (server: { bot?: string }) => { id?: string; cwd?: string } } = {}) {
const cfg: Pick<AppConfig, "mcpServers"> = { mcpServers: {} };
const changes: string[] = [];
let busy = false;
@@ -44,6 +46,7 @@ async function serve(options: { botsPath?: () => BrokerPath | null; bots?: Bot[]
savedCustomDomain: () => null,
connectionsChanged: (change) => { changes.push(change); },
...(options.botsPath ? { botsPath: options.botsPath } : {}),
+ ...(options.probeAs ? { probeAs: options.probeAs } : {}),
});
const active = createServer(async (req, res) => {
const url = new URL(req.url ?? "/", "http://localhost");
@@ -222,3 +225,29 @@ describe.skipIf(process.platform === "win32")("Test, where bots reach URL server
expect(await tested(await brokerPath(), url)).toEqual({ ok: false, error: "Could not reach this address. Check the URL and your network.", reason: "unreachable" });
});
});
+
+describe("a bot's tool budget and a command server's Test", () => {
+ afterEach(() => forgetToolBudgets());
+
+ it("gives a bot's last chat turn's tool budget, nothing before one ran, and not found for no bot", async () => {
+ const { base } = await serve({ bots: [{ id: "ada" }] });
+ expect(await (await fetch(`${base}/api/bots/ada/tool-budget`)).json()).toEqual({ budget: null });
+ const budget = { limit: 128, listed: 127, servers: [{ name: "notes", tools: 124, direct: true }, { name: "sogni", tools: 30, direct: false }] };
+ noteToolBudget("ada", budget);
+ expect(await (await fetch(`${base}/api/bots/ada/tool-budget`)).json()).toEqual({ budget });
+ expect((await fetch(`${base}/api/bots/nobody/tool-budget`)).status).toBe(404);
+ });
+
+ it("starts a command server for Test as its bot's turn would", async () => {
+ const seen: Array<string | undefined> = [];
+ const fake = fileURLToPath(new URL("../testing/fake-mcp-server.ts", import.meta.url));
+ const { cfg, post } = await serve({ probeAs: (server) => { seen.push(server.bot ?? "any bot"); return {}; } });
+ cfg.mcpServers = {
+ notes: { command: process.execPath, args: ["--experimental-strip-types", fake], env: {}, enabled: true },
+ own: { command: process.execPath, args: ["--experimental-strip-types", fake], env: {}, enabled: true, bot: "ada" },
+ };
+ expect(await (await post("/api/mcp/servers/notes/test", {})).json()).toMatchObject({ ok: true, tools: [{ name: "read_notes" }] });
+ expect(await (await post("/api/mcp/servers/own/test", {})).json()).toMatchObject({ ok: true });
+ expect(seen).toEqual(["any bot", "ada"]);
+ });
+});
diff --git a/server/routes/mcp-servers.ts b/server/routes/mcp-servers.ts
index 03b22e139f..a17984689f 100644
--- a/server/routes/mcp-servers.ts
+++ b/server/routes/mcp-servers.ts
@@ -8,6 +8,7 @@ import { brokeredServer, type BrokerPath } from "../bot-box/broker-probe.ts";
import { probeMcpServer, type McpProbeOptions, type McpProbeResult } from "../mcp-probe.ts";
import { MAX_MCP_SERVERS, isRemoteMcpServer, mcpServerBody, mcpServerServes, parseMcpServerMutation, parseMcpServersImport, parseStoredMcpServer, type McpRunsOn, type StoredMcpServer, type StoredRemoteMcpServer } from "../mcp-registry.ts";
import { personKey } from "../person-key.ts";
+import { toolBudgetOf } from "../tool-budgets.ts";
import { postizKeyHeaders } from "../postiz/connection.ts";
import { isLoopbackHost, isProxied, provesSameOrigin, requestOrigin } from "../request-auth.ts";
import type { SessionRegistry } from "../sessions.ts";
@@ -51,6 +52,8 @@ export interface McpServerRouteDeps {
connectionsChanged?(change: "added" | "removed"): void;
/** How bots' turns reach a URL server here: through the credential broker where turns are boxed (null: directly). */
botsPath?(): BrokerPath | null;
+ /** How Test starts a command server: as a bot's turn would (server/mcp-probe.ts `asBot`). */
+ probeAs?(server: { bot?: string }): NonNullable<McpProbeOptions["asBot"]>;
}
/** Where turns are boxed, a URL server is tested the way bots reach it: through the broker. If that fails but the server
@@ -103,6 +106,12 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {
return json(res, 200, withServerDetails(mcpServerResponse()));
}
+ const budgetOf = /^\/api\/bots\/([\w-]+)\/tool-budget$/.exec(path);
+ if (method === "GET" && budgetOf) {
+ if (!deps.bot(budgetOf[1]!)) return json(res, 404, { error: "no such bot" });
+ return json(res, 200, { budget: toolBudgetOf(budgetOf[1]!) ?? null });
+ }
+
const ofBot = /^\/api\/bots\/([\w-]+)\/mcp-servers$/.exec(path);
if (method === "GET" && ofBot) {
const bot = deps.bot(ofBot[1]!);
@@ -149,7 +158,7 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {
const viaBots = isRemoteMcpServer(target) ? deps.botsPath?.() ?? null : null;
const result = viaBots && isRemoteMcpServer(target)
? await probeAsBots(viaBots, name, target, controller.signal, options)
- : await probeMcpServer(target, undefined, controller.signal, options);
+ : await probeMcpServer(target, undefined, controller.signal, isRemoteMcpServer(target) ? options : { ...options, asBot: deps.probeAs?.(target) ?? {} });
if (!result.ok && result.auth === "required" && isRemoteMcpServer(target)) oauth.markNeedsSignIn(name, target.url);
return json(res, 200, result);
} finally {
diff --git a/server/tool-budgets.ts b/server/tool-budgets.ts
new file mode 100644
index 0000000000..2cb3057c81
--- /dev/null
+++ b/server/tool-budgets.ts
@@ -0,0 +1,20 @@
+import type { ToolBudget } from "../shared/tool-budget.ts";
+
+const MAX_BOTS = 1_000;
+const budgets = new Map<string, ToolBudget>();
+
+/** Each bot's last chat-engine turn, kept until the server restarts; past MAX_BOTS the longest-quiet bot goes first. */
+export function noteToolBudget(botId: string | undefined, budget: ToolBudget): void {
+ if (!botId) return;
+ budgets.delete(botId);
+ budgets.set(botId, budget);
+ if (budgets.size > MAX_BOTS) budgets.delete(budgets.keys().next().value!);
+}
+
+export function toolBudgetOf(botId: string): ToolBudget | undefined {
+ return budgets.get(botId);
+}
+
+export function forgetToolBudgets(): void {
+ budgets.clear();
+}
diff --git a/shared/tool-budget.ts b/shared/tool-budget.ts
new file mode 100644
index 0000000000..476684757b
--- /dev/null
+++ b/shared/tool-budget.ts
@@ -0,0 +1,18 @@
+/** The most tools one Chat Completions request may carry: OpenAI-compatible endpoints refuse more than 128. */
+export const CHAT_TOOL_LIMIT = 128;
+
+/** How one bot's last chat-engine turn spent the model's tool limit. */
+export interface ToolBudget {
+ limit: number;
+ /** Tools the model was handed directly, the tool search's own and the built-ins' included. */
+ listed: number;
+ /** The bot's configured MCP servers, in turn order. `direct: false` is a server reached through the tool search. */
+ servers: Array<{ name: string; tools: number; direct: boolean }>;
+}
+
+/** What one server's tool count alone does to a chat-engine turn: past the limit it can only be searched, and from half of
+ * it on it pushes other servers into the search. */
+export function chatToolBudgetFit(tools: number, limit: number = CHAT_TOOL_LIMIT): "fits" | "crowds" | "exceeds" {
+ if (tools >= limit) return "exceeds";
+ return tools * 2 >= limit ? "crowds" : "fits";
+}
diff --git a/src/components/McpServersPanel.limit.test.ts b/src/components/McpServersPanel.limit.test.ts
new file mode 100644
index 0000000000..64a151e065
--- /dev/null
+++ b/src/components/McpServersPanel.limit.test.ts
@@ -0,0 +1,22 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { setLocale } from "@/lib/i18n";
+
+vi.stubGlobal("window", {});
+const { connectedLabel } = await import("./McpServersPanel");
+const tools = (count: number) => Array.from({ length: Math.min(count, 100) }, (_, index) => ({ name: `tool_${index}` }));
+
+beforeEach(() => setLocale("en"));
+
+describe("a passing MCP server test", () => {
+ it("says only Connected for a server that fits beside others", () => {
+ expect(connectedLabel({ tools: tools(26) })).toBe("Connected: 26 tools");
+ });
+
+ it("says when the server alone takes half or more of what some AIs take at once", () => {
+ expect(connectedLabel({ tools: tools(64) })).toBe("Connected: 64 tools. That's 64 of the 128 tools some AIs take at once, so there other MCP servers may be found through tool search instead.");
+ });
+
+ it("says when the server alone has more tools than some AIs take at once", () => {
+ expect(connectedLabel({ tools: tools(100), total: 425 })).toBe("Connected: 425 tools. Some AIs take at most 128 tools at once, so there its tools are found through tool search.");
+ });
+});
diff --git a/src/components/McpServersPanel.tsx b/src/components/McpServersPanel.tsx
index 98fa15f83f..f15b902b68 100644
--- a/src/components/McpServersPanel.tsx
+++ b/src/components/McpServersPanel.tsx
@@ -31,6 +31,7 @@ import { McpServerEditor, type McpServerSubmission } from "./McpServerEditor";
import { isRemoteMcpListing, type McpServerListing } from "./mcp-draft";
import { WHOP_MCP_URL, isWhopServer, whopServerName } from "@/lib/whop-integration";
import { POSTIZ_SERVER } from "../../shared/postiz";
+import { CHAT_TOOL_LIMIT, chatToolBudgetFit } from "../../shared/tool-budget";
import { openBotSettings } from "./bot-panel/panel-link";
export interface ProbeResult {
@@ -82,10 +83,13 @@ function failureReason(server: McpServerListing, result: ProbeResult): string {
return t("mcp.check.keysRefused", { reason, names: new Intl.ListFormat(activeLocale(), { style: "long", type: "conjunction" }).format(server.headerKeys) });
}
-function connectedLabel(result: ProbeResult): string {
+/** The test's answer, with what the server's tool count alone does to an AI that takes a limited number of tools. */
+export function connectedLabel(result: Pick<ProbeResult, "tools" | "total">): string {
const count = Math.max(result.total ?? 0, result.tools?.length ?? 0);
if (!count) return t("mcp.check.connectedNone");
- return count === 1 ? t("mcp.check.connectedOne") : t("mcp.check.connectedMany", { count });
+ const connected = count === 1 ? t("mcp.check.connectedOne") : t("mcp.check.connectedMany", { count });
+ const fit = chatToolBudgetFit(count);
+ return fit === "fits" ? connected : `${connected}. ${t(fit === "exceeds" ? "mcp.check.overLimit" : "mcp.check.crowdsLimit", { count, limit: CHAT_TOOL_LIMIT })}`;
}
export function McpServersPanel({ embedded = false, whopCard = false, hideWhop = false, refreshKey = 0, onWhopConnection }: {
diff --git a/src/components/bot-settings/AccessSection.tsx b/src/components/bot-settings/AccessSection.tsx
index 3edef77d77..df0a0d7a4e 100644
--- a/src/components/bot-settings/AccessSection.tsx
+++ b/src/components/bot-settings/AccessSection.tsx
@@ -17,6 +17,7 @@ import { Switch } from "../SettingsPrimitives";
import { PhoneAppsCard } from "./PhoneAppsCard";
import { ProposalStatus } from "./ProposalStatus";
import { ToolSelectionCard } from "./ToolSelectionCard";
+import { ToolBudgetLine } from "./ToolBudgetLine";
import { useCloudPlan } from "../ProIntroduction";
import { xResearchAction } from "@/lib/cloud-plan";
import { HIGHLEVEL_SLUG } from "@/lib/highlevel-sign-in";
@@ -182,6 +183,7 @@ export function McpServersCard({ bot, patch }: { bot: Bot; patch: (patch: { mcpS
))}
</div>
)}
+ <ToolBudgetLine botId={bot.id} busy={!!bot.busy} />
<div className="mt-3 flex items-center gap-2">
<button type="button" onClick={openPlugins} className="flex items-center gap-1.5 rounded-lg bg-control px-3 py-2 text-[13px] text-ink hover:bg-raised-hover">
<Plus size={14} /> {t("botAccess.mcpAdd")}
diff --git a/src/components/bot-settings/ToolBudgetLine.dom.test.ts b/src/components/bot-settings/ToolBudgetLine.dom.test.ts
new file mode 100644
index 0000000000..575a584f40
--- /dev/null
+++ b/src/components/bot-settings/ToolBudgetLine.dom.test.ts
@@ -0,0 +1,75 @@
+// @vitest-environment happy-dom
+// The tool budget line on a bot's MCP servers card, in a real DOM, against the harness's answer for the bot.
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { setLocale } from "@/lib/i18n";
+import type { ToolBudget } from "../../../shared/tool-budget";
+
+const fixture = vi.hoisted(() => ({ budget: null as ToolBudget | null, asked: [] as string[] }));
+vi.mock("@/state/store", async (importOriginal) => {
+ const original = await importOriginal<typeof import("@/state/store")>();
+ return { ...original, api: (path: string) => { fixture.asked.push(path); return Promise.resolve({ budget: fixture.budget }); } };
+});
+
+const { ToolBudgetLine } = await import("./ToolBudgetLine");
+
+let host: HTMLDivElement;
+let root: Root;
+const render = (busy = false) => flushSync(() => root.render(createElement(ToolBudgetLine, { botId: "scout", busy })));
+const settle = async () => {
+ for (let i = 0; i < 3; i++) await new Promise((resolve) => setTimeout(resolve, 0));
+};
+
+beforeEach(() => {
+ setLocale("en");
+ fixture.budget = null;
+ fixture.asked = [];
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(() => {
+ flushSync(() => root.unmount());
+ host.remove();
+});
+
+describe("a bot's tool budget", () => {
+ it("says how many of its AI's tools the last turn listed, and which servers it found through tool search", async () => {
+ fixture.budget = { limit: 128, listed: 127, servers: [
+ { name: "basicmemory", tools: 12, direct: true }, { name: "sogni", tools: 40, direct: false }, { name: "context7", tools: 2, direct: false },
+ ] };
+ render();
+ await settle();
+ expect(fixture.asked).toEqual(["/api/bots/scout/tool-budget"]);
+ expect(host.querySelector("[data-tool-budget]")?.firstElementChild?.textContent).toBe("Its last turn listed 127 of the 128 tools its AI takes at once.");
+ expect(host.querySelector("[data-tool-budget-searched]")?.textContent).toBe("Found through tool search instead: sogni and context7");
+ });
+
+ it("leaves out the search line when every server was listed, and shows nothing before a turn ran", async () => {
+ fixture.budget = { limit: 128, listed: 20, servers: [{ name: "basicmemory", tools: 12, direct: true }] };
+ render();
+ await settle();
+ expect(host.querySelector("[data-tool-budget]")).not.toBeNull();
+ expect(host.querySelector("[data-tool-budget-searched]")).toBeNull();
+ fixture.budget = null;
+ flushSync(() => root.unmount());
+ root = createRoot(host);
+ render();
+ await settle();
+ expect(host.innerHTML).toBe("");
+ });
+
+ it("reads the budget again when the bot's turn ends, not while it works", async () => {
+ render();
+ await settle();
+ render(true);
+ await settle();
+ expect(fixture.asked).toHaveLength(1);
+ render(false);
+ await settle();
+ expect(fixture.asked).toHaveLength(2);
+ });
+});
diff --git a/src/components/bot-settings/ToolBudgetLine.tsx b/src/components/bot-settings/ToolBudgetLine.tsx
new file mode 100644
index 0000000000..ac8d1548c5
--- /dev/null
+++ b/src/components/bot-settings/ToolBudgetLine.tsx
@@ -0,0 +1,33 @@
+import { useEffect, useState } from "react";
+
+import { activeLocale, t } from "@/lib/i18n";
+import { api } from "@/state/store";
+import type { ToolBudget } from "../../../shared/tool-budget";
+
+export function ToolBudgetView({ budget }: { budget: ToolBudget }) {
+ const searched = budget.servers.filter((server) => !server.direct).map((server) => server.name);
+ return (
+ <div data-tool-budget className="mt-3 text-[12px] text-ink-secondary">
+ <div>{t("botAccess.tools.budget", { listed: budget.listed, limit: budget.limit })}</div>
+ {searched.length > 0 && (
+ <div data-tool-budget-searched className="mt-0.5">
+ {t("botAccess.tools.budgetSearched", { names: new Intl.ListFormat(activeLocale(), { type: "conjunction" }).format(searched) })}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** The bot's last turn on an AI with a tool limit; nothing before one ran. Read again when a turn ends. */
+export function ToolBudgetLine({ botId, busy }: { botId: string; busy: boolean }) {
+ const [budget, setBudget] = useState<ToolBudget | null>(null);
+ useEffect(() => {
+ if (busy) return;
+ let current = true;
+ api(`/api/bots/${encodeURIComponent(botId)}/tool-budget`)
+ .then((result: { budget?: ToolBudget | null }) => { if (current) setBudget(result.budget ?? null); })
+ .catch(() => { if (current) setBudget(null); });
+ return () => { current = false; };
+ }, [botId, busy]);
+ return budget ? <ToolBudgetView budget={budget} /> : null;
+}
diff --git a/src/locales/en.json b/src/locales/en.json
index 4c4330aa86..f763b66581 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -5410,6 +5410,8 @@
"mcp.check.connectedNone": "Connected, but it offers no tools yet.",
"mcp.check.connectedOne": "Connected: 1 tool",
"mcp.check.connectedMany": "Connected: {count} tools",
+ "mcp.check.overLimit": "Some AIs take at most {limit} tools at once, so there its tools are found through tool search.",
+ "mcp.check.crowdsLimit": "That's {count} of the {limit} tools some AIs take at once, so there other MCP servers may be found through tool search instead.",
"mcp.check.failed": "Couldn't connect. {reason}",
"mcp.check.failedOff": "Couldn't connect, so it stays off. {reason}",
"mcp.check.savedOff": "Saved, but off: the test failed. {reason} Your bots can use it once it's on.",
@@ -6289,6 +6291,8 @@
"webPanels.page.cantEmbed": "This page can't be shown inside the app",
"webPanels.page.cantEmbedBody": "Some sites refuse to be embedded. Open it in your browser instead.",
"webPanels.page.refusedBody": "{site} doesn't allow other apps to show it. Open it in your browser instead.",
+ "botAccess.tools.budget": "Its last turn listed {listed} of the {limit} tools its AI takes at once.",
+ "botAccess.tools.budgetSearched": "Found through tool search instead: {names}",
"botAccess.tools.title": "Tool selection",
"botAccess.tools.description": "Advanced: narrow the tools offered to this bot. Existing approvals still apply.",
"botAccess.tools.corrupt": "This bot's saved tool selection is damaged, so the bot can't start. Choose its tools again to fix it.",