Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Chat engine: mount every tool of an MCP server, and use each provider's real tool limit (#4701)
Milind Sonif6af8a06e347
diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.tsindex dff3a03048..5f401e49f9 100644--- a/server/drivers/chat-mcp-tools.test.ts+++ b/server/drivers/chat-mcp-tools.test.ts@@ -5,7 +5,9 @@ import { join } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";import { augmentedPath } from "../env-path.ts";import { MESSAGE_FILE_MAX_BYTES } from "../message-file.ts";+import { Ajv2020 } from "ajv/dist/2020.js";import { ChatToolSessionError, SAVED_RESULTS_FOLDER, SAVED_RESULTS_KEPT, chatToolNotices, directServers, mountChatTools, trimmedToolsNotice, type ChatToolSession } from "./chat-mcp-tools.ts";+import { EXECUTOR_LIKE_TOOLS } from "../testing/executor-like-tools.ts";import type { ToolScope } from "../../shared/tool-scope.ts";import { catalogServer, CUA_DRIVER_WINDOWS_TOOLS, syntheticToolNames } from "../testing/cua-driver-tools.ts";import { startFakeHttpMcp } from "../testing/fake-http-mcp-server.ts";@@ -838,17 +840,21 @@ describe("Chat MCP servers past the tool limit", () => {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"]);+ const PADDED_AUDIT = `if (message.method === "tools/list") {+ reply(message, {tools:[{name:"write",description:"Fixture write",inputSchema:schema}, ...Array.from({length:125}, (_, i) => ({name:"pad_" + (i + 1),description:"Padding",inputSchema:{type:"object"}}))]});+ continue;+ }`;++ it("lists the smallest servers whole, and reaches the biggest through the tool search in the same turn", async () => {+ const audit = fixture(PADDED_AUDIT);+ const { session, signal, names } = await mount({ audit: audit.server, notes: catalog(syntheticToolNames("note", 4)), extra: catalog(syntheticToolNames("extra", 3)) });+ expect(names).toEqual([...syntheticToolNames("notes_note", 4), ...syntheticToolNames("extra_extra", 3), "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(session.budget).toEqual({ limit: 128, listed: 10, servers: [+ { name: "audit", tools: 126, direct: false }, { name: "notes", tools: 4, direct: true }, { name: "extra", tools: 3, direct: true },] });- 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"');+ expect(chatToolNotices(session)).toEqual(['To fit the model\'s 128-tool limit, the tools of "audit" are reached through the tool search this turn.']);+ expect(session.definitions.at(-3)!.function.description).toContain('the MCP servers "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 }" });@@ -865,7 +871,7 @@ describe("Chat MCP servers past the tool limit", () => {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" });+ await expect(session.execute("extra_extra_2", {}, 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);@@ -897,6 +903,7 @@ describe("Chat MCP servers past the tool limit", () => {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([]);+ expect([...directServers([{ name: "big", tools: 9 }, { name: "memory", tools: 5 }, { name: "small", tools: 4 }], 15)]).toEqual(["small", "memory"]);});});@@ -1085,8 +1092,6 @@ describe("Chat MCP schema validation", () => {});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();@@ -1094,14 +1099,25 @@ describe("Chat MCP schema validation", () => {});it.each([- { type: "object", properties: {value:{type:"string",format:"unregistered-format"}} },- { type: "object", properties: {value:{$ref:"https://example.invalid/private-schema"}} },- { type: "object", properties: {value:{type:"string",unrecognizedAssertion: true}} },- { type: "object", properties: {value:{type:"string","x-mcp-header": 5}} },- { type: "object", properties: {value:{type:"string","x-google-enum-descriptions": "not a list"}} },- ])("refuses schemas it cannot validate instead of silently weakening them %#", async (toolSchema) => {- const f = fixture("", toolSchema);- await expectSkipped(f, /schema could not be validated/);+ ["an unknown format", { type: "object", properties: { value: { type: "string", format: "unregistered-format" } }, required: ["value"] }, "lenient"],+ ["an unknown keyword", { type: "object", properties: { value: { type: "string", unrecognizedAssertion: true } }, required: ["value"] }, "lenient"],+ ["a malformed vendor annotation", { type: "object", properties: { value: { type: "string", "x-mcp-header": 5 } }, required: ["value"] }, "object"],+ ["an external $ref", { type: "object", properties: { value: { $ref: "https://example.invalid/private-schema", description: "Value" } }, required: ["value"] }, "object"],+ ["a $ref to a definition it does not hold", { type: "object", properties: { value: { $ref: "#/$defs/missing" } }, required: ["value"] }, "object"],+ ])("mounts a tool whose schema has %s, checks what it can and leaves the rest to the server", async (_label, toolSchema, check) => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ try {+ const f = fixture("", toolSchema);+ const session = await f.mount();+ expect(session.skipped).toEqual([]);+ expect(session.definitions.map((tool) => tool.function.name)).toEqual(["audit_write"]);+ expect(JSON.stringify(session.definitions[0]!.function.parameters)).not.toMatch(/example\.invalid|missing/);+ expect(() => session.validate("audit_write", { value: "ok" })).not.toThrow();+ if (check === "lenient") expect(() => session.validate("audit_write", { value: 7 })).toThrow("input schema");+ else expect(() => session.validate("audit_write", { value: 7 })).not.toThrow();+ await expect(session.execute("audit_write", { value: "ok" }, f.controller.signal)).resolves.toEqual({ ok: true, text: "recorded:ok" });+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('"audit" tool "write": its input schema could not be compiled whole'));+ } finally { warn.mockRestore(); }});it("honors the configured per-call timeout instead of the fixed default", async () => {@@ -1117,3 +1133,165 @@ describe("Chat MCP schema validation", () => {await expect(long.execute("audit_write", { value: "y" }, f.controller.signal)).resolves.toMatchObject({ ok: true, text: "recorded:y" });});});++/** What an OpenAI-compatible provider checks a request's tools against: a function name it accepts, and parameters that are+ * a valid JSON Schema with an object root and no reference it would have to fetch. */+function expectProviderAccepts(session: ChatToolSession) {+ const metaSchema = new Ajv2020({ strict: false });+ for (const { type, function: fn } of session.definitions) {+ expect(type).toBe("function");+ expect(fn.name).toMatch(/^[a-zA-Z0-9_-]{1,64}$/);+ expect(fn.parameters.type).toBe("object");+ expect(metaSchema.validateSchema(fn.parameters), `${fn.name}: ${JSON.stringify(metaSchema.errors)}`).toBe(true);+ for (const ref of JSON.stringify(fn.parameters).match(/"\$ref":"[^"]*"/g) ?? []) expect(ref).toMatch(/^"\$ref":"#/);+ }+}++describe("Chat MCP servers with a schema the checker cannot compile whole", () => {+ async function mountRemote(tools: typeof EXECUTOR_LIKE_TOOLS, name = "executor-2") {+ const remote = await startFakeHttpMcp({ tools });+ const controller = new AbortController(); controllers.push(controller);+ try {+ const session = await mountChatTools({ custom: { [name]: { type: "http", url: remote.url, headers: {} } } }, controller.signal);+ sessions.push(session);+ return { remote, controller, session };+ } catch (error) { await remote.close(); throw error; }+ }++ it("mounts every tool of an Executor gateway, whose skills tool has 2020-12's dependentRequired and no $schema, and enforces it", async () => {+ const { remote, controller, session } = await mountRemote(EXECUTOR_LIKE_TOOLS);+ try {+ expect(session.skipped).toEqual([]);+ expect(chatToolNotices(session)).toEqual([]);+ expect(session.definitions.map((tool) => tool.function.name)).toEqual(EXECUTOR_LIKE_TOOLS.map((tool) => `executor_2_${tool.name}`));+ expect(session.definitions[0]!.function.parameters).toEqual(EXECUTOR_LIKE_TOOLS[0]!.inputSchema);+ expect(() => session.validate("executor_2_skills", {})).not.toThrow();+ expect(() => session.validate("executor_2_skills", { app: "executor", name: "executor" })).not.toThrow();+ expect(() => session.validate("executor_2_skills", { name: "executor" })).toThrow("input schema");+ expect(() => session.validate("executor_2_call", { calls: { path: "tools.github.issues.list", input: {} } })).not.toThrow();+ expect(() => session.validate("executor_2_call", { calls: [] })).toThrow("input schema");+ await expect(session.execute("executor_2_skills", { app: "executor" }, controller.signal)).resolves.toMatchObject({ ok: true });+ expect(remote.calls).toEqual([{ name: "skills", arguments: { app: "executor" } }]);+ expectProviderAccepts(session);+ } finally { await remote.close(); }+ });++ it("mounts every tool when one schema cannot be compiled at all, and leaves that tool's check to the server", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const broken = { name: "broken", description: "References a schema elsewhere", inputSchema: {+ type: "object", properties: { item: { $ref: "https://example.invalid/item.json", description: "The item" }, note: { $ref: "#/$defs/note" } },+ required: ["item"], $defs: { note: { type: "string" } },+ } };+ const { remote, controller, session } = await mountRemote([...EXECUTOR_LIKE_TOOLS, broken]);+ try {+ expect(session.skipped).toEqual([]);+ expect(session.definitions.map((tool) => tool.function.name)).toEqual([...EXECUTOR_LIKE_TOOLS, broken].map((tool) => `executor_2_${tool.name}`));+ expect(session.definitions.at(-1)!.function.parameters).toEqual({+ type: "object", properties: { item: { description: "The item" }, note: { $ref: "#/$defs/note" } }, required: ["item"], $defs: { note: { type: "string" } },+ });+ expect(() => session.validate("executor_2_broken", { item: 7 })).not.toThrow();+ await expect(session.execute("executor_2_broken", { item: { id: 1 } }, controller.signal)).resolves.toMatchObject({ ok: true });+ expect(remote.calls).toEqual([{ name: "broken", arguments: { item: { id: 1 } } }]);+ expect(() => session.validate("executor_2_skills", { name: "executor" })).toThrow("input schema");+ expectProviderAccepts(session);+ } finally { await remote.close(); warn.mockRestore(); }+ });+});++describe("Chat MCP tool limit, fairly shared", () => {+ function catalog(names: readonly string[]) {+ const { dir, server } = catalogServer(names);+ dirs.push(dir);+ return server;+ }+ /** Built-ins of 102 tools, four entries for one URL server, an Executor gateway and a memory server. */+ async function customerTurn(toolLimit?: number | null) {+ const reason = await startFakeHttpMcp({ tools: whopLikeCatalog(12) });+ const executor = await startFakeHttpMcp({ tools: EXECUTOR_LIKE_TOOLS });+ const reasonEntry = { type: "http" as const, url: reason.url, headers: { authorization: "Bearer same-sign-in" } };+ const custom = {+ reason: reasonEntry, "reason-2": { ...reasonEntry }, "reason-3": { ...reasonEntry, headers: { Authorization: "Bearer same-sign-in" } }, "reason-4": { ...reasonEntry },+ "executor-2": { type: "http" as const, url: executor.url, headers: {} },+ basicmemory: catalog(syntheticToolNames("memory", 10)),+ };+ const controller = new AbortController(); controllers.push(controller);+ const closeRemotes = async () => { await reason.close(); await executor.close(); };+ try {+ const session = await mountChatTools({+ localComputer: { ...catalog(CUA_DRIVER_WINDOWS_TOOLS), scope: "local-computer" },+ browser: catalog(syntheticToolNames("agent_browser", 32)),+ agents: catalog(syntheticToolNames("agent", 42)),+ custom,+ }, controller.signal, true, undefined, undefined, undefined, undefined, undefined, toolLimit);+ sessions.push(session);+ return { session, reason, controller, closeRemotes, names: session.definitions.map((tool) => tool.function.name) };+ } catch (error) { await closeRemotes(); throw error; }+ }++ it("mounts one server for entries with the same address and sign-in, keeps the small connectors whole and searches the biggest", async () => {+ const { session, reason, controller, closeRemotes, names } = await customerTurn();+ try {+ expect(session.merged).toEqual([{ server: "reason", same: ["reason-2", "reason-3", "reason-4"] }]);+ expect(session.skipped).toEqual([]);+ expect(session.trimmed).toEqual([]);+ expect(session.budget.servers).toEqual([+ { name: "reason", tools: 12, direct: false }, { name: "executor-2", tools: 6, direct: true }, { name: "basicmemory", tools: 10, direct: true },+ ]);+ expect(names.length + 1).toBeLessThanOrEqual(128);+ expect(names).toEqual(expect.arrayContaining([...syntheticToolNames("basicmemory_memory", 10), "executor_2_skills", "mcp_search_tools", "mcp_call_tool"]));+ expect(names.filter((name) => name.startsWith("reason"))).toEqual([]);+ expect(chatToolNotices(session)).toEqual([+ 'MCP servers "reason-2", "reason-3" and "reason-4" connect to the same address with the same sign-in as "reason", so their tools are listed once, under "reason".',+ 'To fit the model\'s 128-tool limit, the tools of "reason" are reached through the tool search this turn.',+ ]);+ const search = session.definitions.find((tool) => tool.function.name === "mcp_search_tools")!;+ expect(search.function.description).toContain('the MCP servers "reason"');+ const found = JSON.parse((await session.execute("mcp_search_tools", { query: "list payments" }, controller.signal)).text);+ expect(found.matches[0].name).toBe("reason_payments_list");+ const call = { name: "reason_payments_list", arguments: { company_id: "biz_1" } };+ expect(session.view("mcp_call_tool", call)).toMatchObject({ title: "reason_payments_list", input: { company_id: "biz_1" }, ask: true });+ await expect(session.execute("mcp_call_tool", call, controller.signal)).resolves.toMatchObject({ ok: true, text: "remote execution recorded" });+ expect(reason.calls).toEqual([{ name: "payments_list", arguments: { company_id: "biz_1" } }]);+ expectProviderAccepts(session);+ } finally { await closeRemotes(); }+ });++ it("lists every tool directly for a provider that takes any number", async () => {+ const { session, closeRemotes, names } = await customerTurn(null);+ try {+ expect(session.budget).toEqual({ limit: null, listed: names.length, servers: [+ { name: "reason", tools: 12, direct: true }, { name: "executor-2", tools: 6, direct: true }, { name: "basicmemory", tools: 10, direct: true },+ ] });+ expect(names).toHaveLength(28 + 32 + 42 + 12 + 6 + 10);+ expect(names.some((name) => name.startsWith("mcp_"))).toBe(false);+ expect(chatToolNotices(session)).toEqual([expect.stringContaining('"reason-2", "reason-3" and "reason-4"')]);+ } finally { await closeRemotes(); }+ });++ it("lists the turn's tools again within a limit a provider names, and still reaches the rest through the tool search", async () => {+ const { session, controller, closeRemotes } = await customerTurn(null);+ try {+ await session.refit(116);+ const names = session.definitions.map((tool) => tool.function.name);+ expect(names.length).toBeLessThanOrEqual(115);+ expect(session.budget.limit).toBe(116);+ expect(session.budget.servers.filter((server) => !server.direct).map((server) => server.name)).toEqual(["reason", "basicmemory"]);+ await expect(session.execute("mcp_call_tool", { name: "basicmemory_memory_3", arguments: {} }, controller.signal)).resolves.toEqual({ ok: true, text: "ran memory_3" });+ await expect(session.execute("executor_2_search", { query: "issues" }, controller.signal)).resolves.toMatchObject({ ok: true });+ } finally { await closeRemotes(); }+ });++ it("keeps entries with the same address but different sign-ins apart", async () => {+ const remote = await startFakeHttpMcp({ tools: whopLikeCatalog(3) });+ const controller = new AbortController(); controllers.push(controller);+ try {+ const session = await mountChatTools({ custom: {+ work: { type: "http", url: remote.url, headers: { authorization: "Bearer work" } },+ home: { type: "http", url: remote.url, headers: { authorization: "Bearer home" } },+ } }, controller.signal);+ sessions.push(session);+ expect(session.merged).toEqual([]);+ expect(session.budget.servers.map((server) => server.name)).toEqual(["work", "home"]);+ } finally { await remote.close(); }+ });+});diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.tsindex 7922bfad39..6110ee7139 100644--- a/server/drivers/chat-mcp-tools.ts+++ b/server/drivers/chat-mcp-tools.ts@@ -17,10 +17,10 @@ import { CALL_TOOL, DESCRIBE_TOOL, SEARCH_TOOL, ToolDirectory, directoryCallTargimport { 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 { compileServerToolSchema, compileToolSchema, schemaProblems } from "../mcp-schema-validator.ts";-import { fitToolList } from "../mcp-tool-schema.ts";+import { compileToolSchema, schemaProblems, serverToolValidator, type ServerToolCheck } from "../mcp-schema-validator.ts";+import { fitToolList, withoutDanglingReferences } from "../mcp-tool-schema.ts";import { listsComputerTool } from "../computer-tool-list.ts";-import { capToolList, shareToolBudget } from "../tool-count-limit.ts";+import { capToolList, learnToolCountLimit, shareToolBudget, toolCountLimitFromError } 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";@@ -37,13 +37,18 @@ export interface ChatToolCallView { title: string; input: Record<string, unknown/** A dispatched operation may already have taken effect: never retry it through a new round. */export class ChatToolSessionError extends Error {}export interface SkippedChatMcpServer { server: string; reason: string }+/** Configured servers at the same address with the same sign-in as `server`, mounted once under its name. */+export interface MergedChatMcpServers { server: string; same: string[] }/** A built-in server that listed only its first `listed` of `of` tools, so the turn fits the model's tool limit. */export interface TrimmedChatMcpServer { server: string; listed: number; of: number }export interface ChatToolSession {definitions: ChatToolDefinition[];skipped: SkippedChatMcpServer[];trimmed: TrimmedChatMcpServer[];+ merged: MergedChatMcpServers[];budget: ToolBudget;+ /** Lists the turn's tools again within `limit`, after a provider refused that many; started servers keep running. */+ refit(limit: number): Promise<void>;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;@@ -60,10 +65,8 @@ 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 = 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";@@ -252,25 +255,53 @@ export class ChatMcpClient {}}-export function trimmedToolsNotice(trimmed: readonly TrimmedChatMcpServer[]): string | undefined {+export function trimmedToolsNotice(trimmed: readonly TrimmedChatMcpServer[], limit: number | null = CHAT_TOOL_LIMIT): string | undefined {if (!trimmed.length) return undefined;const servers = trimmed.map(({ server, listed, of }) => `"${server}" listed ${listed} of ${of} tools`).join(", ");- return `${servers} to fit the model's ${TOOL_COUNT}-tool limit; the rest are left out of this turn.`;+ return `${servers} to fit the model's ${limit}-tool limit; the rest are left out of this turn.`;+}++function quotedList(names: readonly string[]): string {+ const quoted = names.map((name) => `"${name}"`);+ return quoted.length === 1 ? quoted[0]! : `${quoted.slice(0, -1).join(", ")} and ${quoted.at(-1)}`;+}++export function mergedServersNotice({ server, same }: MergedChatMcpServers): string {+ return `MCP ${same.length === 1 ? "server" : "servers"} ${quotedList(same)} ${same.length === 1 ? "connects" : "connect"} to the same address with the same sign-in as "${server}", so their tools are listed once, under "${server}".`;}export function searchedServersNotice(budget: ToolBudget): string | undefined {- const names = budget.servers.filter((server) => !server.direct).map((server) => `"${server.name}"`);+ 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.`;+ return `To fit the model's ${budget.limit}-tool limit, the tools of ${quotedList(names)} are reached through the tool search this turn.`;+}++/** What the tool limit did to a turn's servers, one line each. */+export function toolLimitNotices(session: Pick<ChatToolSession, "trimmed" | "budget">): string[] {+ return [trimmedToolsNotice(session.trimmed, session.budget.limit), searchedServersNotice(session.budget)].filter((line): line is string => line !== undefined);+}++/** After a provider refused a request for the limit its `error` names, learns that limit under `key` and lists the turn's+ * tools again within it, the runtime's own `runtime` definitions kept after them. The lines say what the limit did;+ * undefined when the refusal was for something else. */+export async function refitChatTools(session: ChatToolSession, error: unknown, key: string, runtime: readonly ChatToolDefinition[]): Promise<string[] | undefined> {+ const limit = toolCountLimitFromError(error);+ if (limit === undefined || limit >= session.definitions.length) return undefined;+ learnToolCountLimit(key, limit);+ console.warn(`chat-mcp: the model takes at most ${limit} tools; listing the turn's tools again within that`);+ const kept = session.definitions.filter((definition) => runtime.includes(definition));+ await session.refit(limit);+ session.definitions.push(...kept);+ return toolLimitNotices(session);}/** 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[] {+export function chatToolNotices(session: Pick<ChatToolSession, "skipped" | "trimmed" | "budget"> & Partial<Pick<ChatToolSession, "merged">>): string[] {return [+ ...(session.merged ?? []).map(mergedServersNotice),...session.skipped.map(({ server, reason }) => `MCP server "${server}" was skipped for this turn: ${reason}`),- trimmedToolsNotice(session.trimmed), searchedServersNotice(session.budget),- ].filter((line): line is string => line !== undefined);+ ...toolLimitNotices(session),+ ];}function preview(bytes: Buffer): string {@@ -336,34 +367,44 @@ function omitBlankDefaults(builtInBrowser: boolean, tool: string, args: unknown)}}-type CheckedTool = { tool: Record<string, unknown> & { name: string; inputSchema: Record<string, unknown> }; schema: ValidateFunction };+type CheckedTool = { tool: Record<string, unknown> & { name: string; inputSchema: Record<string, unknown> }; schema: ValidateFunction; check: ServerToolCheck };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[] {+function checkedTools(tools: readonly unknown[], server: string): 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) };+ const { validate, check } = serverToolValidator(tool.inputSchema);+ if (check !== "full") console.warn(`chat-mcp: "${server}" tool "${tool.name}": its input schema could not be compiled whole, so ${check === "lenient" ? "calls are checked against its lenient copy and the server checks the rest" : "the server alone checks its arguments"}`);+ return { tool: tool as CheckedTool["tool"], schema: validate, check };});}+/** Two configured URL servers are the same when they share the address and every header, the sign-in among them. */+function sameServerKey(server: unknown): string | undefined {+ const remote = remoteMcpSpec(server);+ if (!remote) return undefined;+ const headers = Object.entries(remote.headers).map(([name, value]) => [name.toLowerCase(), value]).sort(([a], [b]) => a! < b! ? -1 : a! > b! ? 1 : 0);+ return JSON.stringify([new URL(remote.url).href, headers]);+}+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. */+/** The configured servers a turn lists whole within `room` tools. When not all fit, the tool search's own tools take their+ * place in the room first, and the smallest servers are listed whole, so the fewest 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) {+ for (const server of [...servers].sort((a, b) => a.tools - b.tools)) {if (server.tools > left) continue;direct.add(server.name);left -= server.tools;@@ -372,9 +413,10 @@ export function directServers(servers: ReadonlyArray<{ name: string; tools: numb}/** Under `schemaProfile` the model reads each tool's schema fitted to its provider; calls are still checked against the full one.- * A tool result over 50KB is saved whole in `resultFolder`, the bot's working folder, after `scrub` masks secrets (see savedOrBounded). */+ * A tool result over 50KB is saved whole in `resultFolder`, the bot's working folder, after `scrub` masks secrets (see savedOrBounded).+ * `toolLimit` is the most tools the provider takes in one request, ask_user included; null when it takes any number. */export async function mountChatTools(integrations: SendTurnInput["integrations"], signal: AbortSignal, computerUse = false, toolScope?: ToolScope, callTimeoutMs: number = DEFAULT_CALL_MS,- schemaProfile?: ToolSchemaProfile, resultFolder?: string, scrub: (text: string) => string = redactSecretsInText): Promise<ChatToolSession> {+ schemaProfile?: ToolSchemaProfile, resultFolder?: string, scrub: (text: string) => string = redactSecretsInText, toolLimit: number | null = CHAT_TOOL_LIMIT): Promise<ChatToolSession> {const parsed = parseToolScope(toolScope);if (!parsed.ok) throw new Error(parsed.error);const scope = parsed.scope;@@ -395,8 +437,15 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]if (integrations?.device && eligible("device")) servers.push(["device", integrations.device]);const builtIns = servers.length;const besideBrowser = servers.some(([, descriptor]) => descriptor === integrations?.browser);+ const merged: MergedChatMcpServers[] = [];+ const firstOf = new Map<string, MergedChatMcpServers>();for (const [name, server] of Object.entries(integrations?.custom ?? {})) {if (!eligible(name)) continue;+ // A selection names each server's tools, so with one every server keeps its own name.+ const key = scope === undefined ? sameServerKey(server) : undefined;+ const first = key === undefined ? undefined : firstOf.get(key);+ if (first) { first.same.push(name); continue; }+ if (key !== undefined) firstOf.set(key, { server: name, same: [] });const remote = remoteMcpSpec(server) !== undefined;const apps = appMountFor(name, { integrations });if (apps && !remote) observers.set(name, new AppObserver(apps));@@ -405,6 +454,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]if (remote) searchable.add(name);servers.push([name, { command: stdio.command, args: stdio.args ?? [], env: stdio.env ?? {} }]);}+ for (const group of firstOf.values()) if (group.same.length) merged.push(group);if (servers.length > 32) throw new Error("MCP server count exceeds the 32-server limit");const clients: ChatMcpClient[] = [];const skipped: SkippedChatMcpServer[] = [];@@ -428,13 +478,13 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]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 budget: ToolBudget = { limit: toolLimit, listed: 0, servers: [] };const register = (origin: ToolOrigin, tools: readonly CheckedTool[]) => {const staged: Array<{ tool: RegisteredTool; definition: ChatToolDefinition }> = [];- for (const { tool, schema } of tools) {+ for (const { tool, schema, check } 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 parameters = { ...(check === "full" ? listed.inputSchema : withoutDanglingReferences(listed.inputSchema)) };const constraints: Record<string, unknown> = {};if (computerUse) {for (const key of ["anyOf", "oneOf", "allOf", "not"]) {@@ -461,67 +511,46 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]}}};- try {- if (signal.aborted) throw aborted();- // Concurrent starts, consumed in config order so names and collision suffixes stay stable.- const mounts = await Promise.allSettled(servers.map(async ([name, descriptor], index) => {- if (signal.aborted || closed) throw aborted();- const client = new ChatMcpClient(descriptor, computerUse, index >= builtIns);- clients.push(client);- started.set(name, client);- const computer = descriptor === integrations?.localComputer;- const keeps = (tool: unknown) => !computer || !object(tool) || typeof tool.name !== "string" || listsComputerTool(tool.name, besideBrowser);- const include = (tool: unknown) => keeps(tool) && (scope === undefined || (object(tool) && typeof tool.name === "string"- && ((searchable.has(name) && isDirectoryTool(tool.name)) || allowsTool(scope, { kind: "mcp", server: name, name: tool.name }))));- const tools = await client.tools(signal, include, searchable.has(name) ? REMOTE_MCP_STARTUP_MS : STARTUP_MS, observers.get(name));- if (!tools.length && scope === undefined && descriptor === integrations?.localComputer) throw new Error("The Local VM listed no tools");- // Harness mounts are known by descriptor, never by a name a configured server could claim. A grant- // 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");- 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 };- }));- 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()) {- if (signal.aborted || closed) throw aborted();- if (index < builtIns) {- if (mount.status === "rejected") throw mount.reason;- offered.push(mount.value);- 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;+ 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 offeredTools: Array<{ origin: ToolOrigin; tools: CheckedTool[] }> = [];+ let configured: Array<{ origin: ToolOrigin; tools: CheckedTool[] }> = [];+ /** Built-ins are listed first, trimmed to their share when they alone overflow; configured servers then fill the room+ * left, and those that do not fit are reached through the tool search. */+ const layout = async (limit: number | null) => {+ definitions.length = 0;+ registered.clear();+ catalog.clear();+ directoryNames.clear();+ directory = undefined;+ trimmed.length = 0;+ Object.assign(budget, { limit, listed: 0, servers: [] });+ const room = limit === null ? Infinity : Math.max(0, limit - RUNTIME_TOOLS);+ const wanted = [...offeredTools, ...configured].reduce((sum, server) => sum + server.tools.length, 0);+ const searchRoom = configured.some((server) => server.tools.length) && wanted > room ? 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)));+ const shares = limit === null ? undefined : shareToolBudget(offeredTools.map(({ origin, tools }, index) => ({ name: String(index), tools: tools.length, agents: origin.agents }))+ .sort((a, b) => Number(b.agents) - Number(a.agents)), room - searchRoom);+ for (const [index, { origin, tools: listed }] of offeredTools.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`);+ console.warn(`chat-mcp: "${origin.server}" listed ${tools.length} of ${listed.length} tools to fit the model's ${limit}-tool limit`);}- register(origin, checkedTools(tools));+ register(origin, tools);}- const direct = directServers(configured.map(({ origin, tools }) => ({ name: origin.server, tools: tools.length })), MCP_TOOL_COUNT - definitions.length);+ const direct = directServers(configured.map(({ origin, tools }) => ({ name: origin.server, tools: tools.length })), room - 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; }+ catch (error) { configured = configured.filter((entry) => entry !== server); await skip(server.origin.server, error); continue; }}budget.servers.push({ name: server.origin.server, tools: server.tools.length, direct: direct.has(server.origin.server) });}@@ -545,6 +574,40 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]}}budget.listed = definitions.length;+ };+ try {+ if (signal.aborted) throw aborted();+ // Concurrent starts, consumed in config order so names and collision suffixes stay stable.+ const mounts = await Promise.allSettled(servers.map(async ([name, descriptor], index) => {+ if (signal.aborted || closed) throw aborted();+ const client = new ChatMcpClient(descriptor, computerUse, index >= builtIns);+ clients.push(client);+ started.set(name, client);+ const computer = descriptor === integrations?.localComputer;+ const keeps = (tool: unknown) => !computer || !object(tool) || typeof tool.name !== "string" || listsComputerTool(tool.name, besideBrowser);+ const include = (tool: unknown) => keeps(tool) && (scope === undefined || (object(tool) && typeof tool.name === "string"+ && ((searchable.has(name) && isDirectoryTool(tool.name)) || allowsTool(scope, { kind: "mcp", server: name, name: tool.name }))));+ const tools = await client.tools(signal, include, searchable.has(name) ? REMOTE_MCP_STARTUP_MS : STARTUP_MS, observers.get(name));+ if (!tools.length && scope === undefined && descriptor === integrations?.localComputer) throw new Error("The Local VM listed no tools");+ // Harness mounts are known by descriptor, never by a name a configured server could claim. A grant+ // 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");+ 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 };+ }));+ for (const [index, mount] of mounts.entries()) {+ if (signal.aborted || closed) throw aborted();+ if (index < builtIns) {+ if (mount.status === "rejected") throw mount.reason;+ offeredTools.push({ origin: mount.value.origin, tools: checkedTools(mount.value.tools, mount.value.origin.server) });+ 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, mount.value.origin.server) }); }+ catch (error) { await skip(mount.value.origin.server, error); }+ }+ await layout(toolLimit);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;@@ -618,7 +681,11 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]};const answer = (result: DirectoryResult): ChatToolResult => ({ text: boundedText(result.content.map((part) => part.text).join("\n")), ok: result.isError !== true });return {- definitions, skipped, trimmed, budget, validate, view, close,+ definitions, skipped, trimmed, merged, budget, validate, view, close,+ async refit(limit) {+ if (closed || signal.aborted) throw new ChatToolSessionError("MCP session closed");+ await layout(limit);+ },async execute(name, args, callSignal) {validate(name, args);if (callSignal.aborted) { await close(); throw aborted(); }diff --git a/server/drivers/openai-chat-tools.test.ts b/server/drivers/openai-chat-tools.test.tsindex f543ff5a73..6bcd734891 100644--- a/server/drivers/openai-chat-tools.test.ts+++ b/server/drivers/openai-chat-tools.test.ts@@ -1410,6 +1410,30 @@ describe("a turn with the person's Windows computer, the built-in browser and th.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 }] });});++ it("lists fewer tools once when the provider names a lower limit, learns it for the next turn, and runs the turn", async () => {+ const f = await fixture((body, response) => {+ if ((body.tools?.length ?? 0) <= 110) return answer(response);+ response.writeHead(400, { "content-type": "application/json" });+ response.end(JSON.stringify({ error: { message: `Invalid 'tools': array too long. Expected an array with maximum length 110, but got an array with length ${body.tools!.length} instead.`, type: "invalid_request_error" } }));+ });+ const warn = console.warn;+ console.warn = () => {};+ try {+ await f.start({ botId: "ines", integrations: integrations(42, { custom: { notes: catalog(syntheticToolNames("note", 14)) } }) });+ expect(await f.completed()).toMatchObject({ ok: true });+ } finally { console.warn = warn; }+ expect(f.requests.map((request) => request.tools!.length)).toEqual([118, 110]);+ expect(f.requests[1].tools!.map((tool) => tool.function.name).slice(-4)).toEqual(["mcp_search_tools", "mcp_describe_tool", "mcp_call_tool", "ask_user"]);+ expect(f.recorder.events).toContainEqual(expect.objectContaining({ type: "runtime.notice",+ message: `To fit the model's 110-tool limit, the tools of "notes" are reached through the tool search this turn.` }));+ expect(f.recorder.events.some((event) => event.type === "runtime.error")).toBe(false);+ expect(toolBudgetOf("ines")).toMatchObject({ limit: 110, servers: [{ name: "notes", tools: 14, direct: false }] });++ await f.start({ botId: "ines", integrations: integrations(42, { custom: { notes: catalog(syntheticToolNames("note", 14)) } }) });+ await f.recorder.until((event) => event.type === "turn.completed" && f.requests.length === 3);+ expect(f.requests[2].tools).toHaveLength(110);+ });});describe("a provider that streams whole tool calls without an index", () => {diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex 3afc3a1fd0..a083fe21e5 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -14,8 +14,9 @@ import { ASK_USER_TOOL, ASK_USER_TOOL_DEFINITION, askQuestionSummary, parseAskQuimport { allowsTool, parseToolScope } from "../../shared/tool-scope.ts";import { redactSecretsInText } from "../redact.ts";import { toolDetailPreview } from "../tool-summary.ts";-import { ChatToolSessionError, chatToolNotices, mountChatTools, type ChatToolDefinition, type ChatToolSession, type ChatToolResult } from "./chat-mcp-tools.ts";+import { ChatToolSessionError, chatToolNotices, mountChatTools, refitChatTools, type ChatToolDefinition, type ChatToolSession, type ChatToolResult } from "./chat-mcp-tools.ts";import { noteToolBudget } from "../tool-budgets.ts";+import { chatToolLimitFor, chatToolLimitKey } from "../tool-count-limit.ts";import { assertImageTransport, chatImageBudget, chatToolImages, chatUserContent, type ChatContentPart } from "./chat-images.ts";import { promptHalves, volatileContextNote, withContextNote } from "./prompt-split.ts";import { createChatToolApproval, refusal } from "./chat-tool-approval.ts";@@ -609,7 +610,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)if (!parsed.ok) throw new Error(parsed.error);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 }), turn.cwd ?? turn.toolResultFolder, safeText);+ toolSchemaProfileFor({ url: options.apiUrl, model }), turn.cwd ?? turn.toolResultFolder, safeText, chatToolLimitFor(options.apiUrl, model));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 });@@ -674,6 +675,14 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)} catch (value) {const error = asError(value);const verdict = classifyError(error);+ // A provider refuses a request with too many tools before running anything: learn its limit and list fewer.+ const refit = streamed || seenCalls.size || abort.signal.aborted ? undefined : await refitChatTools(tools, error, chatToolLimitKey(options.apiUrl, model), [ASK_USER_TOOL_DEFINITION]);+ if (refit) {+ for (const message of refit) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });+ noteToolBudget(turn.botId, tools.budget);+ emit({ ...base(turn.threadId, turnId), type: "turn.retrying", attempt: 1, delayMs: 0, reason: "tool_limit" });+ continue;+ }// A rejected reasoning echo executed nothing upstream, so the stripped resend repeats nothing.if (error instanceof UnsupportedReasoningReplayError && !streamed && !abort.signal.aborted) {reasoningReplayRejected.add(model);diff --git a/server/mcp-schema-validator.ts b/server/mcp-schema-validator.tsindex 60a44bf23a..f0d88cc177 100644--- a/server/mcp-schema-validator.ts+++ b/server/mcp-schema-validator.ts@@ -2,6 +2,9 @@ import { Ajv, type ErrorObject, type ValidateFunction } from "ajv";import { Ajv2020 } from "ajv/dist/2020.js";import formats from "ajv-formats";+const DRAFT_07 = "http://json-schema.org/draft-07/schema#";+const DRAFT_2020_12 = "https://json-schema.org/draft/2020-12/schema";+// A schema is a contract: no coercion, defaults, removed fields or fetched external references.const validatorOptions = {strict: true, allErrors: false, coerceTypes: false, useDefaults: false,@@ -12,12 +15,12 @@ const validatorOptions = {export function compileToolSchema(schema: Record<string, unknown>, options: { allErrors?: boolean; strict?: boolean } = {}): ValidateFunction {const dialect = schema.$schema;- if (dialect !== undefined && dialect !== "http://json-schema.org/draft-07/schema#" && dialect !== "https://json-schema.org/draft/2020-12/schema") {+ if (dialect !== undefined && dialect !== DRAFT_07 && dialect !== DRAFT_2020_12) {throw new Error("MCP tool schema uses an unsupported dialect; use JSON Schema draft-07 or 2020-12");}// One compiler per schema keeps external IDs from resolving against unrelated tools.const settings = { ...validatorOptions, allErrors: options.allErrors === true, strict: options.strict !== false };- const compiler = dialect === "https://json-schema.org/draft/2020-12/schema" ? new Ajv2020(settings) : new Ajv(settings);+ const compiler = dialect === DRAFT_2020_12 ? new Ajv2020(settings) : new Ajv(settings);// ajv-formats is CommonJS and exports the plugin as both module.exports and .default.formats.default(compiler);// GitHub's MCP server tags header-routed arguments with this annotation; it adds no constraint to check.@@ -30,18 +33,34 @@ export function compileToolSchema(schema: Record<string, unknown>, options: { alcatch { 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. */+/** A configured server's tool schema, strictly. MCP (2025-11-25) reads a schema without `$schema` as JSON Schema 2020-12,+ * while older servers write draft-07 without naming it, so such a schema is tried as each. 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 plain = withoutNonAssertions(schema);+ const candidates = [schema, ...(plain ? [plain] : [])]+ .flatMap((candidate) => candidate.$schema === undefined ? [candidate, { ...candidate, $schema: DRAFT_2020_12 }] : [candidate]);+ let refusal: unknown;+ for (const candidate of candidates) {+ try { return compileToolSchema(candidate); }+ catch (error) { refusal ??= error; }}+ throw refusal;+}++/** How much of a server tool's schema OpenMausBot checks a call against before the server checks it: all of it, the+ * lenient copy, or only that the arguments are an object. */+export type ServerToolCheck = "full" | "lenient" | "object";++/** A check for every tool a server lists, so one schema this checker cannot compile never costs the server its other tools.+ * Security: no compiler here loads a schema, so an external `$ref` is never fetched; it leaves the check to the server. */+export function serverToolValidator(schema: Record<string, unknown>): { validate: ValidateFunction; check: ServerToolCheck } {+ try { return { validate: compileServerToolSchema(schema), check: "full" }; }+ catch {}+ const lenient = lenientToolValidator(schema);+ return lenient ? { validate: lenient, check: "lenient" } : { validate: compileToolSchema({ type: "object" }), check: "object" };}-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"]);diff --git a/server/mcp-tool-schema.ts b/server/mcp-tool-schema.tsindex 2d9d992661..31d93699c4 100644--- a/server/mcp-tool-schema.ts+++ b/server/mcp-tool-schema.ts@@ -54,6 +54,44 @@ export function providerSafeInputSchema(schema: unknown): JsonObject {return safe;}+const REFERENCES = new Set(["$ref", "$dynamicRef", "$recursiveRef"]);+const VALUES = new Set(["const", "enum", "default", "examples", "example"]);+const SCHEMA_MAPS = new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);++function resolvesInside(root: JsonObject, ref: string): boolean {+ if (ref === "#") return true;+ if (!ref.startsWith("#/")) return false;+ let node: unknown = root;+ for (const token of ref.slice(2).split("/")) {+ let key: string;+ try { key = decodeURIComponent(token).replace(/~1/g, "/").replace(/~0/g, "~"); } catch { return false; }+ if (!isObject(node) && !Array.isArray(node)) return false;+ if (!Object.hasOwn(node, key)) return false;+ node = (node as Record<string, unknown>)[key];+ }+ return true;+}++/** A tool's parameters as a Chat Completions provider is handed them when OpenMausBot could not compile its schema: a+ * reference the schema does not hold itself is left out, since no provider fetches one and a strict one refuses the whole+ * request over it. The server still checks the call. The same object when nothing dangles. */+export function withoutDanglingReferences(schema: JsonObject): JsonObject {+ let changed = false;+ const visit = (node: unknown, depth: number): unknown => {+ if (Array.isArray(node)) return node.map((child) => visit(child, depth + 1));+ if (!isObject(node) || depth > 64) return node;+ const copy: JsonObject = {};+ for (const [key, value] of Object.entries(node)) {+ if (REFERENCES.has(key) && typeof value === "string" && !resolvesInside(schema, value)) { changed = true; continue; }+ if (SCHEMA_MAPS.has(key) && isObject(value)) copy[key] = Object.fromEntries(Object.entries(value).map(([name, child]) => [name, visit(child, depth + 1)]));+ else copy[key] = VALUES.has(key) ? value : visit(value, depth + 1);+ }+ return copy;+ };+ const kept = visit(schema, 0) as JsonObject;+ return changed ? kept : schema;+}+function toolName(tool: JsonObject): string {return typeof tool.name === "string" && tool.name ? tool.name : "unnamed";}diff --git a/server/testing/executor-like-tools.ts b/server/testing/executor-like-tools.tsnew file mode 100644index 0000000000..30ed0b9820--- /dev/null+++ b/server/testing/executor-like-tools.ts@@ -0,0 +1,77 @@+import type { FakeHttpMcpTool } from "./fake-http-mcp-server.ts";++const callRequest = {+ type: "object",+ properties: { path: { type: "string", description: "An exact path from search." }, input: { description: "The tool's input, matching its input type." } },+ required: ["path", "input"],+ additionalProperties: true,+};++/** The tools an Executor MCP gateway (github.com/UsefulSoftwareCo/executor, Nov 2026) lists, with the input schemas Effect+ * Schema 4.0.1 writes for them: no `$schema`, and `skills` carries 2020-12's `dependentRequired`. */+export const EXECUTOR_LIKE_TOOLS: FakeHttpMcpTool[] = [+ {+ name: "skills",+ description: "List or read the skills apps ship.",+ inputSchema: {+ type: "object",+ properties: {+ app: { type: "string", pattern: "^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$" },+ name: { type: "string" },+ file: { type: "string" },+ version: { type: "string", pattern: "^dpl_[\\s\\S]+$" },+ revision: { type: "string", pattern: "^[a-f0-9]{64}$" },+ accounts: {},+ },+ additionalProperties: true,+ dependentRequired: { name: ["app"], file: ["app", "name"], version: ["app"], revision: ["app"], accounts: ["app"] },+ },+ },+ {+ name: "search",+ description: "Search the tools of the connected apps.",+ inputSchema: {+ type: "object",+ properties: { query: { type: "string" }, namespace: { type: "string" }, limit: { type: "integer", exclusiveMinimum: 0 }, offset: { type: "integer", minimum: 0 } },+ additionalProperties: true,+ },+ },+ {+ name: "describe",+ description: "Describe tools by their exact paths.",+ inputSchema: { type: "object", properties: { paths: { type: "array", items: { type: "string" }, minItems: 1, maxItems: 20 } }, required: ["paths"], additionalProperties: true },+ },+ {+ name: "call",+ description: "Call one tool, or several at once.",+ inputSchema: {+ type: "object",+ properties: { calls: { anyOf: [callRequest, { type: "array", items: callRequest, minItems: 1 }] } },+ required: ["calls"],+ additionalProperties: true,+ },+ },+ {+ name: "execute",+ description: "Run a program against the connected apps.",+ inputSchema: { type: "object", properties: { code: { type: "string", maxLength: 100_000 } }, required: ["code"], additionalProperties: true },+ },+ {+ name: "resume",+ description: "Continue a paused program with the person's answer.",+ inputSchema: {+ type: "object",+ properties: {+ requestId: { anyOf: [{ type: "string", pattern: "^apr_[\\s\\S]+$" }, { type: "string", pattern: "^elc_[\\s\\S]+$" }] },+ response: {+ anyOf: [+ { type: "object", properties: { _meta: { anyOf: [{ type: "object" }, { type: "null" }] }, action: { type: "string", enum: ["accept"] }, content: { type: "object" } }, required: ["action"], additionalProperties: true },+ { type: "object", properties: { _meta: { anyOf: [{ type: "object" }, { type: "null" }] }, action: { type: "string", enum: ["cancel", "decline"] } }, required: ["action"], additionalProperties: true },+ ],+ },+ },+ required: ["requestId", "response"],+ additionalProperties: true,+ },+ },+];diff --git a/server/tool-count-limit.test.ts b/server/tool-count-limit.test.tsindex 6e1adefbb7..4de8ff225a 100644--- a/server/tool-count-limit.test.ts+++ b/server/tool-count-limit.test.ts@@ -1,7 +1,7 @@import { afterEach, describe, expect, it } from "vitest";import {- capToolListResult, forgetToolCountLimits, learnedToolCountLimit, learnToolCountLimit, mcpToolBudget, shareToolBudget, toolCountLimitFromError,+ capToolListResult, chatToolLimitFor, chatToolLimitKey, forgetToolCountLimits, learnedToolCountLimit, learnToolCountLimit, mcpToolBudget, shareToolBudget, toolCountLimitFromError,} from "./tool-count-limit.ts";afterEach(() => forgetToolCountLimits());@@ -70,3 +70,19 @@ describe("a learned limit", () => {expect(learnedToolCountLimit("b")).toBeUndefined();});});++describe("a chat provider's tool limit", () => {+ it("is none for Venice, whose API takes any number of tools, and the common 128 elsewhere", () => {+ expect(chatToolLimitFor("https://api.venice.ai/api/v1", "venice-uncensored")).toBeNull();+ expect(chatToolLimitFor("https://openrouter.ai/api/v1", "openai/gpt-5")).toBe(128);+ expect(chatToolLimitFor("https://api.openai.com/v1", "gpt-5")).toBe(128);+ expect(chatToolLimitFor("https://notvenice.ai.example.com/v1", "m")).toBe(128);+ expect(chatToolLimitFor("not a url", "m")).toBe(128);+ });++ it("is what a refusal taught for that address and model", () => {+ learnToolCountLimit(chatToolLimitKey("https://api.venice.ai/api/v1", "small-model"), 64);+ expect(chatToolLimitFor("https://api.venice.ai/api/v1", "small-model")).toBe(64);+ expect(chatToolLimitFor("https://api.venice.ai/api/v1", "other-model")).toBeNull();+ });+});diff --git a/server/tool-count-limit.ts b/server/tool-count-limit.tsindex 157e3ce66e..c26ff5b532 100644--- a/server/tool-count-limit.ts+++ b/server/tool-count-limit.ts@@ -2,6 +2,8 @@// 128 ("Invalid value for 'tools': maximum number of items is 128."). Under a limit every MCP server of a turn lists at// most its share; the engine's own tools are never trimmed, and a server still answers a call to a tool it left out.+import { CHAT_TOOL_LIMIT } from "../shared/tool-budget.ts";+/** The most tools one MCP server lists for this turn, in the environment of each server the turn hands an engine. */export const TOOL_LIMIT_ENV = "OMB_TOOL_LIMIT";/** The same on OpenMausBot's own MCP endpoints, reached over HTTP. */@@ -116,3 +118,21 @@ export function retryUnderToolLimit(error: unknown, turn: {export function mcpToolBudget(limit: number | undefined, engineTools: number): number | undefined {return limit === undefined ? undefined : Math.max(0, limit - engineTools);}++/** Providers whose API takes any number of tools. Venice serves its models through vLLM, which sets no count, and its+ * chat completions reference names none (https://docs.venice.ai/api-reference/endpoint/chat/completions, read 2026-11-06). */+const UNCOUNTED_HOSTS = /(?:^|\.)venice\.ai$/;++/** The most tools one Chat Completions request to `apiUrl` carries for `model`: the limit a refusal taught, else the+ * provider's own, else the common 128. Null when the provider sets none. */+export function chatToolLimitFor(apiUrl: string, model: string): number | null {+ const learned = learnedToolCountLimit(chatToolLimitKey(apiUrl, model));+ if (learned !== undefined) return learned;+ let host = "";+ try { host = new URL(apiUrl).hostname.toLowerCase(); } catch {}+ return UNCOUNTED_HOSTS.test(host) ? null : CHAT_TOOL_LIMIT;+}++export function chatToolLimitKey(apiUrl: string, model: string): string {+ return `chat ${apiUrl} ${model}`;+}diff --git a/shared/tool-budget.ts b/shared/tool-budget.tsindex 476684757b..33a8db68f0 100644--- a/shared/tool-budget.ts+++ b/shared/tool-budget.ts@@ -3,7 +3,8 @@ 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;+ /** Null when the AI's provider takes any number of tools. */+ limit: number | null;/** 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. */diff --git a/src/components/bot-settings/ToolBudgetLine.dom.test.ts b/src/components/bot-settings/ToolBudgetLine.dom.test.tsindex 575a584f40..96556614d3 100644--- a/src/components/bot-settings/ToolBudgetLine.dom.test.ts+++ b/src/components/bot-settings/ToolBudgetLine.dom.test.ts@@ -48,6 +48,14 @@ describe("a bot's tool budget", () => {expect(host.querySelector("[data-tool-budget-searched]")?.textContent).toBe("Found through tool search instead: sogni and context7");});+ it("shows nothing when the bot's AI takes any number of tools", async () => {+ fixture.budget = { limit: null, listed: 140, servers: [{ name: "basicmemory", tools: 12, direct: true }] };+ render();+ await settle();+ expect(fixture.asked).toEqual(["/api/bots/scout/tool-budget"]);+ expect(host.querySelector("[data-tool-budget]")).toBeNull();+ });+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();diff --git a/src/components/bot-settings/ToolBudgetLine.tsx b/src/components/bot-settings/ToolBudgetLine.tsxindex ac8d1548c5..1777a37ee0 100644--- a/src/components/bot-settings/ToolBudgetLine.tsx+++ b/src/components/bot-settings/ToolBudgetLine.tsx@@ -4,7 +4,7 @@ import { activeLocale, t } from "@/lib/i18n";import { api } from "@/state/store";import type { ToolBudget } from "../../../shared/tool-budget";-export function ToolBudgetView({ budget }: { budget: ToolBudget }) {+export function ToolBudgetView({ budget }: { budget: ToolBudget & { limit: number } }) {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">@@ -29,5 +29,5 @@ export function ToolBudgetLine({ botId, busy }: { botId: string; busy: boolean }.catch(() => { if (current) setBudget(null); });return () => { current = false; };}, [botId, busy]);- return budget ? <ToolBudgetView budget={budget} /> : null;+ return budget?.limit != null ? <ToolBudgetView budget={{ ...budget, limit: budget.limit }} /> : null;}