Skip to content

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

Gemini: fit the MCP tool list to the CLI's size budget

koeria68991787ae2d
diff --git a/server/drivers/agents-mcp-env.ts b/server/drivers/agents-mcp-env.ts
index 4068bf179f..664119a785 100644
--- a/server/drivers/agents-mcp-env.ts
+++ b/server/drivers/agents-mcp-env.ts
@@ -1,10 +1,17 @@
import { TOOL_BRIDGE_ENV } from "./agents-bridge.ts";
import { TOOL_LIMIT_ENV } from "../tool-count-limit.ts";
+import { TOOL_SCHEMA_PROFILE_ENV } from "../tool-schema-profile.ts";
import { DEFER_TOOLS_ENV } from "./agents-claude-defer.ts";
/** The settings the harness gives the agents MCP server, and the only ones a request may carry over HTTP. */
export const AGENTS_MCP_ENV = ["OMB_BOT_ID", "OMB_THREAD_ID", "OMB_EXTERNAL_RUNTIME", "OMB_CHIEF_OF_STAFF",
"OMB_SKILL_AUTHORING_ENABLED", "OMB_SKILL_BURGER", "OMB_MEMORY_ENABLED", "OMB_SHARED_COMPUTERS_ENABLED", "OMB_CLOUD_HOME", "OMB_VOICE_NOTES",
+<<<<<<< HEAD
"OMB_X_RESEARCH", "OMB_RESEARCH", "OMB_TEAM_PEOPLE", "OMB_TEAM_BOARD", "OMB_MAUSBOT", "OMB_COMPUTER_SELECTION", "OMB_ROOM", "OMB_IMAGE_GENERATION", "OMB_MEETINGS", "OMB_APP_HOSTING", "OMB_TOOLS_OFF", "OMB_LOCAL_VM", TOOL_BRIDGE_ENV, TOOL_LIMIT_ENV,
+=======
+ "OMB_X_RESEARCH", "OMB_RESEARCH", "OMB_TEAM_PEOPLE", "OMB_MAUSBOT", "OMB_COMPUTER_SELECTION", "OMB_ROOM", "OMB_IMAGE_GENERATION", "OMB_MEETINGS", "OMB_APP_HOSTING", "OMB_TOOLS_OFF", "OMB_LOCAL_VM", TOOL_BRIDGE_ENV, TOOL_LIMIT_ENV,
+ // The engine's schema profile: the URL form carries it as the stdio proxy's environment does.
+ TOOL_SCHEMA_PROFILE_ENV,
+>>>>>>> 56bac665c (Gemini: fit the MCP tool list to the CLI's size budget)
// Claude's deferred catalog: the URL form carries it as the stdio proxy's environment does.
DEFER_TOOLS_ENV] as const;
diff --git a/server/drivers/agents-mcp.ts b/server/drivers/agents-mcp.ts
index 15932e4f19..ecf6b49d9a 100644
--- a/server/drivers/agents-mcp.ts
+++ b/server/drivers/agents-mcp.ts
@@ -9,6 +9,7 @@ import { callTool, capResult, toolCallContextFromEnv } from "./agents-call.ts";
import { sendToolReceipt } from "./agents-timing.ts";
import type { Json } from "./agents-client.ts";
import { capToolListResult, toolLimitFromEnv } from "../tool-count-limit.ts";
+import { fitToolListForBudget, toolSchemaProfileFromEnv } from "../tool-schema-profile.ts";
/** What the agents server lists for `env`, before any tool limit. */
export function agentsToolList(env: NodeJS.ProcessEnv) {
@@ -21,6 +22,7 @@ export function agentsToolList(env: NodeJS.ProcessEnv) {
export function agentsMcp(env: NodeJS.ProcessEnv): (msg: Json) => Promise<Json | undefined> {
const { available, bridge, listed } = agentsToolList(env);
const limit = toolLimitFromEnv(env);
+ const schemaProfile = toolSchemaProfileFromEnv(env);
const context = toolCallContextFromEnv(env);
const ok = (id: unknown, result: unknown): Json => ({ jsonrpc: "2.0", id, result } as Json);
const rpcErr = (id: unknown, code: number, message: string): Json => ({ jsonrpc: "2.0", id, error: { code, message } } as Json);
@@ -43,7 +45,7 @@ export function agentsMcp(env: NodeJS.ProcessEnv): (msg: Json) => Promise<Json |
case "ping":
return ok(id, {});
case "tools/list":
- return ok(id, capToolListResult({ tools: listed }, limit, (line) => console.warn(`[agents] ${line}`)));
+ return ok(id, capToolListResult({ tools: fitToolListForBudget(listed as Array<{ name: string; inputSchema?: unknown }>, schemaProfile, (line) => console.warn(`[agents] ${line}`)) }, limit, (line) => console.warn(`[agents] ${line}`)));
case "tools/call": {
const called = { name: params.name as string, arguments: (params.arguments ?? {}) as Json };
// Security: past the bridge a use_tool call is a direct call: same unknown-tool check, callTool and result bounds.
diff --git a/server/tool-schema-profile.test.ts b/server/tool-schema-profile.test.ts
index 3e569a52ab..7a4e54958f 100644
--- a/server/tool-schema-profile.test.ts
+++ b/server/tool-schema-profile.test.ts
@@ -6,7 +6,7 @@ import { DATA_TOOLS } from "./data/tools.ts";
import bridgedAgents from "./drivers/agents-catalog-goldens/bridged.tools-list.json" with { type: "json" };
import fullAgents from "./drivers/agents-catalog-goldens/full.tools-list.json" with { type: "json" };
import { createPageSchema, wideSchema } from "./testing/oversized-tool-schema.ts";
-import { fitToolSchema, schemaBytes, toolSchemaProfile, toolSchemaProfileFor, type ToolSchemaProfile } from "./tool-schema-profile.ts";
+import { fitToolListForBudget, fitToolSchema, schemaBytes, toolSchemaProfile, toolSchemaProfileFor, type ToolSchemaProfile } from "./tool-schema-profile.ts";
type Json = Record<string, unknown>;
const MOONSHOT = toolSchemaProfile("moonshot")!;
@@ -151,7 +151,7 @@ describe("which turns carry a schema profile", () => {
});
it("is no other engine or endpoint, so their tool lists are unchanged", () => {
- for (const engine of ["claudeAgent", "codex", "geminiAgent", "grokAgent", "opencodeGo", "qwenAgent", "cursorAgent", "hermesAgent"]) {
+ for (const engine of ["claudeAgent", "codex", "grokAgent", "opencodeGo", "qwenAgent", "cursorAgent", "hermesAgent"]) {
expect(toolSchemaProfileFor({ engine, model: "kimi-k2.6" })).toBeUndefined();
}
expect(toolSchemaProfileFor({ url: "https://api.groq.com/openai/v1", model: "moonshotai/kimi-k2-instruct-0905" })).toBeUndefined();
@@ -162,6 +162,47 @@ describe("which turns carry a schema profile", () => {
});
});
+describe("fitting a tool list to Gemini's list budget", () => {
+ const GEMINI = toolSchemaProfile("gemini")!;
+ const bytes = (list: unknown) => Buffer.byteLength(JSON.stringify(list));
+ const names = (list: Array<{ name: string }>) => list.map((tool) => tool.name);
+
+ it("the Antigravity and Gemini CLI engines carry the profile", () => {
+ expect(toolSchemaProfileFor({ engine: "antigravityAgent" })).toBe(GEMINI);
+ expect(toolSchemaProfileFor({ engine: "geminiAgent" })).toBe(GEMINI);
+ expect(toolSchemaProfileFor({ engine: "claudeAgent" })).toBeUndefined();
+ });
+
+ it("a list under the budget goes out untouched", () => {
+ const tools = [{ name: "small", inputSchema: { type: "object", properties: { id: { type: "string" } } } }];
+ expect(fitToolListForBudget(tools, GEMINI)).toEqual(tools);
+ expect(fitToolListForBudget(tools, undefined)).toEqual(tools);
+ expect(fitToolListForBudget(tools, { ...GEMINI, maxListBytes: undefined })).toEqual(tools);
+ });
+
+ it("the full agents list fits with every tool's name kept", () => {
+ const tools = fullAgents.tools as Array<{ name: string; description: string; inputSchema: Json }>;
+ expect(bytes(tools)).toBeGreaterThan(GEMINI.maxListBytes!);
+ const fitted = fitToolListForBudget(tools, GEMINI);
+ expect(bytes(fitted)).toBeLessThanOrEqual(GEMINI.maxListBytes!);
+ expect(names(fitted)).toEqual(names(tools));
+ });
+
+ it("each tool keeps its required fields and the trimming loses the deep words first", () => {
+ const required = ["id"];
+ const tools = [
+ { name: "wide", required: [], inputSchema: wideSchema(200) as Json },
+ { name: "page", required, inputSchema: createPageSchema() as Json },
+ ];
+ const fitted = fitToolListForBudget(tools, { ...GEMINI, maxListBytes: bytes(tools) / 2 });
+ expect(bytes(fitted)).toBeLessThanOrEqual(bytes(tools) / 2);
+ const page = fitted.find((tool) => tool.name === "page")!;
+ expect(page.required).toEqual(required);
+ expect(Object.keys((page.inputSchema as Json).properties ?? {})).toEqual(Object.keys((tools[1].inputSchema as Json).properties ?? {}));
+ expect(bytes(fitted)).toBeLessThan(bytes(tools));
+ });
+});
+
describe("OpenMausBot's own tools", () => {
const catalogs: Array<[string, ReadonlyArray<{ name: string; inputSchema: unknown }>]> = [
["agents (full)", fullAgents.tools], ["agents (bridged)", bridgedAgents.tools], ["browser", BROWSER_TOOLS],
diff --git a/server/tool-schema-profile.ts b/server/tool-schema-profile.ts
index 840b72ef2f..8db18fe392 100644
--- a/server/tool-schema-profile.ts
+++ b/server/tool-schema-profile.ts
@@ -2,7 +2,7 @@
// still validates every call against its own full schema.
type Json = Record<string, unknown>;
-export type ToolSchemaProfileId = "moonshot";
+export type ToolSchemaProfileId = "moonshot" | "gemini";
export interface ToolSchemaProfile {
id: ToolSchemaProfileId;
@@ -12,6 +12,9 @@ export interface ToolSchemaProfile {
maxDepth: number;
/** The engine inlines local `$ref`s before it sends, so the inlined form is what the provider measures. */
measureInlined: boolean;
+ /** A whole tool list's byte budget for a CLI that shows the model every MCP tool eagerly and silently drops the
+ * largest ones once the turn's whole tool JSON passes a character budget. */
+ maxListBytes?: number;
}
const PROFILES: Record<ToolSchemaProfileId, ToolSchemaProfile> = {
@@ -20,6 +23,11 @@ const PROFILES: Record<ToolSchemaProfileId, ToolSchemaProfile> = {
// https://github.com/morluto/rea/issues/3654. Depth 30 is walle's default (https://github.com/MoonshotAI/walle/blob/main/conf.go).
// Kimi Code inlines every local $ref first (normalizeKimiToolSchema in MoonshotAI/kimi-code packages/kosong).
moonshot: { id: "moonshot", provider: "Kimi", maxSchemaBytes: 12_000, maxDepth: 30, measureInlined: true },
+ // The Antigravity and Gemini CLIs hand the model every MCP tool eagerly and drop the largest ones, largest first, once
+ // the turn's whole tool JSON passes a character budget (about 64K, measured in milind-soni/OpenMausBot#7341): the
+ // agents list alone is about 76K, so its largest tools go missing without any refusal. The budget leaves headroom under
+ // it for the person's own MCP servers; the server still validates every call against its own full schema.
+ gemini: { id: "gemini", provider: "Gemini", maxSchemaBytes: 2_000, maxDepth: 20, measureInlined: false, maxListBytes: 56_000 },
};
export const TOOL_SCHEMA_PROFILE_ENV = "OMB_TOOL_SCHEMA_PROFILE";
@@ -44,6 +52,7 @@ const OPENROUTER_HOST = /(?:^|\.)openrouter\.ai$/;
export function toolSchemaProfileFor(target: { engine?: string; url?: string; model?: string }): ToolSchemaProfile | undefined {
const host = hostOf(target.url);
if (target.engine === "kimiAgent" || MOONSHOT_HOST.test(host)) return PROFILES.moonshot;
+ if (target.engine === "antigravityAgent" || target.engine === "geminiAgent") return PROFILES.gemini;
if (OPENROUTER_HOST.test(host) && /^moonshotai\//i.test(target.model ?? "")) return PROFILES.moonshot;
return undefined;
}
@@ -292,3 +301,50 @@ export function fitToolSchema(schema: Json, profile: ToolSchemaProfile): SchemaF
}
return { outcome: "dropped", bytes: schemaBytes(topLevelOnly(working, 0)), from };
}
+
+/** A whole tool list fitted under `profile.maxListBytes`, undefined when the profile sets no budget. Least loss first,
+ * applied to every tool's schema until the list fits: fewer words deep in, then fewer words, then deep fields collapsed
+ * into typed placeholders, then only the top-level fields. Every tool keeps its name, its own description and its
+ * `required` fields; the server still validates every call against the tool's own full schema. */
+export function fitToolListForBudget<Tool extends { name: string; inputSchema?: unknown }>(
+ tools: readonly Tool[],
+ profile: ToolSchemaProfile | undefined,
+ log?: (line: string) => void,
+): Tool[] {
+ if (!profile?.maxListBytes) return [...tools];
+ const list = [...tools];
+ const schemaOf = (tool: Tool) => isObject(tool.inputSchema) ? (structuredClone(tool.inputSchema) as Json) : undefined;
+ const schemas = new Map(list.map((tool) => [tool, schemaOf(tool)]));
+ const bytesOf = (item: { name: string; inputSchema?: unknown }) =>
+ Buffer.byteLength(JSON.stringify({ ...item, inputSchema: schemas.get(item as Tool) ?? item.inputSchema }) ?? "");
+ const total = () => list.reduce((sum, tool) => sum + bytesOf(tool), 0);
+ const from = total();
+ if (from <= profile.maxListBytes) return list;
+ const budget: number = profile.maxListBytes;
+ const shrink = (schema: Json, step: (schema: Json) => void) => { step(schema); return total() <= budget; };
+ const steps: ReadonlyArray<(schema: Json) => void> = [
+ (schema) => { for (let depth = schemaDepth(schema); depth >= 3; depth -= 1) shortenDescriptions(schema, depth, 0); },
+ (schema) => shortenDescriptions(schema, 0, 300),
+ (schema) => { for (let depth = schemaDepth(schema); depth >= 2; depth -= 1) collapseAt(schema, depth); },
+ (schema) => shortenDescriptions(schema, 0, 120),
+ (schema) => replace(schema, topLevelOnly(schema, 120)),
+ (schema) => replace(schema, topLevelOnly(schema, 0)),
+ ];
+ outer: for (const step of steps) {
+ for (const tool of list) {
+ const schema = schemas.get(tool);
+ if (schema && shrink(schema, step)) break outer;
+ }
+ }
+ const fitted = list.map((tool) => {
+ const schema = schemas.get(tool);
+ return schema ? { ...tool, inputSchema: schema } : tool;
+ });
+ log?.(`fitted the tool list to ${profile.provider}'s list budget (${from} → ${total()} bytes)`);
+ return fitted;
+
+ function replace(schema: Json, top: Json): void {
+ for (const key of Object.keys(schema)) delete schema[key];
+ Object.assign(schema, top);
+ }
+}