Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Count the MCP server limit per bot, with 100 in all
AdityaUmale8db69909cbd1
diff --git a/server/host/mcp-config.test.ts b/server/host/mcp-config.test.tsindex ed943f0b87..f34dcdb1c2 100644--- a/server/host/mcp-config.test.ts+++ b/server/host/mcp-config.test.ts@@ -172,3 +172,48 @@ describe("shared MCP config", () => {expect(forget).toHaveBeenCalledWith("warehouse");});});++describe("how many MCP servers fit", () => {+ const own = (bot: string): StoredMcpServer => ({ command: "linear-mcp", args: [], env: {}, enabled: false, bot }) as StoredMcpServer;+ const fill = (cfg: { mcpServers?: Record<string, unknown> }, count: number, make: (i: number) => StoredMcpServer, prefix: string) => {+ const next = { ...cfg.mcpServers };+ for (let i = 0; i < count; i++) next[`${prefix}${i}`] = make(i);+ cfg.mcpServers = next as never;+ };++ it("lets each bot have its own servers up to 20 with the shared ones, while other bots can still add theirs", () => {+ const { cfg, config } = fixture();+ fill(cfg, 2, () => remote(), "shared");+ fill(cfg, 18, () => own("bot-a"), "a");+ expect(config.add("a18", own("bot-a"))).toEqual({ status: 400, error: "A bot can use at most 20 MCP servers: the shared ones plus its own." });+ expect(config.add("b0", own("bot-b"))).toMatchObject({ status: 201 });+ fill(cfg, 17, () => own("bot-b"), "b-more");+ expect(Object.keys(cfg.mcpServers ?? {})).toHaveLength(38);+ expect(config.add("c0", own("bot-c"))).toMatchObject({ status: 201 });+ });++ it("refuses a shared server that would take any bot past 20, and keeps the old words when no bot has its own", () => {+ const { cfg, config } = fixture();+ fill(cfg, 20, () => remote(), "s");+ expect(config.add("extra", remote())).toEqual({ status: 400, error: "You can add at most 20 MCP servers." });+ cfg.mcpServers = {};+ fill(cfg, 1, () => remote(), "s");+ fill(cfg, 19, () => own("bot-a"), "a");+ expect(config.add("extra", remote())).toEqual({ status: 400, error: "A bot can use at most 20 MCP servers: the shared ones plus its own." });+ });++ it("holds at most 100 servers in all", () => {+ const { cfg, config } = fixture();+ for (let bot = 0; bot < 5; bot++) fill(cfg, 20, () => own(`bot-${bot}`), `b${bot}-`);+ expect(config.add("one-more", own("bot-new"))).toEqual({ status: 400, error: "You can add at most 100 MCP servers in all." });+ });++ it("an import counts each pasted server against the same limits", async () => {+ const { cfg, config } = fixture();+ fill(cfg, 15, () => own("bot-a"), "a");+ const servers = Object.fromEntries(Array.from({ length: 6 }, (_, i) => [`p${i}`, remote()]));+ expect(await config.addMany(async () => ({ servers }))).toEqual({ status: 400, error: "A bot can use at most 20 MCP servers: the shared ones plus its own." });+ const five = Object.fromEntries(Array.from({ length: 5 }, (_, i) => [`p${i}`, remote()]));+ expect(await config.addMany(async () => ({ servers: five }))).toMatchObject({ status: 201 });+ });+});diff --git a/server/host/mcp-config.ts b/server/host/mcp-config.tsindex 7e0da9d4e8..f2f2c28f61 100644--- a/server/host/mcp-config.ts+++ b/server/host/mcp-config.ts@@ -2,7 +2,7 @@ import { userError, type UserError } from "../user-errors.ts";import { withMcpSignIn, type McpOAuthManager } from "../mcp-oauth.ts";import { brokeredServer, type BrokerPath } from "../bot-box/broker-probe.ts";import { probeMcpServer, sendsCredentials, type McpProbeOptions, type McpProbeResult } from "../mcp-probe.ts";-import { MAX_MCP_SERVERS, isRemoteMcpServer, mcpServerNotFound, parseStoredMcpServer, type McpRunsOn, type StoredMcpServer, type StoredRemoteMcpServer } from "../mcp-registry.ts";+import { isRemoteMcpServer, mcpServerLimitError, mcpServerNotFound, parseStoredMcpServer, type McpRunsOn, type StoredMcpServer, type StoredRemoteMcpServer } from "../mcp-registry.ts";import { postizKeyHeaders } from "../postiz/connection.ts";import type { AppConfig } from "../config.ts";import type { ChatAppsMcp } from "../chat-apps-mcp.ts";@@ -144,9 +144,8 @@ export function createMcpConfig(deps: McpConfigDeps & { changed(): void }): McpCadd: (name, server, keys) => write(() => {const current = cfg.mcpServers ?? {};if (Object.hasOwn(current, name)) return { status: 409, error: "An MCP server with that name already exists." };- if (Object.keys(current).length >= MAX_MCP_SERVERS) {- return { status: 400, error: `You can add at most ${MAX_MCP_SERVERS} MCP servers.` };- }+ const limit = mcpServerLimitError(current, [server]);+ if (limit) return { status: 400, error: limit };const refusal = refused(name, server);if (refusal) return refusal;if (keys) deps.keys?.grant(name, keys);@@ -166,9 +165,8 @@ export function createMcpConfig(deps: McpConfigDeps & { changed(): void }): McpCif (taken.length) {return { status: 409, error: `Already added: ${taken.join(", ")}. Remove or rename ${taken.length === 1 ? "it" : "them"} first.` };}- if (Object.keys(current).length + names.length > MAX_MCP_SERVERS) {- return { status: 400, error: `You can add at most ${MAX_MCP_SERVERS} MCP servers.` };- }+ const limit = mcpServerLimitError(current, Object.values(servers));+ if (limit) return { status: 400, error: limit };const personalRefusal = names.map((name) => personalHeaderRefusal(name, servers[name]!)).find(Boolean);if (personalRefusal) return { status: 400, ...personalRefusal };const blocked = names.filter((name) => mcpPolicyRefusal(name, servers[name] as object));diff --git a/server/mcp-registry.test.ts b/server/mcp-registry.test.tsindex f5699995e0..8ff3fdf9c2 100644--- a/server/mcp-registry.test.ts+++ b/server/mcp-registry.test.ts@@ -4,6 +4,7 @@ import {addDisabledMcpServer,listMcpServers,MAX_MCP_SERVERS,+ mcpSharedServerRoom,mcpServerNameError,parseMcpServerMutation,parseMcpServersImport,@@ -386,3 +387,15 @@ describe("the \"Show its apps in chat\" switch", () => {expect(parseStoredMcpServer("draw", { command: "npx", apps: "no" }).ok).toBe(false);});});++describe("mcpSharedServerRoom", () => {+ const own = (bot: string) => ({ command: "x", args: [], env: {}, enabled: false, bot });+ const shared = { command: "x", args: [], env: {}, enabled: false };+ it("is what is left for every bot: 20 less the shared ones and the most any one bot has of its own, within 100 in all", () => {+ expect(mcpSharedServerRoom({})).toBe(MAX_MCP_SERVERS);+ expect(mcpSharedServerRoom({ s: shared, a1: own("a"), a2: own("a"), b1: own("b") })).toBe(MAX_MCP_SERVERS - 3);+ const full: Record<string, unknown> = {};+ for (let i = 0; i < 100; i++) full[`b${i}`] = own(`bot${i}`);+ expect(mcpSharedServerRoom(full)).toBe(0);+ });+});diff --git a/server/mcp-registry.ts b/server/mcp-registry.tsindex 6d7f140ec4..edcf8fd288 100644--- a/server/mcp-registry.ts+++ b/server/mcp-registry.ts@@ -79,7 +79,39 @@ export function mcpServerServes(server: object & { bot?: string }, botId: stringreturn !server.bot || server.bot === botId;}+/** How many MCP servers one bot can use: the shared ones plus its own. */export const MAX_MCP_SERVERS = 20;+/** How many the whole install can hold, shared and per-bot together. */+export const MAX_MCP_SERVERS_TOTAL = 100;++/** How many servers there are, how many every bot uses, and the most any one bot has of its own. */+function countMcpServers(values: readonly unknown[]): { total: number; shared: number; mostOwn: number } {+ const own = new Map<string, number>();+ let shared = 0;+ for (const value of values) {+ const bot = value && typeof value === "object" ? (value as { bot?: unknown }).bot : undefined;+ if (typeof bot === "string" && bot) own.set(bot, (own.get(bot) ?? 0) + 1);+ else shared++;+ }+ return { total: values.length, shared, mostOwn: Math.max(0, ...own.values()) };+}++/** Why `adding` would not fit next to `current`: at most 100 servers in all, and no bot may use more than 20, the shared ones plus its own. */+export function mcpServerLimitError(current: Record<string, unknown>, adding: readonly unknown[]): string | null {+ const { total, shared, mostOwn } = countMcpServers([...Object.values(current), ...adding]);+ if (total > MAX_MCP_SERVERS_TOTAL) return `You can add at most ${MAX_MCP_SERVERS_TOTAL} MCP servers in all.`;+ if (shared + mostOwn <= MAX_MCP_SERVERS) return null;+ return mostOwn+ ? `A bot can use at most ${MAX_MCP_SERVERS} MCP servers: the shared ones plus its own.`+ : `You can add at most ${MAX_MCP_SERVERS} MCP servers.`;+}++/** How many more shared servers (ones every bot uses) fit next to `current`. */+export function mcpSharedServerRoom(current: Record<string, unknown>): number {+ const { total, shared, mostOwn } = countMcpServers(Object.values(current));+ return Math.max(0, Math.min(MAX_MCP_SERVERS_TOTAL - total, MAX_MCP_SERVERS - shared - mostOwn));+}+const MAX_ARGS = 64;const MAX_ENV = 64;const MAX_HEADERS = 32;@@ -401,11 +433,10 @@ export function addDisabledMcpServer(current: Record<string, unknown>, body: unkif (name && Object.hasOwn(current, name)) {return { ok: false, status: 409, error: "An MCP server with that name already exists." };}- if (Object.keys(current).length >= MAX_MCP_SERVERS) {- return { ok: false, status: 400, error: `You can add at most ${MAX_MCP_SERVERS} MCP servers.` };- }const parsed = parseMcpServerMutation(name, pickMcpServerFields(record));if (!parsed.ok) return { ok: false, status: 400, error: parsed.error };+ const limit = mcpServerLimitError(current, [parsed.server]);+ if (limit) return { ok: false, status: 400, error: limit };if (parsed.server.enabled !== false) return { ok: false, status: 400, error: BOT_CANNOT_SWITCH };return { ok: true, name, server: parsed.server, next: { ...current, [name]: parsed.server } };}diff --git a/server/package-import.ts b/server/package-import.tsindex 99680a2886..02249cec3f 100644--- a/server/package-import.ts+++ b/server/package-import.ts@@ -1,7 +1,7 @@// Packages are untrusted: import only adds new records, sets every privilege-bearing field itself, and rolls back on any failure.import { createHash, randomUUID } from "node:crypto";-import { mcpServerNameError, MAX_MCP_SERVERS, parseStoredMcpServer } from "./mcp-registry.ts";+import { mcpServerNameError, mcpSharedServerRoom, parseStoredMcpServer } from "./mcp-registry.ts";import {AGENT_PARTS, agentReleaseValues, connectionLocalValue, connectionReleaseValue, pair, pairs, playbookValues,ROOM_PARTS, roomReleaseValues, ROUTINE_PARTS, routineReleaseValues, scheduleValue, sha256Hex, TEAM_PARTS,@@ -260,7 +260,7 @@ function runImport(source: ImportSource, options: PackageImportOptions, deps: Paconst next: Record<string, unknown> = { ...deps.mcp.servers() };for (const connection of pkg.connections) {const part = `connections[${connection.key}]`;- if (Object.keys(next).length >= MAX_MCP_SERVERS) {+ if (mcpSharedServerRoom(next) === 0) {skipped.push({ part, reason: "too_many_connections" });continue;}diff --git a/server/setup-import.ts b/server/setup-import.tsindex 3704efbb1e..3bef786857 100644--- a/server/setup-import.ts+++ b/server/setup-import.ts@@ -14,7 +14,7 @@ import { holdsCredential } from "../shared/redact.ts";import { parseSkillMd, SKILL_FILE_MAX_BYTES, type ParsedSkill } from "../shared/skill-md.ts";import { importedSkillIntact, readImportedSkills, storeImportedSkills, type ImportedSkillEntry, type ImportedSkillInput } from "./imported-skills.ts";import { scanSkillFolder } from "./skill-folder.ts";-import { importedMcpServerName, isRemoteMcpServer, MAX_MCP_SERVERS, parseMcpServersImport, parseStoredMcpServer, type StoredMcpServer } from "./mcp-registry.ts";+import { importedMcpServerName, isRemoteMcpServer, mcpSharedServerRoom, parseMcpServersImport, parseStoredMcpServer, type StoredMcpServer } from "./mcp-registry.ts";import { parseToml } from "./toml-lite.ts";/** The file operations finding and copying use, so tests can see every path touched. Each answers null on failure. */@@ -664,7 +664,7 @@ function importTools(machine: SetupMachine, host: SetupHost): NonNullable<SetupItry {const current = host.mcpServers();const { fresh, present, conflicts, refused } = findTools(machine, current, host);- const room = Math.max(0, MAX_MCP_SERVERS - Object.keys(current).length);+ const room = mcpSharedServerRoom(current);const adding = fresh.slice(0, room);let saved = true;if (adding.length) {@@ -692,7 +692,7 @@ export function detectSetup(machine: SetupMachine, host: SetupHost): SetupDetectconst index = readImportedSkills();const skills = findSkills(machine).filter((skill) => freshSkill(skill, index[skill.name])).map(({ name, source }) => ({ name, source }));const current = host.mcpServers();- const tools = Object.keys(current).length < MAX_MCP_SERVERS+ const tools = mcpSharedServerRoom(current) > 0? findTools(machine, current, host).fresh.map(({ name, source }) => ({ name, source })): [];return { skills, tools };