Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Antigravity CLI: fit connected apps and the person's servers into the session tool budget (#7715)
Milind Sonib2e66200745d
diff --git a/scripts/testing/antigravity-cli-probe.ts b/scripts/testing/antigravity-cli-probe.tsnew file mode 100644index 0000000000..a427f0dc48--- /dev/null+++ b/scripts/testing/antigravity-cli-probe.ts@@ -0,0 +1,150 @@+// Measures, on this computer, which MCP tools Google's native Antigravity CLI shows its model: one tool alone at sizes+// either side of 950 bytes and up to the budget, many tools at once, long names, a deep profile folder (Windows path+// length), and a session shaped like a bot with connected apps before and after the session budget.+// node scripts/testing/antigravity-cli-probe.ts [--cli <path to antigravity or agy.exe>]+// Without --cli it downloads the CLI the app would install, into a temporary folder. It never uses a sign-in: every run+// has a new temporary home and profile, a made-up API key and a loopback stand-in for the model. Prints one table (also+// to $GITHUB_STEP_SUMMARY); a CLI that cannot be downloaded or opened is reported in one line, and the run still exits 0.+import { appendFileSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++const scratch = mkdtempSync(join(tmpdir(), "agp-"));+const home = join(scratch, "home");+for (const folder of ["home", "data", "appdata", "localappdata"]) mkdirSync(join(scratch, folder), { recursive: true });+process.env.OMB_DATA_DIR = join(scratch, "data");+const cliEnv: NodeJS.ProcessEnv = {+ ...process.env, HOME: home, USERPROFILE: home, APPDATA: join(scratch, "appdata"), LOCALAPPDATA: join(scratch, "localappdata"),+};++const lines: string[] = [];+const say = (line: string) => {+ lines.push(line);+ console.log(line);+};+const finish = (): never => {+ if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${lines.join("\n")}\n`);+ process.exit(0);+};++const { probeAntigravityCli, toolOfBytes } = await import("../../server/testing/antigravity-cli-probe.ts");+type ProbeTool = import("../../server/testing/antigravity-cli-probe.ts").ProbeTool;++async function obtainCli(): Promise<{ path: string; version: string } | string> {+ const given = process.argv.indexOf("--cli");+ if (given > 0 && process.argv[given + 1]) return { path: process.argv[given + 1]!, version: "given" };+ try {+ const { latestAntigravityCliRelease } = await import("../../server/drivers/antigravity-cli-release.ts");+ const { installAntigravityCli } = await import("../../server/drivers/antigravity-cli-install.ts");+ const release = await latestAntigravityCliRelease();+ if (!release) return "Google's update channel offered no CLI release for this platform";+ const installed = await installAntigravityCli(release, { root: join(scratch, "cli") });+ return { path: installed.executablePath, version: release.version };+ } catch (error) {+ return error instanceof Error ? error.message : String(error);+ }+}++const cli = await obtainCli();+say(`## Antigravity CLI tool probe (${process.platform}-${process.arch})`);+if (typeof cli === "string") {+ say(`RESULT: CLI not obtainable: ${cli}`);+ finish();+}+const executable = (cli as { path: string }).path;++let runs = 0;+async function shown(servers: Record<string, readonly ProbeTool[]>, profile?: string) {+ runs += 1;+ const result = await probeAntigravityCli({ executable, profile: profile ?? join(scratch, `p${runs}`), env: cliEnv, servers, settleMs: 3_000, prompt: true });+ const rows = Object.values(result.servers).flat();+ return { result, rows, kept: rows.filter((row) => row.kept), dropped: rows.filter((row) => !row.kept) };+}+const sum = (rows: Array<{ bytes: number }>) => rows.reduce((total, row) => total + row.bytes, 0);++const first = await shown({ probe: [toolOfBytes("one", 965)] });+if (first.result.session !== "ok" || first.result.modelTools === undefined || first.result.modelTools.length === 0) {+ say(`RESULT: could not open a session (CLI ${first.result.version}, session/new: ${first.result.session}, model request ${first.result.modelTools ? "had no tools" : "never came"})`);+ finish();+}+say(`CLI version: ${first.result.version}`);+say("");+say("| run | tools | bytes offered | shown | dropped | largest shown | smallest dropped |");+say("|---|---|---|---|---|---|---|");+const row = (label: string, run: Awaited<ReturnType<typeof shown>>) => say(`| ${label} | ${run.rows.length} | ${sum(run.rows)} | ${run.kept.length} | ${run.dropped.length} | ${run.kept.length ? Math.max(...run.kept.map((tool) => tool.bytes)) : "-"} | ${run.dropped.length ? Math.min(...run.dropped.map((tool) => tool.bytes)) : "-"} |`);++/** One row of the table; a row that fails says why and the rest still run. */+async function attempt(label: string, step: () => Promise<void>): Promise<void> {+ try {+ await step();+ } catch (error) {+ say(`| ${label} | row failed: ${(error instanceof Error ? error.message : String(error)).replace(/\|/g, "/").slice(0, 200)} | | | | | |`);+ }+}++const single: Record<number, boolean> = {};+for (const bytes of [900, 944, 950, 965, 1_000, 2_000, 4_000, 20_000, 50_000]) {+ await attempt(`one tool of ${bytes} B`, async () => {+ const run = await shown({ probe: [toolOfBytes("one", bytes)] });+ single[bytes] = run.kept.length === 1;+ row(`one tool of ${bytes} B`, run);+ });+}+let low = 50_000, high = 62_000;+await attempt("largest single tool shown", async () => {+ while (high - low > 100) {+ const middle = Math.floor((low + high) / 2);+ if ((await shown({ probe: [toolOfBytes("one", middle)] })).kept.length === 1) low = middle; else high = middle;+ }+ say(`| largest single tool shown | 1 | ${low} (dropped at ${high}) | | | | |`);+});+const missing = [965, 1_000, 4_000].filter((bytes) => single[bytes] === false);+say("");+say(`RESULT: ${missing.length+ ? `a tool of ${missing.join(", ")} B alone was NOT shown: a per-tool size limit exists on this platform`+ : `every single tool from 900 B to 50 KB was shown alone and the largest single tool shown was about ${low} B: no per-tool size limit, one budget shared by all tools`}`);+say("");+say("| run | tools | bytes offered | shown | dropped | largest shown | smallest dropped |");+say("|---|---|---|---|---|---|---|");+await attempt("20 tools, 200 B to 4 KB", async () => row("20 tools, 200 B to 4 KB", await shown({ probe: [200, 400, 600, 800, 900, 910, 920, 930, 940, 944, 950, 960, 965, 970, 980, 1_000, 1_500, 2_000, 3_000, 4_000].map((bytes) => toolOfBytes(`g${bytes}`, bytes)) })));+for (const count of [10, 40, 80, 150]) await attempt(`${count} tools of 600 B`, async () => row(`${count} tools of 600 B`, await shown({ probe: Array.from({ length: count }, (_, index) => toolOfBytes(`c${index}`, 600)) })));+await attempt("80 tools, 800 B to 1,590 B", async () => row("80 tools, 800 B to 1,590 B", await shown({ probe: Array.from({ length: 80 }, (_, index) => toolOfBytes(`s${String(index).padStart(2, "0")}`, 800 + index * 10)) })));+const named = (length: number) => (`n${length}_${"x".repeat(length)}`).slice(0, length);+await attempt("tool names", async () => {+ const names = await shown({ probe: [50, 54, 55, 60].map((length) => toolOfBytes(named(length), 900)) });+ say(`| tool names 50/54/55/60 chars (mcp_probe_ + name): shown / dropped by length | 4 | ${sum(names.rows)} | ${names.kept.map((tool) => tool.name.length).join(",") || "none"} | ${names.dropped.map((tool) => tool.name.length).join(",") || "none"} | | |`);+});+await attempt("deep profile", async () => {+ const deep = join(scratch, ...Array.from({ length: 12 }, (_, index) => `deep-profile-folder-${index}`));+ const run = await shown({ probe: Array.from({ length: 5 }, (_, index) => toolOfBytes(`${named(50)}${index}`.slice(-50), 900 + index * 30)) }, deep);+ say(`| deep profile (session ${run.result.session}), definition file paths up to ${run.result.longestPath} chars | 5 | ${sum(run.rows)} | ${run.kept.length} | ${run.dropped.length} | files written: ${run.result.files.length} | |`);+});++await attempt("bot + connected apps", async () => {+ const { workspaceAppsLikeCatalog } = await import("../../server/testing/workspace-apps-like-catalog.ts");+ const { fitToolList } = await import("../../server/mcp-tool-schema.ts");+ const { toolSchemaProfile } = await import("../../server/tool-schema-profile.ts");+ const { agentsToolList } = await import("../../server/drivers/agents-mcp.ts");+ const { TOOL_LIST: BROWSER } = await import("../../server/browser/tools.ts");+ const { DATA_TOOLS } = await import("../../server/data/tools.ts");+ const { sessionToolShares } = await import("../../server/drivers/own-mcp-session-budget.ts");+ const { ANTIGRAVITY_CLI_TOOL_BUDGET, fitToolListToShare } = await import("../../server/tool-list-budget.ts");+ const gemini = toolSchemaProfile("gemini")!;+ const own = [agentsToolList({ OMB_CHIEF_OF_STAFF: "1", OMB_COMPUTER_SELECTION: "1" }).listed, BROWSER, DATA_TOOLS] as ProbeTool[][];+ const apps = fitToolList(workspaceAppsLikeCatalog(), gemini) as ProbeTool[];+ const plain = (tools: readonly ProbeTool[]) => tools.map(({ name, description, inputSchema }) => ({ name, description: description ?? "", inputSchema: inputSchema ?? { type: "object" } }));+ const ownShares = sessionToolShares(own, ANTIGRAVITY_CLI_TOOL_BUDGET).shares;+ const before = await shown({+ agents: plain(fitToolListToShare(own[0]!, ownShares[0]!).tools), browser: plain(fitToolListToShare(own[1]!, ownShares[1]!).tools),+ data: plain(fitToolListToShare(own[2]!, ownShares[2]!).tools), composio: plain(apps),+ });+ row("bot + 74 connected-app tools, own servers budgeted only", before);+ say(`| (dropped there) | | | | ${before.dropped.map((tool) => tool.name).slice(0, 12).join(", ")}${before.dropped.length > 12 ? ", ..." : ""} | | |`);+ const everyShare = sessionToolShares([...own, apps], ANTIGRAVITY_CLI_TOOL_BUDGET).shares;+ row("same, every server budgeted", await shown({+ agents: plain(fitToolListToShare(own[0]!, everyShare[0]!).tools), browser: plain(fitToolListToShare(own[1]!, everyShare[1]!).tools),+ data: plain(fitToolListToShare(own[2]!, everyShare[2]!).tools), composio: plain(fitToolListToShare(apps, everyShare[3]!).tools),+ }));+});+writeFileSync(join(scratch, "summary.md"), `${lines.join("\n")}\n`);+finish();diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.tsindex 9605fdb2d8..9cbf497ae3 100644--- a/server/bot-box/env.test.ts+++ b/server/bot-box/env.test.ts@@ -43,7 +43,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set(["OMB_JEV_API_KEY", "OMB_LAN", "OMB_LICENSE_KEY", "OMB_LINUX_GPU", "OMB_LIVE_PROVIDER", "OMB_LOCAL_VM_UPDATE_WAIT_MS","OMB_LOOPBACK_TRUST", "OMB_LOOP_GUARD", "OMB_LOOP_GUARD_STOP_AT", "OMB_LOOP_GUARD_UNATTENDED_STOP_AT", "OMB_META_API_KEY", "OMB_MODELGO_API_KEY", "OMB_NETLIFY_API_URL", "OMB_OPENAI_API_KEY","OMB_OPENAI_IMAGE_KEY", "OMB_OPENAI_LIVE_KEY", "OMB_OPENAI_LIVE_URL", "OMB_OPENROUTER_API_KEY",- "OMB_OPENROUTER_DECIDER_KEY", "OMB_OWN_MCP_HTTP", "OMB_PERSON_FIRST_MS", "OMB_PHONE_PUSH", "OMB_PHONE_RELAY", "OMB_PHONE_RELAY_URL", "OMB_PHONE_SECRET_PUBLIC_KEY", "OMB_PODMAN_SERVICE", "OMB_PORT", "OMB_SERVES_TUNNEL", "OMB_POSTIZ_API_KEY",+ "OMB_OPENROUTER_DECIDER_KEY", "OMB_OWN_MCP_HTTP", "OMB_SESSION_TOOL_BUDGET", "OMB_PERSON_FIRST_MS", "OMB_PHONE_PUSH", "OMB_PHONE_RELAY", "OMB_PHONE_RELAY_URL", "OMB_PHONE_SECRET_PUBLIC_KEY", "OMB_PODMAN_SERVICE", "OMB_PORT", "OMB_SERVES_TUNNEL", "OMB_POSTIZ_API_KEY","OMB_POSTIZ_CLOUD_URL", "OMB_PROCESS_ID", "OMB_PUBLIC_IPV4", "OMB_PUBLIC_URL", "OMB_PUSH_CREDENTIAL", "OMB_QUOTA_SWITCH","OMB_REPLAY_TOOL_HISTORY", "OMB_ROOM_SESSIONS", "OMB_SAFETY_FLOOR", "OMB_SERVER_COMPILE_CACHE", "OMB_SERVER_NAME","OMB_SERVER_UPDATE_DIR",diff --git a/server/bot-box/env.ts b/server/bot-box/env.tsindex 7b29599568..6b940557cb 100644--- a/server/bot-box/env.ts+++ b/server/bot-box/env.ts@@ -27,6 +27,7 @@ export const BOX_ENV_OMB_NAMES: ReadonlySet<string> = new Set(["OMB_CHIEF_OF_STAFF", "OMB_MAUSBOT", "OMB_SKILL_AUTHORING_ENABLED", "OMB_SKILL_BURGER", "OMB_MEMORY_ENABLED", "OMB_SHARED_COMPUTERS_ENABLED","OMB_VOICE_NOTES", "OMB_X_RESEARCH", "OMB_RESEARCH", "OMB_TEAM_PEOPLE", "OMB_TEAM_BOARD", "OMB_COMPUTER_SELECTION", "OMB_ROOM","OMB_IMAGE_GENERATION", "OMB_MEETINGS", "OMB_APP_HOSTING", "OMB_TOOLS_OFF", "OMB_LOCAL_VM", "OMB_AGENTS_TOOL_BRIDGE", "OMB_AGENTS_DEFER_TOOLS", "OMB_TOOL_LIMIT", "OMB_TOOL_SCHEMA_PROFILE",+ "OMB_TOOL_LIST_SHARE", "OMB_TOOL_LIST_RECORD","OMB_MCP_CONFIG", "OMB_MCP_RESTART", "OMB_MCP_RESULT_BUDGET","OMB_HOOK_URL", "OMB_HOOK_TOKEN_FILE", "OMB_HOOK_TIMEOUT_MS", "OMB_PERMISSION_TOOL_SCOPE","OMB_CONNECTOR_UPSTREAM_URL", "OMB_CONNECTOR_UPSTREAM_HEADERS", "OMB_CONNECTOR_TOKEN", "OMB_CONNECTOR_ALLOWED_TOOLS",diff --git a/server/connector-proxy.ts b/server/connector-proxy.tsindex 0ae1b2d176..43409f3dc6 100644--- a/server/connector-proxy.ts+++ b/server/connector-proxy.ts@@ -19,6 +19,7 @@ import { AUTH_CONFIG_ID } from "../shared/connector-availability.ts";import { fitToolListResult } from "./mcp-tool-schema.ts";import { toolSchemaProfileFromEnv } from "./tool-schema-profile.ts";import { capToolListResult, toolLimitFromEnv } from "./tool-count-limit.ts";+import { toolsListResultForSessionShare } from "./tool-list-share.ts";import { readStdioLines } from "./stdio-lines.ts";type Json = Record<string, unknown>;@@ -267,9 +268,9 @@ function withArgumentNotes(name: string, response: Json, changed: readonly strin}function fittedList(frame: Json): Json {- if ((!SCHEMA_PROFILE && TOOL_LIMIT === undefined) || !("result" in frame)) return frame;+ if (!("result" in frame)) return frame;const log = (line: string) => process.stderr.write(`connector-proxy: ${line}\n`);- return { ...frame, result: capToolListResult(fitToolListResult(frame.result, SCHEMA_PROFILE, log), TOOL_LIMIT, log) };+ return { ...frame, result: toolsListResultForSessionShare(capToolListResult(fitToolListResult(frame.result, SCHEMA_PROFILE, log), TOOL_LIMIT, log), process.env, log) };}/** A refusal that answers the same way every time: an HTTP 4xx other than 429, or a result that is not a list (thediff --git a/server/drivers/own-mcp-http.ts b/server/drivers/own-mcp-http.tsindex b35ac74ecd..ef837cb62f 100644--- a/server/drivers/own-mcp-http.ts+++ b/server/drivers/own-mcp-http.ts@@ -7,7 +7,7 @@// port is the box's bridge to the harness gate (bot-box/harness-gate.ts), which passes /api/internal/ only, and the box// keeps loopback out of its egress proxy (NO_PROXY).import { botBox } from "../bot-box/box.ts";-import { withSessionToolShares } from "./own-mcp-session-budget.ts";+import { withSessionToolBudget } from "./session-tool-budget.ts";import { acpOwnServersOverHttp, ownMcpOverHttp, type AcpMcpServer } from "./turn-mcp.ts";/** "1" turns the URL form on for every engine that can take it; "0" keeps every engine on stdio proxies, the ACP agents@@ -78,11 +78,11 @@ export function acpAgentTakesHttpMcp(init: unknown): boolean {/** The servers a session/new or session/load sends: under `advertised`, OpenMausBot's own as this server's endpoints when* the session's agent takes them, by its `initialize` answer or, for an agent that takes them without saying so, by* `takesUnadvertised`. Deciding here, after `initialize`, lets an agent's first session use the URL form too. An agent- * with a session-wide budget for tool definitions (`toolBudget`, by its `initialize` answer) has OpenMausBot's own servers- * share it out, by URL or stdio alike. */+ * with a session-wide budget for tool definitions (`toolBudget`, by its `initialize` answer) has every server OpenMausBot+ * serves or relays share it out, by URL or stdio alike. */export function acpSessionMcpServers(servers: AcpMcpServer[], transport: AcpOwnMcpTransport, init: unknown,takesUnadvertised?: (init: unknown) => boolean, toolBudget?: (init: unknown) => number | undefined): AcpMcpServer[] {const budget = toolBudget?.(init);- const shared = budget === undefined ? servers : withSessionToolShares(servers, budget);+ const shared = budget === undefined ? servers : withSessionToolBudget(servers, budget);return transport === "advertised" && (acpAgentTakesHttpMcp(init) || takesUnadvertised?.(init) === true) ? acpOwnServersOverHttp(shared) : shared;}diff --git a/server/drivers/own-mcp-session-budget.test.ts b/server/drivers/own-mcp-session-budget.test.tsindex fca706146b..df34e47a02 100644--- a/server/drivers/own-mcp-session-budget.test.ts+++ b/server/drivers/own-mcp-session-budget.test.ts@@ -15,7 +15,7 @@ import { SPAWNED_PROXIES } from "../proxy-paths.ts";import { AGENTS_ENV_HEADER, TOOL_SHARE_HEADER } from "../routes/own-mcp-http-path.ts";import { cliDrops } from "../testing/cli-tool-drop.ts";import {- ANTIGRAVITY_CLI_TOOL_BUDGET, definitionListBytes, fitToolListToShare, PROTECTED_TOOLS, toolListShare, toolListShareProfile, type ListedTool,+ ANTIGRAVITY_CLI_TOOL_BUDGET, definitionListBytes, fitToolListToShare, PROTECTED_TOOLS, toolListFloorBytes, toolListShare, toolListShareProfile, type ListedTool,} from "../tool-list-budget.ts";import { fitToolListForBudget, TOOL_SCHEMA_PROFILE_ENV, toolSchemaProfileFromEnv } from "../tool-schema-profile.ts";import type { SendTurnInput } from "../contracts.ts";@@ -23,6 +23,8 @@ import { agentsToolList } from "./agents-mcp.ts";import { antigravityCliToolBudget } from "./antigravity-acp.ts";import { acpSessionMcpServers } from "./own-mcp-http.ts";import { sessionToolShares, withSessionToolShares } from "./own-mcp-session-budget.ts";+import { UNKNOWN_LIST_RESERVE } from "./session-tool-budget.ts";+import { TOOL_LIST_SHARE_ENV } from "../tool-list-share.ts";import { acpMcpServers, type AcpMcpServer } from "./turn-mcp.ts";const GOLDEN = join(dirname(fileURLToPath(import.meta.url)), "agents-catalog-goldens", "antigravity-cli.tools-list.json");@@ -181,16 +183,17 @@ describe("which sessions share a budget", () => {const sent = acpSessionMcpServers(servers, "advertised", nativeCli, takesUrls, antigravityCliToolBudget);const header = (server: AcpMcpServer, name: string) => ("headers" in server ? server.headers.find((entry) => entry.name === name)?.value : undefined);const agentsSettings = JSON.parse(Buffer.from(header(sent[0]!, AGENTS_ENV_HEADER)!, "base64url").toString("utf8")) as Record<string, string>;- const expected = sessionToolShares([agentsList(CHIEF), catalog(BROWSER_TOOLS), catalog(DATA_TOOLS)], ANTIGRAVITY_CLI_TOOL_BUDGET).shares;+ // The person's server, not relayed by OpenMausBot, is counted at a reserve and sent as it is.+ const expected = sessionToolShares([agentsList(CHIEF), catalog(BROWSER_TOOLS), catalog(DATA_TOOLS), UNKNOWN_LIST_RESERVE], ANTIGRAVITY_CLI_TOOL_BUDGET).shares;expect(toolListShare(agentsSettings[TOOL_SCHEMA_PROFILE_ENV])).toBe(expected[0]);- expect([header(sent[1]!, TOOL_SHARE_HEADER), header(sent[2]!, TOOL_SHARE_HEADER)].map(toolListShare)).toEqual(expected.slice(1));+ expect([header(sent[1]!, TOOL_SHARE_HEADER), header(sent[2]!, TOOL_SHARE_HEADER)].map(toolListShare)).toEqual(expected.slice(1, 3));expect(sent[3]).toBe(notes);});it("reaches each own server as a stdio proxy too, with OMB_OWN_MCP_HTTP=0", () => {const sent = acpSessionMcpServers(servers, "stdio", nativeCli, takesUrls, antigravityCliToolBudget);expect(sent.slice(0, 3).map((server) => toolListShare(envOf(server)[TOOL_SCHEMA_PROFILE_ENV]))).toEqual(- sessionToolShares([agentsList(CHIEF), catalog(BROWSER_TOOLS), catalog(DATA_TOOLS)], ANTIGRAVITY_CLI_TOOL_BUDGET).shares);+ sessionToolShares([agentsList(CHIEF), catalog(BROWSER_TOOLS), catalog(DATA_TOOLS), UNKNOWN_LIST_RESERVE], ANTIGRAVITY_CLI_TOOL_BUDGET).shares.slice(0, 3));});});@@ -215,15 +218,21 @@ describe("on Antigravity, beside the Gemini engines' schema profile", () => {expect((built[3] as { args: string[] }).args[0]).toBe(SPAWNED_PROXIES.mcpGate);});- it("the native CLI: one trim of OpenMausBot's own servers, the session's shares in place of gemini, and the person's gate as it was", () => {+ it("the native CLI: one trim of OpenMausBot's own servers, the session's shares in place of gemini, and the person's gate given the rest", () => {const logged: string[] = [];const sent = acpSessionMcpServers(built, "advertised", nativeCli, () => true, antigravityCliToolBudget);- const shares = sessionToolShares([agentsList(CHIEF), catalog(BROWSER_TOOLS), catalog(DATA_TOOLS)], ANTIGRAVITY_CLI_TOOL_BUDGET).shares;+ // The gate has no record yet: it is set aside what the own lists leave at their shortest.+ const own = [agentsList(CHIEF), catalog(BROWSER_TOOLS), catalog(DATA_TOOLS)];+ const reserve = ANTIGRAVITY_CLI_TOOL_BUDGET - own.reduce((sum, tools) => sum + toolListFloorBytes(tools), 0);+ const shares = sessionToolShares([...own, reserve], ANTIGRAVITY_CLI_TOOL_BUDGET).shares;const agentsSettings = settingsOf(sent[0]!);expect(toolListShare(agentsSettings[TOOL_SCHEMA_PROFILE_ENV])).toBe(shares[0]);- expect([header(sent[1]!, TOOL_SHARE_HEADER), header(sent[2]!, TOOL_SHARE_HEADER)].map(toolListShare)).toEqual(shares.slice(1));+ expect([header(sent[1]!, TOOL_SHARE_HEADER), header(sent[2]!, TOOL_SHARE_HEADER)].map(toolListShare)).toEqual(shares.slice(1, 3));expect(JSON.stringify(sent.slice(0, 3))).not.toContain("gemini");- expect(sent[3]).toBe(built[3]);+ const gate = envOf(sent[3]!);+ expect(Number(gate[TOOL_LIST_SHARE_ENV])).toBe(shares[3]);+ expect(gate[TOOL_SCHEMA_PROFILE_ENV]).toBe("gemini");+ expect({ ...sent[3]!, env: (sent[3] as { env: unknown[] }).env.slice(0, -2) }).toEqual(built[3]);// The agents endpoint under that share serves exactly the session's fit: gemini's own list budget does not run on top.const env = { ...agentsSettings, OMB_HARNESS_URL: HARNESS, OMB_COMMS_TOKEN: "comms" };const served = agentsToolList(env).listed as ListedTool[];diff --git a/server/drivers/own-mcp-session-budget.ts b/server/drivers/own-mcp-session-budget.tsindex 74b9fd1aa3..51b47bb440 100644--- a/server/drivers/own-mcp-session-budget.ts+++ b/server/drivers/own-mcp-session-budget.ts@@ -1,10 +1,9 @@-// One session's MCP tool budget shared out among OpenMausBot's own servers in it: the least cut that-// brings all of them under the budget together is found here, when the session's servers are sent, and each server gets-// what its list comes to at that cut plus its part of what is left, as its OMB_TOOL_SCHEMA_PROFILE. Each server then fits-// the list it really serves into that share: a browser engine listing more than the estimate here only cuts its own.-// The agents list is sized exactly; the others by the catalogs their endpoints serve (email and phone show fewer when-// the bot may use fewer, and agent-browser's own list replaces the browser catalog). The person's servers and the-// connected-apps server are not ours to trim and are not sized: their lists are only known once they answer.+// OpenMausBot's own servers in one session's MCP tool budget: the least cut that brings every sized list under the+// budget together is found when the session's servers are sent, and each own server gets what its list comes to at that+// cut plus its part of what is left, as its OMB_TOOL_SCHEMA_PROFILE. Each server then fits the list it really serves into+// that share: a browser engine listing more than the estimate here only cuts its own. The agents list is sized exactly;+// the others by the catalogs their endpoints serve (email and phone show fewer when the bot may use fewer, and+// agent-browser's own list replaces the browser catalog).import { TOOL_LIST as BROWSER_TOOLS } from "../browser/tools.ts";import { CLOUD_COMPUTER_TOOLS } from "../cloud-computer-tools.ts";import { DATA_TOOLS } from "../data/tools.ts";@@ -33,12 +32,14 @@ export interface SessionShares {fits: boolean;}-/** Shares of `budget` for `lists`: each list's bytes at the least cut that fits them all, plus its part of the rest. With- * no cut that fits, each gets its part of the budget by its size at its shortest, and fits what it can. */-export function sessionToolShares(lists: ReadonlyArray<readonly ListedTool[]>, budget: number): SessionShares {- const compacted = lists.map((tools) => withCompactSchemas(tools));- const { level, fits } = descriptionLevelFor(compacted.flat(), budget);- const sizes = compacted.map((tools) => definitionListBytes(withDescriptionLevel(tools, level)));+/** Shares of `budget` for `lists`: each list's bytes at the least cut that fits them all, plus its part of the rest. A+ * number stands for a list known only by the bytes set aside for it, which no cut changes. With no cut that fits, each+ * gets its part of the budget by its size at its shortest, and fits what it can. */+export function sessionToolShares(lists: ReadonlyArray<readonly ListedTool[] | number>, budget: number): SessionShares {+ const reserved = lists.reduce<number>((sum, list) => sum + (typeof list === "number" ? list : 0), 0);+ const compacted = lists.map((tools) => (typeof tools === "number" ? [] : withCompactSchemas(tools)));+ const { level, fits } = descriptionLevelFor(compacted.flat(), budget - reserved);+ const sizes = lists.map((list, index) => (typeof list === "number" ? list : definitionListBytes(withDescriptionLevel(compacted[index]!, level))));const bytes = sizes.reduce((sum, size) => sum + size, 0);if (bytes === 0) return { shares: sizes, bytes, fits };const room = fits ? budget - bytes : budget;@@ -56,21 +57,32 @@ function ownKind(server: AcpMcpServer): { kind: OwnKind; env: Record<string, strreturn kind === "agents" || (kind !== undefined && kind in CATALOGS) ? { kind: kind as OwnKind, env } : null;}+/** The tools one of OpenMausBot's own servers lists before any share; null for any other server. */+export function ownServerToolList(server: AcpMcpServer): readonly ListedTool[] | null {+ const own = ownKind(server);+ if (!own) return null;+ return own.kind === "agents" ? agentsToolList({ ...own.env, [TOOL_SCHEMA_PROFILE_ENV]: undefined }).listed as ListedTool[] : CATALOGS[own.kind];+}++/** One of OpenMausBot's own stdio servers with `share` as its OMB_TOOL_SCHEMA_PROFILE, any earlier profile replaced. */+export function withOwnShare(server: AcpMcpServer, share: number): AcpMcpServer {+ if (!("command" in server)) return server;+ const env = server.env.filter(({ name }) => name !== TOOL_SCHEMA_PROFILE_ENV);+ return { ...server, env: [...env, { name: TOOL_SCHEMA_PROFILE_ENV, value: toolListShareProfile(share) }] };+}+/** `servers` with each of OpenMausBot's own servers given its share of `budget`; every other server as it was. */export function withSessionToolShares(servers: AcpMcpServer[], budget: number, log: (line: string) => void = (line) => console.warn(line)): AcpMcpServer[] {- const own = servers.map((server) => ({ server, own: ownKind(server) })).filter((entry) => entry.own !== null);+ const own = servers.map((server) => ({ server, tools: ownServerToolList(server) })).filter((entry) => entry.tools !== null);if (!own.length) return servers;- const lists = own.map(({ own: found }) => (found!.kind === "agents" ? agentsToolList({ ...found!.env, [TOOL_SCHEMA_PROFILE_ENV]: undefined }).listed as ListedTool[] : CATALOGS[found!.kind as HarnessMcpKind]));- const { shares, bytes, fits } = sessionToolShares(lists, budget);+ const { shares, bytes, fits } = sessionToolShares(own.map(({ tools }) => tools!), budget);if (!fits) {const others = servers.filter((server) => !own.some((entry) => entry.server === server)).map((server) => server.name);- log(`[mcp] this session's own MCP tools (${own.map(({ own: found }) => found!.kind).join(", ")}) come to ${bytes} bytes at their shortest, ${bytes - budget} over the ${budget}-byte tool budget; the engine leaves out its largest tools first${others.length ? ` (${others.join(", ")} not counted)` : ""}`);+ log(`[mcp] this session's own MCP tools (${own.map(({ server }) => server.name).join(", ")}) come to ${bytes} bytes at their shortest, ${bytes - budget} over the ${budget}-byte tool budget; the engine leaves out its largest tools first${others.length ? ` (${others.join(", ")} not counted)` : ""}`);}const shareOf = new Map(own.map(({ server }, index) => [server, shares[index]!]));return servers.map((server) => {const share = shareOf.get(server);- if (share === undefined || !("command" in server)) return server;- const env = server.env.filter(({ name }) => name !== TOOL_SCHEMA_PROFILE_ENV);- return { ...server, env: [...env, { name: TOOL_SCHEMA_PROFILE_ENV, value: toolListShareProfile(share) }] };+ return share === undefined ? server : withOwnShare(server, share);});}diff --git a/server/drivers/session-tool-budget.test.ts b/server/drivers/session-tool-budget.test.tsnew file mode 100644index 0000000000..c52644b6f7--- /dev/null+++ b/server/drivers/session-tool-budget.test.ts@@ -0,0 +1,199 @@+// The native Antigravity CLI's session budget over every server of a session: OpenMausBot's own, the connected apps and+// the person's own servers behind OpenMausBot's relays. The CLI leaves out a session's largest tools first once their+// definitions pass its budget (kept about 58,700 bytes of ~100 tools on 1.5.16 to 1.5.18), which reads as "every tool+// over about 950 bytes is dropped" once a connected-apps server adds dozens of tools.+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { TOOL_LIST as BROWSER_TOOLS } from "../browser/tools.ts";+import { DATA_TOOLS } from "../data/tools.ts";+import { fitToolList } from "../mcp-tool-schema.ts";+import { SPAWNED_PROXIES } from "../proxy-paths.ts";+import { TOOL_SHARE_HEADER } from "../routes/own-mcp-http-path.ts";+import { cliDrops } from "../testing/cli-tool-drop.ts";+import { whopLikeCatalog } from "../testing/whop-like-catalog.ts";+import { workspaceAppsLikeCatalog } from "../testing/workspace-apps-like-catalog.ts";+import {+ ANTIGRAVITY_CLI_TOOL_BUDGET, definitionListBytes, toolListFloorBytes, toolsForShareProfile, type ListedTool,+} from "../tool-list-budget.ts";+import { TOOL_LIST_RECORD_ENV, TOOL_LIST_SHARE_ENV, toolsForSessionShare } from "../tool-list-share.ts";+import { TOOL_SCHEMA_PROFILE_ENV, toolSchemaProfile } from "../tool-schema-profile.ts";+import { agentsToolList } from "./agents-mcp.ts";+import { antigravityCliTakesHttpMcp, antigravityCliToolBudget } from "./antigravity-acp.ts";+import { acpSessionMcpServers } from "./own-mcp-http.ts";+import { withSessionToolShares } from "./own-mcp-session-budget.ts";+import { SESSION_TOOL_BUDGET_ENV, UNKNOWN_LIST_RESERVE, withSessionToolBudget } from "./session-tool-budget.ts";+import { acpMcpServers, type AcpMcpServer } from "./turn-mcp.ts";+import type { SendTurnInput } from "../contracts.ts";++const CLI_DROP_FLOOR = 58_700;+const HARNESS = "http://127.0.0.1:8799";+const CHIEF = { OMB_CHIEF_OF_STAFF: "1", OMB_COMPUTER_SELECTION: "1" };+const gemini = toolSchemaProfile("gemini")!;+type Stdio = Extract<AcpMcpServer, { command: string }>;++const pairs = (record: Record<string, string>) => Object.entries(record).map(([name, value]) => ({ name, value }));+const envOf = (server: AcpMcpServer) => ("command" in server ? Object.fromEntries(server.env.map(({ name, value }) => [name, value])) : {});+const agents: Stdio = { name: "agents", command: process.execPath, args: [SPAWNED_PROXIES.agents],+ env: pairs({ OMB_HARNESS_URL: HARNESS, OMB_COMMS_TOKEN: "comms", OMB_BOT_ID: "b1", OMB_THREAD_ID: "t1", ...CHIEF }) };+const harness = (kind: string): Stdio => ({ name: kind, command: process.execPath, args: [SPAWNED_PROXIES.harnessMcp, kind],+ env: pairs({ OMB_HARNESS_URL: HARNESS, [`OMB_MCP_TOKEN_${kind.toUpperCase()}`]: `${kind}-capability`, [TOOL_SCHEMA_PROFILE_ENV]: "gemini" }) });+const relay = (name: string, script: string): Stdio => ({ name, command: process.execPath, args: [script], env: pairs({ OMB_BOT_ID: "b1", [TOOL_SCHEMA_PROFILE_ENV]: "gemini" }) });+const composio = relay("composio", SPAWNED_PROXIES.connectors);+const workspace = relay("workspace", SPAWNED_PROXIES.mcpGate);++/** What each relayed server really lists, after the gemini profile its relay applies first. */+const LISTS: Record<string, readonly ListedTool[]> = {+ composio: fitToolList(workspaceAppsLikeCatalog(), gemini) as ListedTool[],+ workspace: fitToolList(whopLikeCatalog().slice(0, 30), gemini) as ListedTool[],+};+const OWN: Record<string, readonly ListedTool[]> = { agents: agentsToolList(CHIEF).listed as ListedTool[], browser: BROWSER_TOOLS, data: DATA_TOOLS as readonly ListedTool[] };++/** Each server's list as the engine is shown it under the planned servers: own servers by their profile, relays by+ * their share (recording as they go). */+function shown(planned: AcpMcpServer[]): Record<string, ListedTool[]> {+ return Object.fromEntries(planned.map((server) => {+ const env = envOf(server);+ const tools = server.name in OWN ? toolsForShareProfile(OWN[server.name]!, env[TOOL_SCHEMA_PROFILE_ENV]) : toolsForSessionShare(LISTS[server.name]!, env);+ return [server.name, tools as ListedTool[]];+ }));+}+const flat = (lists: Record<string, ListedTool[]>) => Object.entries(lists).flatMap(([server, tools]) => tools.map((tool) => ({ ...tool, name: `${server}/${tool.name}` })));++function plan(servers: AcpMcpServer[], recordsDir: string, env: NodeJS.ProcessEnv = {}) {+ const logged: string[] = [];+ return { planned: withSessionToolBudget(servers, ANTIGRAVITY_CLI_TOOL_BUDGET, { env, recordsDir, log: (line) => logged.push(line) }), logged };+}++describe("the session's tool budget over every server", () => {+ const session = [agents, harness("browser"), harness("data"), composio];++ it("a Chief with 74 connected-app tools: without it the CLI leaves out a whole size class, Drive, Docs and Photos with own tools", () => {+ const ownOnly = withSessionToolShares(session, ANTIGRAVITY_CLI_TOOL_BUDGET, () => {});+ const lists = { ...shown(ownOnly.filter((server) => server.name in OWN)), composio: [...LISTS.composio!] };+ const dropped = cliDrops(flat(lists), CLI_DROP_FLOOR);+ expect(dropped).toEqual(expect.arrayContaining(["agents/trigger", "composio/GOOGLEDRIVE_FIND_FILE", "composio/GOOGLEDOCS_CREATE_DOCUMENT"]));+ expect(dropped.some((name) => name.startsWith("composio/GMAIL_"))).toBe(false);+ });++ it("first session, nothing recorded: the relay is set aside what the own servers leave at their shortest, and nothing is dropped", () => {+ const recordsDir = mkdtempSync(join(tmpdir(), "stb-"));+ const { planned } = plan(session, recordsDir);+ const ownFloor = Object.values(OWN).reduce((sum, tools) => sum + toolListFloorBytes(tools), 0);+ const share = Number(envOf(planned[3]!)[TOOL_LIST_SHARE_ENV]);+ expect(share).toBeGreaterThanOrEqual(ANTIGRAVITY_CLI_TOOL_BUDGET - ownFloor - 2);+ expect(share).toBeGreaterThanOrEqual(UNKNOWN_LIST_RESERVE);+ const lists = shown(planned);+ expect(Object.fromEntries(Object.entries(lists).map(([server, tools]) => [server, tools.map((tool) => tool.name)])))+ .toEqual({ ...Object.fromEntries(Object.entries(OWN).map(([server, tools]) => [server, tools.map((tool) => tool.name)])), composio: LISTS.composio!.map((tool) => tool.name) });+ expect(cliDrops(flat(lists), CLI_DROP_FLOOR)).toEqual([]);+ });++ it("next session: the relay's record sizes every share at one cut, and still nothing is dropped", () => {+ const recordsDir = mkdtempSync(join(tmpdir(), "stb-"));+ shown(plan(session, recordsDir).planned);+ const { planned } = plan(session, recordsDir);+ const lists = shown(planned);+ expect(flat(lists)).toHaveLength(Object.values(OWN).flat().length + LISTS.composio!.length);+ expect(cliDrops(flat(lists), CLI_DROP_FLOOR)).toEqual([]);+ for (const [server, tools] of Object.entries(lists)) {+ const before = server in OWN ? OWN[server]! : LISTS[server]!;+ tools.forEach((tool, index) => {+ expect(tool.name).toBe(before[index]!.name);+ expect((tool.inputSchema as { required?: unknown }).required).toEqual((before[index]!.inputSchema as { required?: unknown }).required);+ });+ }+ });++ it("a session that cannot fit even at its shortest keeps every tool, says by how much, and leaves the CLI the largest to drop", () => {+ const recordsDir = mkdtempSync(join(tmpdir(), "stb-"));+ const big = [...session, workspace];+ LISTS.workspace = fitToolList(whopLikeCatalog().slice(0, 120), gemini) as ListedTool[];+ try {+ shown(plan(big, recordsDir).planned);+ const { planned, logged } = plan(big, recordsDir);+ const lists = shown(planned);+ expect(flat(lists)).toHaveLength(Object.values(OWN).flat().length + LISTS.composio!.length + LISTS.workspace.length);+ expect(logged).toEqual([expect.stringMatching(/^\[mcp\] this session's MCP tools \(agents, browser, data, composio, workspace\) come to \d+ bytes at their shortest, \d+ over the 55000-byte tool budget; the engine leaves out its largest tools first$/)]);+ } finally {+ LISTS.workspace = fitToolList(whopLikeCatalog().slice(0, 30), gemini) as ListedTool[];+ }+ });++ it("gives every relay its share and a record path in its environment, any earlier one replaced; own servers keep theirs in the profile", () => {+ const recordsDir = mkdtempSync(join(tmpdir(), "stb-"));+ const stale = { ...composio, env: [...composio.env, { name: TOOL_LIST_SHARE_ENV, value: "1" }] };+ const { planned } = plan([agents, harness("browser"), stale, workspace], recordsDir);+ for (const server of planned.slice(2)) {+ const env = envOf(server);+ expect(("command" in server ? server.env : []).filter(({ name }) => name === TOOL_LIST_SHARE_ENV)).toHaveLength(1);+ expect(Number(env[TOOL_LIST_SHARE_ENV])).toBeGreaterThan(UNKNOWN_LIST_RESERVE - 1);+ expect(env[TOOL_LIST_RECORD_ENV]).toMatch(new RegExp(`^${recordsDir.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&")}`));+ expect(env[TOOL_SCHEMA_PROFILE_ENV]).toBe("gemini");+ }+ expect(envOf(planned[0]!)[TOOL_SCHEMA_PROFILE_ENV]).toMatch(/^listShare:\d+$/);+ expect(envOf(planned[0]!)[TOOL_LIST_RECORD_ENV]).toBeUndefined();+ });++ it("OMB_SESSION_TOOL_BUDGET=0 shares the budget among own servers only, as before, and leaves every relay alone", () => {+ const recordsDir = mkdtempSync(join(tmpdir(), "stb-"));+ const { planned } = plan(session, recordsDir, { [SESSION_TOOL_BUDGET_ENV]: "0" });+ expect(planned).toEqual(withSessionToolShares(session, ANTIGRAVITY_CLI_TOOL_BUDGET, () => {}));+ expect(planned[3]).toBe(composio);+ });++ it("counts a server it does not relay without touching it, and says so", () => {+ const notes: Stdio = { name: "notes", command: "npx", args: ["notes-mcp"], env: [] };+ const { planned, logged } = plan([agents, notes], mkdtempSync(join(tmpdir(), "stb-")));+ expect(planned[1]).toBe(notes);+ expect(logged).toContain(`[mcp] notes: not relayed by OpenMausBot, so not fitted to the session's tool budget (${UNKNOWN_LIST_RESERVE} bytes set aside each)`);+ });++ it("names the recorded tools the CLI refuses for their name, whatever their size", () => {+ const recordsDir = mkdtempSync(join(tmpdir(), "stb-"));+ const long = { name: `GOOGLEDRIVE_${"X".repeat(50)}`, description: "d", inputSchema: { type: "object" } };+ toolsForSessionShare([long], envOf(plan([composio], recordsDir).planned[0]!));+ const { logged } = plan([composio], recordsDir);+ expect(logged).toContain(`[mcp] composio: the engine refuses 1 tool(s) whose name as mcp_composio_<tool> is over 64 characters or not [a-zA-Z0-9_-]: ${long.name}`);+ });++ it("reaches the relays by stdio and own servers by URL or stdio alike, OMB_OWN_MCP_HTTP=0 included", () => {+ const init = { agentInfo: { name: "Antigravity ACP Server" } };+ for (const transport of ["advertised", "stdio"] as const) {+ const sent = acpSessionMcpServers(session, transport, init, antigravityCliTakesHttpMcp, antigravityCliToolBudget);+ const browser = sent.find((server) => server.name === "browser")!;+ if (transport === "advertised") expect("headers" in browser && browser.headers.some(({ name }) => name === TOOL_SHARE_HEADER)).toBe(true);+ else expect(envOf(browser)[TOOL_SCHEMA_PROFILE_ENV]).toMatch(/^listShare:\d+$/);+ expect(Number(envOf(sent.find((server) => server.name === "composio")!)[TOOL_LIST_SHARE_ENV])).toBeGreaterThan(0);+ }+ expect(acpSessionMcpServers(session, "stdio", { agentInfo: { name: "antigravity-acp" } }, antigravityCliTakesHttpMcp, antigravityCliToolBudget)).toBe(session);+ });++ it("is within the budget in the definitions the CLI writes, every own list included", () => {+ const recordsDir = mkdtempSync(join(tmpdir(), "stb-"));+ shown(plan(session, recordsDir).planned);+ const lists = shown(plan(session, recordsDir).planned);+ expect(definitionListBytes(flat(lists))).toBeLessThan(CLI_DROP_FLOOR);+ });++ it("with a tool selection, every server behind the gate: own servers still sized by their lists, the connected apps given the rest", () => {+ const turn = {+ threadId: "t1", text: "x", toolScope: { allow: ["mcp:agents:*", "mcp:browser:*", "mcp:data:*", "mcp:composio:*", "native:*"] },+ integrations: {+ agents: { command: process.execPath, args: [SPAWNED_PROXIES.agents], env: { ...envOf(agents) } },+ browser: { command: process.execPath, args: [SPAWNED_PROXIES.harnessMcp, "browser"], env: { OMB_HARNESS_URL: HARNESS, OMB_MCP_TOKEN_BROWSER: "b" } },+ data: { command: process.execPath, args: [SPAWNED_PROXIES.harnessMcp, "data"], env: { OMB_HARNESS_URL: HARNESS, OMB_MCP_TOKEN_DATA: "d" } },+ composio: { command: process.execPath, args: [SPAWNED_PROXIES.connectors], env: { OMB_BOT_ID: "b1" } },+ },+ } as SendTurnInput;+ const built = acpMcpServers(turn, { engine: "antigravityAgent" });+ expect(built.every((server) => "command" in server && server.args[0] === SPAWNED_PROXIES.mcpGate)).toBe(true);+ const sent = acpSessionMcpServers(built, "advertised", { agentInfo: { name: "Antigravity ACP Server" } }, antigravityCliTakesHttpMcp, antigravityCliToolBudget);+ const share = (name: string) => Number(envOf(sent.find((server) => server.name === name)!)[TOOL_LIST_SHARE_ENV]);+ for (const [name, tools] of Object.entries(OWN)) expect(share(name)).toBeGreaterThanOrEqual(toolListFloorBytes(tools));+ expect(share("composio")).toBeGreaterThan(UNKNOWN_LIST_RESERVE);+ expect(["agents", "browser", "data", "composio"].reduce((sum, name) => sum + share(name), 0)).toBeLessThanOrEqual(ANTIGRAVITY_CLI_TOOL_BUDGET);+ });+});diff --git a/server/drivers/session-tool-budget.ts b/server/drivers/session-tool-budget.tsnew file mode 100644index 0000000000..012a4c78ad--- /dev/null+++ b/server/drivers/session-tool-budget.ts@@ -0,0 +1,106 @@+// One session's MCP tool budget shared out among every server in it, not only OpenMausBot's own: connected apps and the+// person's own servers reach the engine through OpenMausBot's relays, and each relay fits what it lists into the share+// it is given here. Their lists are known only once they answer, so each relay records the list it relayed and the next+// session sizes its share by that record. Until there is one, a relayed server is set aside what the known lists leave+// at their shortest: description text is lost, not tools.+// Measured on the native Antigravity CLI 1.5.18 (google-antigravity/antigravity-cli#1530): past the budget it leaves out+// the session's largest tools first, whichever server they come from, so to a person the cut looks like a size limit for+// one tool; and it refuses any tool whose `mcp_<server>_<tool>` is not 1 to 64 of [a-zA-Z0-9_-], whatever its size.+import { createHash } from "node:crypto";+import { join } from "node:path";++import { DATA_DIR } from "../config.ts";+import { toolListFloorBytes, type ListedTool } from "../tool-list-budget.ts";+import { readRecordedToolList, TOOL_LIST_RECORD_ENV, TOOL_LIST_SHARE_ENV } from "../tool-list-share.ts";+import { ownServerToolList, sessionToolShares, withOwnShare, withSessionToolShares } from "./own-mcp-session-budget.ts";+import type { AcpMcpServer } from "./turn-mcp.ts";++/** "0" counts only OpenMausBot's own servers in the budget, and leaves every other server's list as it is. */+export const SESSION_TOOL_BUDGET_ENV = "OMB_SESSION_TOOL_BUDGET";++/** The least set aside for a server whose list is not known yet. */+export const UNKNOWN_LIST_RESERVE = 8_000;++const RELAY = /(?:^|[\\/])(?:connector-proxy|mcp-gate|mcp-remote-proxy|local-computer-proxy)\.[jt]s$/;+/** The tool names the native CLI accepts, as `mcp_<server>_<tool>`. */+const CLI_TOOL_NAME = /^[a-zA-Z0-9_-]{1,64}$/;++type Env = Array<{ name: string; value: string }>;+const valueOf = (env: Env, name: string) => env.find((entry) => entry.name === name)?.value;++export interface SessionBudgetOptions {+ env?: NodeJS.ProcessEnv;+ /** Where relays record the lists they relay. */+ recordsDir?: string;+ log?: (line: string) => void;+}++export function toolListRecordPath(recordsDir: string, botId: string, server: string): string {+ return join(recordsDir, `${createHash("sha256").update(`${botId}\0${server}`).digest("hex").slice(0, 40)}.json`);+}++/** The tools of `tools` the native CLI refuses for their name under server `server`. */+export function cliRefusedToolNames(server: string, tools: readonly ListedTool[]): string[] {+ return tools.filter((tool) => !CLI_TOOL_NAME.test(`mcp_${server}_${tool.name}`)).map((tool) => tool.name);+}++/** One of OpenMausBot's own servers behind a tool-selection gate: its list, which the gate narrows. */+function gatedOwnList(server: AcpMcpServer & { env: Env }): readonly ListedTool[] | null {+ try {+ const upstream = JSON.parse(valueOf(server.env, "OMB_GATE_UPSTREAM") ?? "") as { command?: unknown; args?: unknown; env?: unknown };+ if (typeof upstream.command !== "string" || !Array.isArray(upstream.args)) return null;+ const env = upstream.env && typeof upstream.env === "object" ? Object.entries(upstream.env as Record<string, unknown>).map(([name, value]) => ({ name, value: String(value) })) : [];+ return ownServerToolList({ name: server.name, command: upstream.command, args: upstream.args.map(String), env });+ } catch {+ return null;+ }+}++type Planned =+ | { server: AcpMcpServer; kind: "own"; tools: readonly ListedTool[] }+ | { server: AcpMcpServer & { env: Env }; kind: "relay"; tools: readonly ListedTool[] | number; record: string }+ | { server: AcpMcpServer; kind: "other" };++/** `servers` with every server the session can size given its share of `budget`: OpenMausBot's own by their+ * OMB_TOOL_SCHEMA_PROFILE, relayed ones by OMB_TOOL_LIST_SHARE (and OMB_TOOL_LIST_RECORD, where they record their list). */+export function withSessionToolBudget(servers: AcpMcpServer[], budget: number, options: SessionBudgetOptions = {}): AcpMcpServer[] {+ const env = options.env ?? process.env;+ const log = options.log ?? ((line: string) => console.warn(line));+ if (env[SESSION_TOOL_BUDGET_ENV] === "0") return withSessionToolShares(servers, budget, log);+ const recordsDir = options.recordsDir ?? join(DATA_DIR, "tool-list-records");+ const botId = servers.map((server) => ("command" in server ? valueOf(server.env, "OMB_BOT_ID") : undefined)).find(Boolean) ?? "";+ const planned: Planned[] = servers.map((server) => {+ const own = ownServerToolList(server);+ if (own) return { server, kind: "own", tools: own };+ if (!("command" in server) || !server.args.some((arg) => RELAY.test(arg))) return { server, kind: "other" };+ const record = toolListRecordPath(recordsDir, botId, server.name);+ return { server, kind: "relay", tools: readRecordedToolList(record) ?? gatedOwnList(server) ?? UNKNOWN_LIST_RESERVE, record };+ });+ const unknown = planned.filter((entry) => entry.kind === "relay" && typeof entry.tools === "number");+ if (unknown.length) {+ const known = planned.reduce((sum, entry) => sum + (entry.kind === "other" ? UNKNOWN_LIST_RESERVE : typeof entry.tools === "number" ? 0 : toolListFloorBytes(entry.tools)), 0);+ const reserve = Math.max(UNKNOWN_LIST_RESERVE, Math.floor((budget - known) / unknown.length));+ for (const entry of unknown) if (entry.kind === "relay") entry.tools = reserve;+ }+ if (!planned.some((entry) => entry.kind !== "other")) return servers;+ const others = planned.filter((entry) => entry.kind === "other");+ const sized = planned.filter((entry) => entry.kind !== "other");+ const lists = [...sized.map((entry) => entry.tools), ...others.map(() => UNKNOWN_LIST_RESERVE)];+ const { shares, bytes, fits } = sessionToolShares(lists, budget);+ if (!fits) {+ log(`[mcp] this session's MCP tools (${sized.map((entry) => entry.server.name).join(", ")}) come to ${bytes} bytes at their shortest, ${bytes - budget} over the ${budget}-byte tool budget; the engine leaves out its largest tools first`);+ }+ if (others.length) log(`[mcp] ${others.map((entry) => entry.server.name).join(", ")}: not relayed by OpenMausBot, so not fitted to the session's tool budget (${UNKNOWN_LIST_RESERVE} bytes set aside each)`);+ for (const entry of sized) {+ const refused = typeof entry.tools === "number" ? [] : cliRefusedToolNames(entry.server.name, entry.tools);+ if (refused.length) log(`[mcp] ${entry.server.name}: the engine refuses ${refused.length} tool(s) whose name as mcp_${entry.server.name}_<tool> is over 64 characters or not [a-zA-Z0-9_-]: ${refused.join(", ")}`);+ }+ const shareOf = new Map(sized.map((entry, index) => [entry.server, shares[index]!]));+ return planned.map((entry) => {+ const share = shareOf.get(entry.server);+ if (share === undefined || entry.kind === "other") return entry.server;+ if (entry.kind === "own") return withOwnShare(entry.server, share);+ const kept = entry.server.env.filter(({ name }) => name !== TOOL_LIST_SHARE_ENV && name !== TOOL_LIST_RECORD_ENV);+ return { ...entry.server, env: [...kept, { name: TOOL_LIST_SHARE_ENV, value: String(share) }, { name: TOOL_LIST_RECORD_ENV, value: entry.record }] };+ });+}diff --git a/server/mcp-bridge.ts b/server/mcp-bridge.tsindex d3deee91ea..46ba51ac02 100644--- a/server/mcp-bridge.ts+++ b/server/mcp-bridge.ts@@ -7,6 +7,7 @@ import { textOnlyErrorResultLine } from "./mcp-error-result.ts";import { createToolListNormalizer } from "./mcp-tool-schema.ts";import { createJournalTap, postJournal } from "./saved-steps/journal-tap.ts";import { toolSchemaProfileFromEnv } from "./tool-schema-profile.ts";+import { toolsForSessionShare } from "./tool-list-share.ts";export const BRIDGE_INACTIVITY_MS = 45_000;const PROBE_TIMEOUT_MS = 10_000;@@ -358,7 +359,8 @@ export function runMcpBridge(options: BridgeOptions): void {: null;const reply = createReplyQueue(tap, (written) => process.stdout.write(written + "\n"));const answer = (line: string) => reply(line, line);- const toolLists = createToolListNormalizer(toolSchemaProfileFromEnv(), (line) => process.stderr.write(`${options.label}: ${line}\n`), options.ownTools);+ const logList = (line: string) => process.stderr.write(`${options.label}: ${line}\n`);+ const toolLists = createToolListNormalizer(toolSchemaProfileFromEnv(), logList, options.ownTools, (tools) => toolsForSessionShare(tools, process.env, logList));// Injected responses must never land inside one of the child's half-written frames.const rewrite = options.rewriteResponse ?? ((line: string) => line);const respond = (line: string) => reply(line, textOnlyErrorResultLine(rewrite(toolLists.rewriteResponse(line))));diff --git a/server/mcp-gate.ts b/server/mcp-gate.tsindex ce36d0fb93..c69020cf92 100644--- a/server/mcp-gate.ts+++ b/server/mcp-gate.ts@@ -16,6 +16,7 @@ import { killCliTree } from "./procs.ts";import { readStdioLines } from "./stdio-lines.ts";import { toolSchemaProfileFromEnv } from "./tool-schema-profile.ts";import { capToolListResult, toolLimitFromEnv } from "./tool-count-limit.ts";+import { TOOL_LIST_RECORD_ENV, TOOL_LIST_SHARE_ENV, toolsListResultForSessionShare } from "./tool-list-share.ts";type Json = Record<string, unknown>;@@ -224,6 +225,9 @@ if (SPILL_DIR) sweepSpill(SPILL_DIR);const childEnv: NodeJS.ProcessEnv = { ...process.env, ...spec.env };for (const key of Object.keys(childEnv)) if (key.startsWith("OMB_GATE_")) delete childEnv[key];+// The gate fits and records the list; a relay behind it doing so too would record the fitted list as the full one.+delete childEnv[TOOL_LIST_SHARE_ENV];+delete childEnv[TOOL_LIST_RECORD_ENV];// CreateProcess cannot exec an npm .cmd shim or a node-shebang script, and a shell would re-interpret JSON argv.const resolved = resolveCliSpawn(spec.command, spec.args ?? []);@@ -410,6 +414,9 @@ readStdioLines(child.stdout, (line) => {if (TOOL_LIMIT !== undefined && request?.kind === "list" && message.error === undefined && isRecord(result)) {message.result = capToolListResult(result, TOOL_LIMIT, (note) => process.stderr.write(`mcp-gate(${NAME}): ${note}\n`));}+ if (request?.kind === "list" && message.error === undefined) {+ message.result = toolsListResultForSessionShare(message.result, process.env, (note) => process.stderr.write(`mcp-gate(${NAME}): ${note}\n`));+ }if (request?.kind === "call" && observer && message.error === undefined) observer.returned(request.params, result);if (request?.kind === "call" && request.trim && isRecord(result)) {try {diff --git a/server/mcp-remote-proxy.ts b/server/mcp-remote-proxy.tsindex f55806ff63..4e7bd5743c 100644--- a/server/mcp-remote-proxy.ts+++ b/server/mcp-remote-proxy.ts@@ -29,6 +29,7 @@ import { APP_ONLY_REFUSAL, AppObserver, REMOTE_MCP_APPS_ENV, UI_EXTENSION, modelimport { lenientToolValidator, schemaProblems } from "./mcp-schema-validator.ts";import { fitToolListResult } from "./mcp-tool-schema.ts";import { toolSchemaProfileFromEnv } from "./tool-schema-profile.ts";+import { toolsListResultForSessionShare } from "./tool-list-share.ts";import { capToolListResult, toolLimitFromEnv } from "./tool-count-limit.ts";import { readStdioLines } from "./stdio-lines.ts";import { APP_EXTENSION_KEY } from "../shared/app.ts";@@ -341,7 +342,7 @@ async function handle(message: Json): Promise<void> {try {const result = directory ? await directed(message, signal) : await upstream(message.method, message.params, signal);if (message.method === "initialize") initialized = true;- send({ jsonrpc: "2.0", id: message.id, result: message.method === "tools/list" ? capToolListResult(fitToolListResult(result, SCHEMA_PROFILE, logFit), TOOL_LIMIT, logFit) : result });+ send({ jsonrpc: "2.0", id: message.id, result: message.method === "tools/list" ? toolsListResultForSessionShare(capToolListResult(fitToolListResult(result, SCHEMA_PROFILE, logFit), TOOL_LIMIT, logFit), process.env, logFit) : result });} catch (failure) {// Transport failures may carry URLs or header values: never relayed.let code = -32603;diff --git a/server/mcp-tool-schema.ts b/server/mcp-tool-schema.tsindex ad168bac6e..bedd7088fb 100644--- a/server/mcp-tool-schema.ts+++ b/server/mcp-tool-schema.ts@@ -143,7 +143,9 @@ export function fitToolListResult(result: unknown, profile: ToolSchemaProfile |/** Every listed schema gets a plain object root; under a profile each is also fitted to it. *//** `ownTools`: listed after the child's on its last page, in place of any child tool of the same name. */-export function createToolListNormalizer(profile?: ToolSchemaProfile, log?: (line: string) => void, ownTools: readonly JsonObject[] = []): {+/** `fitted`: a last step over each whole list (a single page), after the profile's. */+export function createToolListNormalizer(profile?: ToolSchemaProfile, log?: (line: string) => void, ownTools: readonly JsonObject[] = [],+ fitted: (tools: unknown[]) => unknown[] = (tools) => tools): {observeRequest: (line: string) => void;rewriteResponse: (line: string) => string;} {@@ -179,11 +181,12 @@ export function createToolListNormalizer(profile?: ToolSchemaProfile, log?: (linconst listed: unknown[] = ownNames.size? [...frame.result.tools.filter((tool: unknown) => !isObject(tool) || !ownNames.has(tool.name)), ...own]: frame.result.tools;- const tools = profile ? fitToolList(listed, profile, log) : listed.map((tool: unknown) => {+ const profiled = profile ? fitToolList(listed, profile, log) : listed.map((tool: unknown) => {if (!isObject(tool)) return tool;const inputSchema = providerSafeInputSchema(tool.inputSchema);return inputSchema === tool.inputSchema ? tool : { ...tool, inputSchema };});+ const tools = frame.result.nextCursor ? profiled : fitted(profiled);const changed = own.length > 0 || listed.length !== frame.result.tools.length || tools.length !== listed.length || tools.some((tool, index) => tool !== listed[index]);return changed ? JSON.stringify({ ...frame, result: { ...frame.result, tools } }) : line;},diff --git a/server/testing/antigravity-cli-probe.test.ts b/server/testing/antigravity-cli-probe.test.tsnew file mode 100644index 0000000000..56939a9ba8--- /dev/null+++ b/server/testing/antigravity-cli-probe.test.ts@@ -0,0 +1,68 @@+// The probe itself, and (with OMB_ANTIGRAVITY_CLI_PROBE naming a native Antigravity CLI executable) what the real CLI+// shows its model: one budget for all of a session's tools, no limit for one tool.+import { mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { gateServer } from "../mcp-gate-config.ts";+import { definitionBytes } from "../tool-list-budget.ts";+import { readRecordedToolList, TOOL_LIST_RECORD_ENV, TOOL_LIST_SHARE_ENV } from "../tool-list-share.ts";+import { probeAntigravityCli, serveProbeMcp, toolOfBytes, type ProbeTool } from "./antigravity-cli-probe.ts";+import { workspaceAppsLikeCatalog } from "./workspace-apps-like-catalog.ts";++const REAL_CLI = process.env.OMB_ANTIGRAVITY_CLI_PROBE;++describe("the Antigravity CLI probe", () => {+ it("makes tools of exactly the definition size asked for", () => {+ for (const bytes of [200, 944, 965, 4_000, 56_000]) expect(definitionBytes(toolOfBytes("t", bytes))).toBe(bytes);+ expect(definitionBytes(toolOfBytes("t", 900, 5))).toBe(900);+ expect(() => toolOfBytes("t", 10)).toThrow();+ });++ it("serves each probe server's tools over MCP by its own path", async () => {+ const tools = [toolOfBytes("a", 300), toolOfBytes("b", 400)];+ const servers = await serveProbeMcp({ probe: tools, other: [] });+ try {+ const entry = servers.entries().find((server) => server.name === "probe")!;+ const post = (body: unknown) => fetch(entry.url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }).then((response) => response.json());+ expect(await post({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } })).toMatchObject({ result: { serverInfo: { name: "probe" } } });+ expect(await post({ jsonrpc: "2.0", id: 2, method: "tools/list" })).toEqual({ jsonrpc: "2.0", id: 2, result: { tools } });+ expect(servers.listed.get("probe")).toBe(1);+ } finally {+ await servers.close();+ }+ });++ it.skipIf(!REAL_CLI)("real CLI: a 965-byte tool alone is shown, and past the budget the largest go first", { timeout: 120_000 }, async () => {+ const env = { ...process.env, HOME: mkdtempSync(join(tmpdir(), "agp-home-")) };+ const profile = () => mkdtempSync(join(tmpdir(), "agp-"));+ const alone = await probeAntigravityCli({ executable: REAL_CLI!, profile: profile(), env, servers: { probe: [toolOfBytes("one", 965)] }, prompt: true });+ expect(alone.session).toBe("ok");+ expect(alone.servers.probe!.map((tool) => tool.kept)).toEqual([true]);+ const graded = Array.from({ length: 80 }, (_, index) => toolOfBytes(`s${String(index).padStart(2, "0")}`, 800 + index * 10));+ const many = await probeAntigravityCli({ executable: REAL_CLI!, profile: profile(), env, servers: { probe: graded }, prompt: true });+ const kept = many.servers.probe!.filter((tool) => tool.kept), dropped = many.servers.probe!.filter((tool) => !tool.kept);+ expect(dropped.length).toBeGreaterThan(0);+ expect(Math.max(...kept.map((tool) => tool.bytes))).toBeLessThan(Math.min(...dropped.map((tool) => tool.bytes)));+ expect(many.servers.probe!.every((tool) => tool.written)).toBe(true);+ });++ it.skipIf(!REAL_CLI)("real CLI through the MCP gate: a share brings 74 connected-app tools from some shown to all shown, and is recorded", { timeout: 120_000 }, async () => {+ const folder = mkdtempSync(join(tmpdir(), "agp-gate-"));+ const catalog = workspaceAppsLikeCatalog() as ProbeTool[];+ writeFileSync(join(folder, "tools.json"), JSON.stringify(catalog));+ const gate = gateServer({ name: "workspace", server: { command: process.execPath, args: [join(import.meta.dirname, "probe-stdio-mcp-server.ts")], env: { PROBE_MCP_TOOLS_FILE: join(folder, "tools.json") } },+ threadId: "probe", budget: 0, schemaProfile: "gemini" })!;+ const env = { ...process.env, HOME: mkdtempSync(join(tmpdir(), "agp-home-")) };+ const shownWith = async (extra: Record<string, string>) => {+ const result = await probeAntigravityCli({ executable: REAL_CLI!, profile: mkdtempSync(join(tmpdir(), "agp-")), env, servers: {}, settleMs: 5_000, prompt: true,+ stdio: [{ name: "workspace", command: gate.command, args: gate.args, env: { ...gate.env, PATH: process.env.PATH ?? "", ...extra }, tools: catalog }] });+ return result.servers.workspace!.filter((tool) => tool.kept).length;+ };+ expect(await shownWith({})).toBeLessThan(catalog.length);+ const record = join(folder, "record.json");+ expect(await shownWith({ [TOOL_LIST_SHARE_ENV]: "26000", [TOOL_LIST_RECORD_ENV]: record })).toBe(catalog.length);+ expect(readRecordedToolList(record)?.map((tool) => tool.name)).toEqual(catalog.map((tool) => tool.name));+ });+});diff --git a/server/testing/antigravity-cli-probe.ts b/server/testing/antigravity-cli-probe.tsnew file mode 100644index 0000000000..6d5c0cbf42--- /dev/null+++ b/server/testing/antigravity-cli-probe.ts@@ -0,0 +1,238 @@+// Measures which of a session's MCP tools Google's native Antigravity CLI shows its model: probe MCP servers over HTTP+// whose tools have chosen definition sizes, one `antigravity acp` process in an empty profile, a made-up Gemini API key,+// and a loopback stand-in for the model whose first request names every tool the model is shown. 1.5.18 writes a+// definition file (<gemini-dir>/antigravity-acp/mcp/<server>/<tool>.json) for every tool, the ones it leaves out of the+// model's request included, so the files alone do not say what was kept.+import { spawn } from "node:child_process";+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, statSync } from "node:fs";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { createInterface } from "node:readline";++import { definitionBytes, type ListedTool } from "../tool-list-budget.ts";++export type ProbeTool = { name: string; description: string; inputSchema: Record<string, unknown> };++/** A tool whose definition (as the CLI writes it, see definitionBytes) comes to exactly `bytes`, by padding its+ * description; with `parameters` small string parameters, which the CLI cannot fold away. */+export function toolOfBytes(name: string, bytes: number, parameters = 1): ProbeTool {+ const properties = Object.fromEntries(Array.from({ length: parameters }, (_, index) => [`p${index}`, { type: "string" }]));+ const base: ProbeTool = { name, description: "", inputSchema: { type: "object", properties, required: ["p0"].filter(() => parameters > 0) } };+ const pad = bytes - definitionBytes(base);+ if (pad < 0) throw new Error(`a tool named ${name} cannot be as small as ${bytes} bytes`);+ const description = "Probe tool padded to a chosen size. ".repeat(Math.ceil(pad / 36) + 1).slice(0, pad);+ return { ...base, description };+}++export interface ProbeServers {+ /** The `session/new` entry for each named server. */+ entries(): Array<{ type: "http"; name: string; url: string; headers: Array<{ name: string; value: string }> }>;+ /** The tools/list requests each server answered. */+ listed: Map<string, number>;+ /** Requests that reached the stand-in model endpoint. */+ modelRequests: Array<{ path: string; body: string }>;+ /** The stand-in model endpoint, for GOOGLE_GEMINI_BASE_URL. */+ baseUrl: string;+ close(): Promise<void>;+}++/** One loopback HTTP server answering MCP (JSON responses, no sessions) for every server in `servers`, by path. */+export async function serveProbeMcp(servers: Record<string, readonly ProbeTool[]>): Promise<ProbeServers> {+ const listed = new Map<string, number>();+ const modelRequests: Array<{ path: string; body: string }> = [];+ const server: Server = createServer((request, response) => {+ const path = (request.url ?? "/").split("?")[0]!;+ if (!path.startsWith("/mcp/")) {+ // The model endpoint (GOOGLE_GEMINI_BASE_URL): every request is kept, and answered with an error.+ let body = "";+ request.on("data", (chunk) => { body += chunk; });+ request.on("end", () => {+ modelRequests.push({ path, body });+ response.writeHead(400, { "content-type": "application/json" }).end(JSON.stringify({ error: { code: 400, message: "probe model", status: "INVALID_ARGUMENT" } }));+ });+ return;+ }+ const name = decodeURIComponent(path.slice("/mcp/".length));+ const tools = servers[name];+ if (request.method !== "POST" || !tools) {+ response.writeHead(request.method === "GET" ? 405 : 404).end();+ return;+ }+ let body = "";+ request.on("data", (chunk) => { body += chunk; });+ request.on("end", () => {+ let message: { id?: unknown; method?: string; params?: { protocolVersion?: string } };+ try { message = JSON.parse(body); } catch { response.writeHead(400).end(); return; }+ if (message.id === undefined || message.id === null) { response.writeHead(202).end(); return; }+ let result: unknown;+ if (message.method === "initialize") {+ result = { protocolVersion: message.params?.protocolVersion ?? "2025-06-18", capabilities: { tools: { listChanged: false } }, serverInfo: { name, version: "1.0.0" } };+ } else if (message.method === "tools/list") {+ listed.set(name, (listed.get(name) ?? 0) + 1);+ result = { tools };+ } else if (message.method === "ping") result = {};+ else if (message.method === "tools/call") result = { content: [{ type: "text", text: "probe" }] };+ else {+ response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "not found" } }));+ return;+ }+ response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }));+ });+ });+ await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));+ const port = (server.address() as AddressInfo).port;+ return {+ entries: () => Object.keys(servers).map((name) => ({ type: "http" as const, name, url: `http://127.0.0.1:${port}/mcp/${encodeURIComponent(name)}`, headers: [] })),+ listed,+ modelRequests,+ baseUrl: `http://127.0.0.1:${port}`,+ close: () => new Promise<void>((done) => { server.closeAllConnections(); server.close(() => done()); }),+ };+}++export interface ProbeResult {+ /** The CLI's version, from its `initialize` answer. */+ version: string;+ /** What `session/new` answered: "ok", or its error message. */+ session: string;+ /** For each server, the tools it offered: `kept` when the model was shown it (with `prompt`; else when its definition+ * file was written), `written` when the CLI wrote its definition file, with that file's size. 1.5.18 writes a file for+ * every tool, the ones it leaves out of the model's request included. */+ servers: Record<string, Array<{ name: string; bytes: number; kept: boolean; written: boolean; fileBytes?: number; fileName?: string }>>;+ /** Every file name under mcp/, as the CLI wrote it (relative), for path-length checks. */+ files: string[];+ /** Lines of the CLI's stderr and log files that mention MCP, tools or a budget. */+ logLines: string[];+ /** The longest absolute path the CLI wrote under the profile. */+ longestPath: number;+ /** With `prompt`: every function name the CLI declared to the (stand-in) model on the first turn. */+ modelTools?: string[];+ /** With `prompt`: that request's body as the CLI sent it. */+ modelRequest?: string;+}++function declaredNames(body: string): string[] {+ try {+ const parsed = JSON.parse(body) as { request?: { tools?: unknown }; tools?: unknown };+ const tools = (parsed.request?.tools ?? parsed.tools) as Array<{ functionDeclarations?: Array<{ name?: string }> }> | undefined;+ return (tools ?? []).flatMap((tool) => (tool.functionDeclarations ?? []).map((declaration) => String(declaration.name)));+ } catch {+ return [...body.matchAll(/"name":"([^"]+)"/gu)].map((match) => match[1]!);+ }+}++function walkFiles(directory: string, prefix = ""): string[] {+ if (!existsSync(directory)) return [];+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => entry.isDirectory()+ ? walkFiles(join(directory, entry.name), `${prefix}${entry.name}/`)+ : [`${prefix}${entry.name}`]);+}++/** Starts `executable` as `acp` in `profile` (a new, empty folder) with `env` (which must hold a throwaway HOME), opens one+ * session with `servers`, waits `settleMs` for its MCP preload, and reads back which tools it kept. */+export async function probeAntigravityCli(options: {+ executable: string;+ profile: string;+ env: NodeJS.ProcessEnv;+ servers: Record<string, readonly ProbeTool[]>;+ /** Stdio servers mounted as they are (a relay in front of a real server), with the tools each is expected to list. */+ stdio?: Array<{ name: string; command: string; args: string[]; env: Record<string, string>; tools: readonly ProbeTool[] }>;+ settleMs?: number;+ /** Also run one turn against the stand-in model and read which tools it was shown. */+ prompt?: boolean;+}): Promise<ProbeResult> {+ mkdirSync(options.profile, { recursive: true });+ // Apart from the profile: Windows starts no process in a working folder past 260 characters.+ const cwd = mkdtempSync(join(tmpdir(), "agp-cwd-"));+ const mcp = await serveProbeMcp(options.servers);+ const child = spawn(options.executable, ["acp", "--gemini-dir", options.profile, "--app-data-dir", "antigravity-acp"], {+ // A made-up API key and a loopback model endpoint: the CLI opens sessions (and connects their MCP servers) only when+ // it has some sign-in, and this one reaches nobody.+ cwd, env: { ...options.env, GEMINI_API_KEY: "probe-not-a-key", GOOGLE_API_KEY: "", GOOGLE_GEMINI_BASE_URL: mcp.baseUrl }, stdio: ["pipe", "pipe", "pipe"], windowsHide: true,+ });+ const stderr: string[] = [];+ createInterface({ input: child.stderr }).on("line", (line) => stderr.push(line));+ const pending = new Map<number, (message: any) => void>();+ createInterface({ input: child.stdout }).on("line", (line) => {+ let message: any;+ try { message = JSON.parse(line); } catch { return; }+ if (typeof message.id === "number" && pending.has(message.id) && !message.method) {+ pending.get(message.id)!(message);+ pending.delete(message.id);+ } else if (message.method && message.id !== undefined) {+ // A request from the agent (permission, file read): refused, the probe runs no turn.+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "probe" } })}\n`);+ }+ });+ let next = 0;+ let failed: string | undefined;+ const request = (method: string, params: unknown, ms = 60_000) => new Promise<any>((done) => {+ if (failed !== undefined) return done({ error: { message: `the CLI did not start: ${failed}` } });+ const id = ++next;+ const timer = setTimeout(() => { pending.delete(id); done({ error: { message: `no answer to ${method} in ${ms} ms` } }); }, ms);+ pending.set(id, (message) => { clearTimeout(timer); done(message); });+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);+ });+ const exited = new Promise<void>((done) => child.once("exit", () => done()));+ child.on("error", (error) => {+ failed = error.message;+ for (const [id, answer] of pending) { pending.delete(id); answer({ error: { message: `the CLI did not start: ${error.message}` } }); }+ });+ child.stdin.on("error", () => {});+ try {+ const init = await request("initialize", { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false } });+ const version = String(init.result?.agentInfo?.version ?? init.error?.message ?? "unknown");+ await request("authenticate", { methodId: "gemini-api-key" });+ const stdio = (options.stdio ?? []).map(({ name, command, args, env }) => ({ name, command, args, env: Object.entries(env).map(([key, value]) => ({ name: key, value })) }));+ const created = await request("session/new", { cwd, mcpServers: [...mcp.entries(), ...stdio] });+ const session = created.error ? String(created.error.message ?? "error") : "ok";+ await new Promise((done) => setTimeout(done, options.settleMs ?? 3_000));+ let modelTools: string[] | undefined;+ let modelRequest: string | undefined;+ if (options.prompt) {+ const sessionId = created.result?.sessionId;+ const before = mcp.modelRequests.length;+ void request("session/prompt", { sessionId, prompt: [{ type: "text", text: "Say hi." }] }, 30_000);+ for (let waited = 0; waited < 30_000 && !mcp.modelRequests.slice(before).some((entry) => entry.body.includes("functionDeclarations")); waited += 250) {+ await new Promise((done) => setTimeout(done, 250));+ }+ const sent = mcp.modelRequests.slice(before).find((entry) => entry.body.includes("functionDeclarations"));+ modelTools = sent ? declaredNames(sent.body) : [];+ modelRequest = sent?.body;+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method: "session/cancel", params: { sessionId } })}\n`);+ }+ const root = join(options.profile, "antigravity-acp", "mcp");+ const files = walkFiles(root);+ const servers: ProbeResult["servers"] = {};+ const expected = { ...options.servers, ...Object.fromEntries((options.stdio ?? []).map(({ name, tools }) => [name, tools])) };+ for (const [name, tools] of Object.entries(expected)) {+ const folder = (existsSync(root) ? readdirSync(root, { withFileTypes: true }) : []).find((entry) => entry.isDirectory() && (entry.name === name || entry.name.endsWith(`_${name}`) || entry.name.startsWith(name)))?.name;+ const written = folder ? readdirSync(join(root, folder)) : [];+ servers[name] = tools.map((tool) => {+ const fileName = written.find((file) => file === `${tool.name}.json` || file.endsWith(`_${tool.name}.json`));+ const shown = modelTools === undefined ? undefined : modelTools.some((declared) => declared === `mcp_${name}_${tool.name}` || declared === `mcp_${name.replace(/[^A-Za-z0-9_]/gu, "_")}_${tool.name}`);+ return {+ name: tool.name, bytes: definitionBytes(tool as ListedTool), kept: shown ?? fileName !== undefined, written: fileName !== undefined,+ ...(fileName ? { fileName: `${folder}/${fileName}`, fileBytes: statSync(join(root, folder!, fileName)).size } : {}),+ };+ });+ }+ const logs = walkFiles(join(options.profile, "antigravity-acp")).filter((file) => /\.(log|txt)$/u.test(file))+ .flatMap((file) => readFileSync(join(options.profile, "antigravity-acp", file), "utf8").split("\n"));+ const logLines = [...stderr, ...logs].filter((line) => /mcp|tool|budget|truncat|preload|deadline/iu.test(line)).slice(-200);+ const longestPath = Math.max(0, ...walkFiles(options.profile).map((file) => join(options.profile, file).length));+ return { version, session, servers, files, logLines, longestPath, ...(modelTools ? { modelTools } : {}), ...(modelRequest ? { modelRequest } : {}) };+ } finally {+ child.stdin.end();+ child.kill();+ await Promise.race([exited, new Promise((done) => setTimeout(done, 5_000))]);+ await mcp.close();+ }+}++/** The tools of `result` the CLI did not keep. */+export function droppedTools(result: ProbeResult): string[] {+ return Object.entries(result.servers).flatMap(([server, tools]) => tools.filter((tool) => !tool.kept).map((tool) => `${server}/${tool.name}`));+}diff --git a/server/testing/probe-stdio-mcp-server.ts b/server/testing/probe-stdio-mcp-server.tsnew file mode 100644index 0000000000..e76981aabc--- /dev/null+++ b/server/testing/probe-stdio-mcp-server.ts@@ -0,0 +1,18 @@+// A stdio MCP server listing the tools in the JSON file PROBE_MCP_TOOLS_FILE, answering every other request with an+// error, as a server must for the native Antigravity CLI, which asks `server/discover` before `initialize` and waits.+import { readFileSync } from "node:fs";+import { createInterface } from "node:readline";++const tools: unknown = JSON.parse(readFileSync(process.env.PROBE_MCP_TOOLS_FILE ?? "", "utf8"));+const reply = (frame: Record<string, unknown>) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", ...frame })}\n`);++createInterface({ input: process.stdin }).on("line", (line) => {+ let frame: { id?: unknown; method?: string; params?: { protocolVersion?: string } };+ try { frame = JSON.parse(line); } catch { return; }+ if (frame.id === undefined || frame.id === null) return;+ if (frame.method === "initialize") {+ reply({ id: frame.id, result: { protocolVersion: frame.params?.protocolVersion ?? "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "probe", version: "1" } } });+ } else if (frame.method === "tools/list") reply({ id: frame.id, result: { tools } });+ else if (frame.method === "ping") reply({ id: frame.id, result: {} });+ else reply({ id: frame.id, error: { code: -32601, message: "Method not found" } });+});diff --git a/server/testing/workspace-apps-like-catalog.ts b/server/testing/workspace-apps-like-catalog.tsnew file mode 100644index 0000000000..bdeba6b003--- /dev/null+++ b/server/testing/workspace-apps-like-catalog.ts@@ -0,0 +1,63 @@+// A synthetic connected-apps tool list shaped like Composio's Google Workspace toolkits as its MCP server lists them:+// `<TOOLKIT>_<ACTION>` names, a long description, and per-parameter title, description, examples and default. Gmail and+// Calendar tools are small, Drive, Docs and Photos tools large. All made up; deterministic.+import type { ListedTool } from "../tool-list-budget.ts";++interface Toolkit { slug: string; actions: string[]; noun: string; parameters: [number, number]; words: [number, number] }++const TOOLKITS: Toolkit[] = [+ { slug: "GMAIL", noun: "email", parameters: [1, 3], words: [12, 30], actions: ["FETCH_EMAILS", "SEND_EMAIL", "CREATE_EMAIL_DRAFT", "LIST_LABELS", "ADD_LABEL_TO_EMAIL", "GET_PROFILE", "LIST_THREADS", "MOVE_TO_TRASH", "REPLY_TO_THREAD", "FETCH_MESSAGE_BY_THREAD_ID"] },+ { slug: "GOOGLECALENDAR", noun: "event", parameters: [1, 3], words: [12, 30], actions: ["EVENTS_LIST", "CREATE_EVENT", "DELETE_EVENT", "FIND_FREE_SLOTS", "GET_CALENDAR", "LIST_CALENDARS", "QUICK_ADD", "UPDATE_EVENT"] },+ { slug: "GOOGLEDRIVE", noun: "file", parameters: [4, 12], words: [60, 140], actions: ["FIND_FILE", "FIND_FOLDER", "CREATE_FILE_FROM_TEXT", "CREATE_FOLDER", "UPLOAD_FILE", "DOWNLOAD_FILE", "COPY_FILE", "MOVE_FILE", "DELETE_FILE", "ADD_FILE_SHARING_PREFERENCE", "LIST_PERMISSIONS", "EDIT_FILE", "GET_FILE_METADATA", "LIST_SHARED_DRIVES", "CREATE_SHARED_DRIVE", "EXPORT_FILE", "LIST_COMMENTS", "CREATE_COMMENT", "LIST_REVISIONS", "UPDATE_FILE_METADATA"] },+ { slug: "GOOGLEDOCS", noun: "document", parameters: [3, 10], words: [50, 120], actions: ["CREATE_DOCUMENT", "GET_DOCUMENT_BY_ID", "UPDATE_EXISTING_DOCUMENT", "CREATE_DOCUMENT_MARKDOWN", "UPDATE_DOCUMENT_MARKDOWN", "INSERT_TABLE_ACTION", "INSERT_INLINE_IMAGE", "REPLACE_ALL_TEXT", "DELETE_CONTENT_RANGE", "CREATE_HEADER", "CREATE_FOOTER", "SEARCH_DOCUMENTS", "COPY_DOCUMENT", "LIST_NAMED_RANGES"] },+ { slug: "GOOGLEPHOTOS", noun: "media item", parameters: [3, 9], words: [50, 110], actions: ["LIST_ALBUMS", "CREATE_ALBUM", "ADD_ENRICHMENT", "BATCH_ADD_MEDIA_ITEMS", "BATCH_CREATE_MEDIA_ITEMS", "SEARCH_MEDIA_ITEMS", "GET_MEDIA_ITEM", "LIST_MEDIA_ITEMS", "UPLOAD_MEDIA", "SHARE_ALBUM", "GET_ALBUM", "UPDATE_ALBUM"] },+ { slug: "GOOGLESHEETS", noun: "spreadsheet", parameters: [3, 8], words: [40, 100], actions: ["BATCH_GET", "BATCH_UPDATE", "CREATE_GOOGLE_SHEET1", "GET_SPREADSHEET_INFO", "LOOKUP_SPREADSHEET_ROW", "SHEET_FROM_JSON", "ADD_SHEET", "CLEAR_VALUES", "APPEND_DIMENSION", "SEARCH_SPREADSHEETS"] },+];++const WORDS = "the a to of for with and when this that each its use only returns lists selected given request account item field value page token query filter order results owner shared folder document permission default optional required".split(" ");++function random(seed: number): () => number {+ let state = seed >>> 0;+ return () => {+ state = (state * 1_664_525 + 1_013_904_223) >>> 0;+ return state / 2 ** 32;+ };+}++function sentence(next: () => number, words: number): string {+ const picked = Array.from({ length: words }, () => WORDS[Math.floor(next() * WORDS.length)]!);+ return `${picked.join(" ")}.`.replace(/^./u, (first) => first.toUpperCase());+}++function between(next: () => number, [low, high]: [number, number]): number {+ return low + Math.floor(next() * (high - low + 1));+}++/** `count` tools (at most every action of every toolkit, in toolkit order), or all of them. */+export function workspaceAppsLikeCatalog(count?: number): ListedTool[] {+ const tools: ListedTool[] = [];+ for (const [index, toolkit] of TOOLKITS.entries()) {+ for (const [position, action] of toolkit.actions.entries()) {+ const next = random(index * 1_000 + position + 1);+ const properties: Record<string, unknown> = {};+ const required: string[] = [];+ const parameterCount = between(next, toolkit.parameters);+ for (let parameter = 0; parameter < parameterCount; parameter += 1) {+ const name = `${toolkit.noun.replace(/\s/gu, "_")}_${["id", "name", "query", "page_size", "page_token", "fields", "mime_type", "parent_id", "role", "type", "content", "order_by"][parameter % 12]}${parameter >= 12 ? parameter : ""}`;+ const kind = parameter % 4 === 3 ? "integer" : "string";+ properties[name] = {+ type: kind, title: name.replace(/_/gu, " "), description: sentence(next, between(next, [8, 40])),+ ...(kind === "integer" ? { default: 20, examples: [10, 50] } : { examples: [`${toolkit.noun}-example`] }),+ ...(parameter % 5 === 4 ? { enum: ["user", "group", "domain", "anyone"] } : {}),+ };+ if (parameter < 1 + (parameterCount > 6 ? 1 : 0)) required.push(name);+ }+ tools.push({+ name: `${toolkit.slug}_${action}`,+ description: `${sentence(next, between(next, toolkit.words))} ${sentence(next, 10)}`,+ inputSchema: { type: "object", title: `${action}Request`, properties, required },+ });+ }+ }+ return count === undefined ? tools : tools.slice(0, count);+}diff --git a/server/tool-list-budget.test.ts b/server/tool-list-budget.test.tsindex 04a01f08e4..c0d5a43aa8 100644--- a/server/tool-list-budget.test.ts+++ b/server/tool-list-budget.test.ts@@ -4,7 +4,7 @@ import fullAgents from "./drivers/agents-catalog-goldens/full.tools-list.json" wimport { compactAdvertisedSchema } from "./advertised-schema.ts";import { cliDrops } from "./testing/cli-tool-drop.ts";import {- cutText, definitionBytes, withCompactSchemas, withDescriptionLevel, definitionListBytes, fitToolListToShare, PROTECTED_TOOLS, TOOL_DESCRIPTION_FLOOR, toolListShare, toolListShareProfile,+ cutText, definitionBytes, withCompactSchemas, withDescriptionLevel, definitionListBytes, fitToolListToShare, PROTECTED_TOOLS, TOOL_DESCRIPTION_FLOOR, TOOL_DESCRIPTION_MIN, toolListShare, toolListShareProfile,toolsForShareProfile, toolsListResultForShareProfile, type ListedTool,} from "./tool-list-budget.ts";@@ -94,10 +94,10 @@ describe("fitting a list into its share", () => {});it("over its share even at its shortest, keeps every tool and shrinks the protected ones, so the CLI's largest-first drop takes others first", () => {- const fitted = fitToolListToShare(agents, 25_000);+ const fitted = fitToolListToShare(agents, 14_000);expect(fitted.fits).toBe(false);expect(names(fitted.tools)).toEqual(names(agents));- const shortest = withDescriptionLevel(withCompactSchemas(agents), { parameters: 0, tools: TOOL_DESCRIPTION_FLOOR });+ const shortest = withDescriptionLevel(withCompactSchemas(agents), { parameters: 0, tools: TOOL_DESCRIPTION_MIN, annotations: true });// Past the largest unprotected tool, trigger (23 named fields) is next: shrinking cannot take it lower without hiding fields.const overBy = 1_000;expect(cliDrops(shortest, definitionListBytes(shortest) - overBy).filter((name) => PROTECTED_TOOLS.includes(name))).not.toEqual([]);@@ -125,11 +125,31 @@ describe("fitting a list into its share", () => {expect(toolsListResultForShareProfile(result, "gemini")).toBe(result);expect(toolsListResultForShareProfile({ error: "x" }, toolListShareProfile(1))).toEqual({ error: "x" });const logged: string[] = [];- const fitted = toolsListResultForShareProfile(result, toolListShareProfile(25_000), (line) => logged.push(line)) as { tools: ListedTool[] };+ const fitted = toolsListResultForShareProfile(result, toolListShareProfile(14_000), (line) => logged.push(line)) as { tools: ListedTool[] };expect(names(fitted.tools)).toEqual(names(agents));- expect(logged).toEqual([expect.stringMatching(/^tool list is \d+ bytes at its shortest, \d+ over its 25000-byte share of the session's tool budget$/)]);+ expect(logged).toEqual([expect.stringMatching(/^tool list is \d+ bytes at its shortest, \d+ over its 14000-byte share of the session's tool budget$/)]);// The same list under the same share again, as every request of a turn builds it: the fitted list reused, no second line.- expect(toolsForShareProfile(structuredClone(agents), toolListShareProfile(25_000), (line) => logged.push(line))).toBe(fitted.tools);+ expect(toolsForShareProfile(structuredClone(agents), toolListShareProfile(14_000), (line) => logged.push(line))).toBe(fitted.tools);expect(logged).toHaveLength(1);});++ it("at its deepest cut keeps a list of objects an array of objects, and leaves a field with no type of its own as it was", () => {+ const tool: ListedTool = {+ name: "plain_tool", description: "Does one thing. ".repeat(20),+ inputSchema: { type: "object", required: ["rows"], properties: {+ rows: { type: "array", description: "d".repeat(200), items: { type: "object", properties: { a: { type: "string" }, b: { type: "number" } } } },+ target: { type: "object", properties: { id: { type: "string" } } },+ either: { anyOf: [{ type: "string" }, { type: "object", properties: { id: { type: "string" } } }] },+ mode: { type: "string", enum: ["a", "b"] },+ } },+ };+ const fitted = fitToolListToShare([tool], definitionBytes(withDescriptionLevel([tool], { parameters: 0, tools: TOOL_DESCRIPTION_MIN, annotations: true })[0]!) - 20);+ expect(fitted.level.topLevelOnly).toBe(true);+ expect(fitted.tools[0]!.inputSchema).toEqual({ type: "object", required: ["rows"], properties: {+ rows: { type: "array", items: { type: "object" } },+ target: { type: "object" },+ either: { anyOf: [{ type: "string" }, { type: "object", properties: { id: { type: "string" } } }] },+ mode: { type: "string", enum: ["a", "b"] },+ } });+ });});diff --git a/server/tool-list-budget.ts b/server/tool-list-budget.tsindex c8b5051102..b480201da6 100644--- a/server/tool-list-budget.ts+++ b/server/tool-list-budget.ts@@ -1,12 +1,12 @@// A byte budget over the MCP tool definitions an engine shows its model, for an engine that shows every tool eagerly and,// past its budget, silently leaves out the largest tools first. Google's native Antigravity CLI (1.5.x over ACP) is one-// (google-antigravity/antigravity-cli#1530): it writes each tool to <app-data-dir>/mcp/<server>/<tool>.json as-// {name, description, parameters} and counts those files across every server of the session. On 1.5.16 the drop-// started between 58,700 and 60,600 bytes; on 1.5.17 one tool alone was kept up to 56,608 bytes, about 38 more per-// further tool and about 6 fewer per character of the profile's path. A session's own servers share out-// ANTIGRAVITY_CLI_TOOL_BUDGET and each fits its list into its share, least loss first: the schema compacted, then-// shorter parameter descriptions, then shorter tool descriptions. No tool is left out, and every call is still checked-// against the tool's own full schema.+// (google-antigravity/antigravity-cli#1530): it counts every server's tool definitions ({name, description, parameters})+// together. On 1.5.16 the drop started between 58,700 and 60,600 bytes; on 1.5.17 one tool alone was kept up to 56,608+// bytes, on 1.5.18 up to about 56,780, about 38 more per further tool. There is no limit for one tool: with many tools+// the cut only looks like one, since every tool over some size goes. A session's servers share out+// ANTIGRAVITY_CLI_TOOL_BUDGET and each fits its list into its share, least loss first: the schema compacted, then its+// annotations, shorter parameter descriptions, shorter tool descriptions, and last nested fields. No tool is left out,+// no name or required field changes, and every call is still checked against the tool's own full schema.import { compactAdvertisedSchema } from "./advertised-schema.ts";import { schemaBytes } from "./tool-schema-profile.ts";@@ -42,9 +42,12 @@ export function definitionListBytes(tools: readonly ListedTool[]): number {* fit these are made smaller still. */export const PROTECTED_TOOLS: readonly string[] = ["coordinate_bots", "start_thread", "show_html", "trigger", "memory_update", "attach_file"];-/** A tool description is never cut below this many characters while fitting; past it the list is over its share. */+/** Tool descriptions are cut to this many characters before any is cut further. */export const TOOL_DESCRIPTION_FLOOR = 120;+/** A tool description is never cut below this many characters while fitting; past it the list is over its share. */+export const TOOL_DESCRIPTION_MIN = 40;+/** `text` cut to at most `max` characters: at the last sentence end that fits, else at a word with an ellipsis; undefined* when nothing is left. The kept length never shrinks as `max` grows, so a search over `max` is sound. */export function cutText(text: string, max: number): string | undefined {@@ -66,32 +69,60 @@ function isObject(value: unknown): value is Json {return Boolean(value) && typeof value === "object" && !Array.isArray(value);}-/** Every `description` inside a schema, at any depth, cut to `max` characters (gone at 0). */-function withParameterDescriptions(node: unknown, max: number): unknown {+/** Keywords that tell a model nothing a call must follow: they go before any description does. */+const ANNOTATIONS = new Set(["title", "examples", "example", "$comment", "deprecated", "readOnly", "writeOnly", "$schema", "$id"]);++/** A schema with every `description`, at any depth, cut to `parameters` characters (gone at 0), and with `annotations`+ * its ANNOTATIONS left out. Property names are never touched. */+function withSchemaLevel(node: unknown, parameters: number, annotations: boolean): unknown {if (!isObject(node)) return node;const result: Json = {};for (const [key, value] of Object.entries(node)) {if (key === "description" && typeof value === "string") {- const kept = cutText(value, max);+ const kept = cutText(value, parameters);if (kept !== undefined) result[key] = kept;- } else if (SCHEMA_MAPS.has(key) && isObject(value)) {- result[key] = Object.fromEntries(Object.entries(value).map(([name, child]) => [name, withParameterDescriptions(child, max)]));- } else if (SCHEMA_LISTS.has(key) && Array.isArray(value)) result[key] = value.map((child) => withParameterDescriptions(child, max));- else if (SCHEMA_SLOTS.has(key) && isObject(value)) result[key] = withParameterDescriptions(value, max);+ } else if (annotations && ANNOTATIONS.has(key)) continue;+ else if (SCHEMA_MAPS.has(key) && isObject(value)) {+ result[key] = Object.fromEntries(Object.entries(value).map(([name, child]) => [name, withSchemaLevel(child, parameters, annotations)]));+ } else if (SCHEMA_LISTS.has(key) && Array.isArray(value)) result[key] = value.map((child) => withSchemaLevel(child, parameters, annotations));+ else if (SCHEMA_SLOTS.has(key) && isObject(value)) result[key] = withSchemaLevel(value, parameters, annotations);else result[key] = value;}return result;}-/** How much of each description a list keeps, in characters; Infinity keeps all of it. */-export interface DescriptionLevel { parameters: number; tools: number }+/** A top-level field that holds an object, or a list of objects, as just its type and choices (a list keeps+ * `items: {type: "object"}`, which a Gemini endpoint requires of every array); any other field, and one with no `type` of+ * its own, as it was. */+function collapsedField(property: unknown): unknown {+ if (!isObject(property) || !("type" in property)) return property;+ const listOfObjects = isObject(property.items) && (isObject(property.items.properties) || isObject(property.items.additionalProperties));+ const nested = isObject(property.properties) || isObject(property.additionalProperties) || listOfObjects+ || Array.isArray(property.anyOf) || Array.isArray(property.oneOf) || Array.isArray(property.allOf);+ if (!nested) return property;+ const kept: Json = Object.fromEntries(["type", "enum"].filter((key) => key in property).map((key) => [key, property[key]]));+ return listOfObjects ? { ...kept, items: { type: "object" } } : kept;+}++/** A schema with each top-level field collapsed as above; the field names and `required` as they were. The handler still+ * checks every nested field. */+function withTopLevelFields(schema: unknown): unknown {+ if (!isObject(schema) || !isObject(schema.properties)) return schema;+ return { ...schema, properties: Object.fromEntries(Object.entries(schema.properties).map(([name, property]) => [name, collapsedField(property)])) };+}++/** How much of each tool a list keeps: description lengths in characters (Infinity keeps all), whether schema+ * annotations are left out, and whether tools other than PROTECTED_TOOLS keep only their top-level fields. */+export interface DescriptionLevel { parameters: number; tools: number; annotations?: boolean; topLevelOnly?: boolean }export const FULL_DESCRIPTIONS: DescriptionLevel = { parameters: Infinity, tools: Infinity };export function withDescriptionLevel<T extends ListedTool>(tools: readonly T[], level: DescriptionLevel): T[] {+ const annotations = level.annotations === true;return tools.map((tool) => {const description = typeof tool.description === "string" ? cutText(tool.description, level.tools) ?? "" : tool.description;- const inputSchema = level.parameters === Infinity ? tool.inputSchema : withParameterDescriptions(tool.inputSchema, level.parameters);+ let inputSchema = level.parameters === Infinity && !annotations ? tool.inputSchema : withSchemaLevel(tool.inputSchema, level.parameters, annotations);+ if (level.topLevelOnly && !PROTECTED_TOOLS.includes(tool.name)) inputSchema = withTopLevelFields(inputSchema);return description === tool.description && inputSchema === tool.inputSchema ? tool : { ...tool, description, inputSchema };});}@@ -124,21 +155,27 @@ function largestFitting(low: number, high: number, fits: (value: number) => boolreturn low;}-/** The least cut that brings `tools` (already compacted) to `budget` bytes: parameter descriptions first, then tool- * descriptions down to TOOL_DESCRIPTION_FLOOR. `fits` is false when even that is over. */+/** The least cut that brings `tools` (already compacted) to `budget` bytes, each step only when the one before is not+ * enough: schema annotations; parameter descriptions; tool descriptions down to TOOL_DESCRIPTION_FLOOR, then down to+ * TOOL_DESCRIPTION_MIN; then nested fields, PROTECTED_TOOLS aside. `fits` is false when even that is over. */export function descriptionLevelFor(tools: readonly ListedTool[], budget: number): { level: DescriptionLevel; fits: boolean } {const bytesAt = (level: DescriptionLevel) => definitionListBytes(withDescriptionLevel(tools, level));if (bytesAt(FULL_DESCRIPTIONS) <= budget) return { level: FULL_DESCRIPTIONS, fits: true };+ const plain = { parameters: Infinity, tools: Infinity, annotations: true };+ if (bytesAt(plain) <= budget) return { level: plain, fits: true };const maxParameter = longest(tools, (tool) => parameterDescriptions(tool.inputSchema));- if (bytesAt({ parameters: 0, tools: Infinity }) <= budget) {- const parameters = largestFitting(0, maxParameter, (chars) => bytesAt({ parameters: chars, tools: Infinity }) <= budget);- return { level: { parameters, tools: Infinity }, fits: true };+ if (bytesAt({ ...plain, parameters: 0 }) <= budget) {+ const parameters = largestFitting(0, maxParameter, (chars) => bytesAt({ ...plain, parameters: chars }) <= budget);+ return { level: { ...plain, parameters }, fits: true };}- const floor = { parameters: 0, tools: TOOL_DESCRIPTION_FLOOR };- if (bytesAt(floor) > budget) return { level: floor, fits: false };const maxTool = longest(tools, (tool) => (typeof tool.description === "string" ? [tool.description] : []));- const chars = largestFitting(TOOL_DESCRIPTION_FLOOR, Math.max(TOOL_DESCRIPTION_FLOOR, maxTool), (max) => bytesAt({ parameters: 0, tools: max }) <= budget);- return { level: { parameters: 0, tools: chars }, fits: true };+ const shortest = (floor: number) => largestFitting(floor, Math.max(floor, maxTool), (max) => bytesAt({ ...plain, parameters: 0, tools: max }) <= budget);+ if (bytesAt({ ...plain, parameters: 0, tools: TOOL_DESCRIPTION_FLOOR }) <= budget) return { level: { ...plain, parameters: 0, tools: shortest(TOOL_DESCRIPTION_FLOOR) }, fits: true };+ if (bytesAt({ ...plain, parameters: 0, tools: TOOL_DESCRIPTION_MIN }) <= budget) return { level: { ...plain, parameters: 0, tools: shortest(TOOL_DESCRIPTION_MIN) }, fits: true };+ const floor = { ...plain, parameters: 0, tools: TOOL_DESCRIPTION_MIN, topLevelOnly: true };+ if (bytesAt(floor) > budget) return { level: floor, fits: false };+ const chars = largestFitting(TOOL_DESCRIPTION_MIN, Math.max(TOOL_DESCRIPTION_MIN, maxTool), (max) => bytesAt({ ...floor, tools: max }) <= budget);+ return { level: { ...floor, tools: chars }, fits: true };}/** A protected tool as small as it gets while still naming every top-level field, its type and its choices: its first@@ -146,26 +183,30 @@ export function descriptionLevelFor(tools: readonly ListedTool[], budget: number* handler still checks every nested field and answers a wrong one with what it expects. */function smallest<T extends ListedTool>(tool: T): T {const description = typeof tool.description === "string" ? cutText(tool.description.split(/(?<=[.!?])\s/)[0] ?? "", TOOL_DESCRIPTION_FLOOR) ?? "" : tool.description;- const schema = tool.inputSchema;- if (!isObject(schema) || !isObject(schema.properties)) return { ...tool, description };- const properties = Object.fromEntries(Object.entries(schema.properties).map(([name, property]) => {- if (!isObject(property)) return [name, property];- const nested = isObject(property.properties) || (isObject(property.items) && isObject(property.items.properties)) || isObject(property.additionalProperties);- return [name, nested ? Object.fromEntries(["type", "enum"].filter((key) => key in property).map((key) => [key, property[key]])) : property];- }));- return { ...tool, description, inputSchema: { ...schema, properties } };+ return { ...tool, description, inputSchema: withTopLevelFields(tool.inputSchema) };+}++/** What `tools` come to at the deepest cut there is, protected tools kept whole. */+export function toolListFloorBytes(tools: readonly ListedTool[]): number {+ return definitionListBytes(withDescriptionLevel(withCompactSchemas(tools), { parameters: 0, tools: TOOL_DESCRIPTION_MIN, annotations: true, topLevelOnly: true }));}export interface FittedToolList<T> { tools: T[]; bytes: number; from: number; level: DescriptionLevel; fits: boolean }/** `tools` as this engine is shown them within `share` bytes. A list that cannot fit keeps every tool at its shortest,- * with PROTECTED_TOOLS shrunk further, so the engine's largest-first drop takes others before them. */+ * with PROTECTED_TOOLS shrunk further; another tool keeps its nested fields only where leaving them out would take it+ * below the largest protected tool, so the engine's largest-first drop still takes it before them. */export function fitToolListToShare<T extends ListedTool>(tools: readonly T[], share: number): FittedToolList<T> {const compacted = withCompactSchemas(tools);const from = definitionListBytes(compacted);const { level, fits } = descriptionLevelFor(compacted, share);let fitted = withDescriptionLevel(compacted, level);- if (!fits) fitted = fitted.map((tool) => (PROTECTED_TOOLS.includes(tool.name) ? smallest(tool) : tool));+ if (!fits) {+ const nested = withDescriptionLevel(compacted, { ...level, topLevelOnly: false });+ fitted = fitted.map((tool, index) => (PROTECTED_TOOLS.includes(tool.name) ? smallest(nested[index]!) : tool));+ const largestProtected = Math.max(0, ...fitted.filter((tool) => PROTECTED_TOOLS.includes(tool.name)).map(definitionBytes));+ fitted = fitted.map((tool, index) => (definitionBytes(tool) < largestProtected && definitionBytes(nested[index]!) >= largestProtected ? nested[index]! : tool));+ }return { tools: fitted, bytes: definitionListBytes(fitted), from, level, fits };}diff --git a/server/tool-list-share.test.ts b/server/tool-list-share.test.tsnew file mode 100644index 0000000000..abfecaa923--- /dev/null+++ b/server/tool-list-share.test.ts@@ -0,0 +1,79 @@+import { mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { createToolListNormalizer } from "./mcp-tool-schema.ts";+import { workspaceAppsLikeCatalog } from "./testing/workspace-apps-like-catalog.ts";+import { definitionListBytes, type ListedTool } from "./tool-list-budget.ts";+import {+ readRecordedToolList, TOOL_LIST_RECORD_ENV, TOOL_LIST_SHARE_ENV, toolsForSessionShare, toolsListResultForSessionShare,+} from "./tool-list-share.ts";++type Json = Record<string, unknown>;+const apps = workspaceAppsLikeCatalog();+const names = (tools: readonly unknown[]) => (tools as ListedTool[]).map((tool) => tool.name);+const folder = () => mkdtempSync(join(tmpdir(), "tls-"));++describe("a relayed server's share of the session's tool budget", () => {+ it("leaves a list alone when the session gave no share and asked for no record", () => {+ const result = { tools: apps };+ expect(toolsListResultForSessionShare(result, {})).toBe(result);+ });++ it("fits a connected-apps list into its share: every tool, its name and its required fields kept", () => {+ const share = 26_000;+ expect(definitionListBytes(apps)).toBeGreaterThan(share * 4);+ const fitted = toolsForSessionShare(apps, { [TOOL_LIST_SHARE_ENV]: String(share) }) as ListedTool[];+ expect(names(fitted)).toEqual(names(apps));+ expect(definitionListBytes(fitted)).toBeLessThanOrEqual(share);+ fitted.forEach((tool, index) => {+ const schema = tool.inputSchema as Json;+ const original = apps[index]!.inputSchema as Json;+ expect(schema.required).toEqual(original.required);+ expect(Object.keys(schema.properties as Json)).toEqual(Object.keys(original.properties as Json));+ expect((tool.description ?? "").length).toBeGreaterThan(0);+ });+ });++ it("says by how much a list is over its share at its shortest, and still lists every tool", () => {+ const logged: string[] = [];+ const fitted = toolsForSessionShare(apps, { [TOOL_LIST_SHARE_ENV]: "5000" }, (line) => logged.push(line));+ expect(names(fitted)).toEqual(names(apps));+ expect(logged).toEqual([expect.stringMatching(/^tool list is \d+ bytes at its shortest, \d+ over its 5000-byte share of the session's tool budget$/)]);+ });++ it("records the list it relays, before its share, for the next session to size", () => {+ const record = join(folder(), "records", "composio.json");+ toolsForSessionShare(apps, { [TOOL_LIST_SHARE_ENV]: "20000", [TOOL_LIST_RECORD_ENV]: record });+ expect(readRecordedToolList(record)).toEqual(apps.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })));+ });++ it("still fits its list when the record cannot be written, and reads nothing from a damaged record", () => {+ const blocked = join(folder(), "file");+ writeFileSync(blocked, "not a folder");+ const fitted = toolsForSessionShare(apps, { [TOOL_LIST_SHARE_ENV]: "26000", [TOOL_LIST_RECORD_ENV]: join(blocked, "record.json") });+ expect(names(fitted)).toEqual(names(apps));+ const damaged = join(folder(), "damaged.json");+ writeFileSync(damaged, "{\"tools\": [{\"description\": 1}]}");+ expect(readRecordedToolList(damaged)).toBeUndefined();+ expect(readRecordedToolList(join(folder(), "missing.json"))).toBeUndefined();+ });++ it("leaves a page of a longer list as it came", () => {+ const page = { tools: apps.slice(0, 10), nextCursor: "2" };+ expect(toolsListResultForSessionShare(page, { [TOOL_LIST_SHARE_ENV]: "100" })).toBe(page);+ });++ it("fits a bridged server's list after its profile, on its last page only", () => {+ const share = (tools: unknown[]) => toolsForSessionShare(tools, { [TOOL_LIST_SHARE_ENV]: "26000" });+ const normalizer = createToolListNormalizer(undefined, undefined, [], share);+ normalizer.observeRequest(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }));+ const listed = JSON.parse(normalizer.rewriteResponse(JSON.stringify({ jsonrpc: "2.0", id: 1, result: { tools: apps } }))) as { result: { tools: ListedTool[] } };+ expect(names(listed.result.tools)).toEqual(names(apps));+ expect(definitionListBytes(listed.result.tools)).toBeLessThanOrEqual(26_000);+ normalizer.observeRequest(JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list" }));+ const first = JSON.stringify({ jsonrpc: "2.0", id: 2, result: { tools: apps.slice(0, 3), nextCursor: "next" } });+ expect(JSON.parse(normalizer.rewriteResponse(first)).result.tools).toEqual(apps.slice(0, 3));+ });+});diff --git a/server/tool-list-share.ts b/server/tool-list-share.tsnew file mode 100644index 0000000000..f7c07b78b9--- /dev/null+++ b/server/tool-list-share.ts@@ -0,0 +1,68 @@+// A relayed MCP server's part of a session's tool budget, for the servers OpenMausBot relays but does not serve:+// connected apps and the person's own servers. The session gives each relay its share in bytes and a file to record+// the list it relays; the relay fits what it lists into the share, and the record sizes the share the next session+// gives it.+import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";+import { dirname } from "node:path";++import { fitToolListToShare, type ListedTool } from "./tool-list-budget.ts";++export const TOOL_LIST_SHARE_ENV = "OMB_TOOL_LIST_SHARE";+export const TOOL_LIST_RECORD_ENV = "OMB_TOOL_LIST_RECORD";++const RECORD_MAX_BYTES = 2 * 1024 * 1024;++function isTool(value: unknown): value is ListedTool {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && typeof (value as { name?: unknown }).name === "string";+}++export function toolListShareFromEnv(env: Record<string, string | undefined>): number | undefined {+ const value = env[TOOL_LIST_SHARE_ENV];+ return value !== undefined && /^\d{1,9}$/.test(value) ? Number(value) : undefined;+}++/** The tool list last recorded at `path`, or undefined when there is none that can be read. */+export function readRecordedToolList(path: string): ListedTool[] | undefined {+ try {+ if (statSync(path).size > RECORD_MAX_BYTES) return undefined;+ const tools = (JSON.parse(readFileSync(path, "utf8")) as { tools?: unknown }).tools;+ return Array.isArray(tools) && tools.every(isTool) ? tools : undefined;+ } catch {+ return undefined;+ }+}++function record(path: string, tools: readonly ListedTool[]): void {+ try {+ const text = JSON.stringify({ tools: tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) });+ if (Buffer.byteLength(text) > RECORD_MAX_BYTES) return;+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });+ const staged = `${path}.${process.pid}.tmp`;+ writeFileSync(staged, text, { mode: 0o600 });+ renameSync(staged, path);+ } catch {+ // A relay that cannot write (a read-only sandbox) still fits its list; the next session sizes it by its reserve.+ }+}++/** A relay's tools as the engine is shown them: recorded when the session asked, then fitted into its share. */+export function toolsForSessionShare(tools: readonly unknown[], env: Record<string, string | undefined>, log?: (line: string) => void): unknown[] {+ const share = toolListShareFromEnv(env);+ const path = env[TOOL_LIST_RECORD_ENV];+ if (share === undefined && !path) return [...tools];+ if (!tools.every(isTool)) return [...tools];+ if (path) record(path, tools);+ if (share === undefined) return [...tools];+ const fitted = fitToolListToShare(tools, share);+ if (!fitted.fits) log?.(`tool list is ${fitted.bytes} bytes at its shortest, ${fitted.bytes - share} over its ${share}-byte share of the session's tool budget`);+ return fitted.tools;+}++/** A tools/list result fitted the same way; anything else, or a page of a longer list, as it came. */+export function toolsListResultForSessionShare(result: unknown, env: Record<string, string | undefined>, log?: (line: string) => void): unknown {+ if (!result || typeof result !== "object" || Array.isArray(result)) return result;+ if (toolListShareFromEnv(env) === undefined && !env[TOOL_LIST_RECORD_ENV]) return result;+ const listing = result as { tools?: unknown; nextCursor?: unknown };+ if (!Array.isArray(listing.tools) || listing.nextCursor !== undefined) return result;+ return { ...listing, tools: toolsForSessionShare(listing.tools, env, log) };+}