Skip to content

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

Phones: read a bot's MCP servers (names and switches only) (#4076)

Omkar Satpute99b61dcfba16
diff --git a/companion/src/routes.ts b/companion/src/routes.ts
index 01bea9b4e1..ebed3a2b85 100644
--- a/companion/src/routes.ts
+++ b/companion/src/routes.ts
@@ -123,6 +123,9 @@ const ALLOWED: ReadonlyArray<{ method: string; path: RegExp }> = [
{ method: "GET", path: /^\/api\/bots\/[\w-]+\/overview$/ },
// Read-only: no settings reachable through it.
{ method: "GET", path: /^\/api\/bots\/[\w-]+\/activity$/ },
+ // Names and on/off only. The MCP settings list, which carries commands and
+ // addresses, stays closed.
+ { method: "GET", path: /^\/api\/bots\/[\w-]+\/mcp-servers$/ },
// Team memory edits are content, not execution policy. The section rides as
// a query string.
{ method: "GET", path: /^\/api\/team-memory$/ },
diff --git a/companion/test/routes.test.ts b/companion/test/routes.test.ts
index 74b094ad9c..cd36d40a05 100644
--- a/companion/test/routes.test.ts
+++ b/companion/test/routes.test.ts
@@ -54,6 +54,7 @@ describe("what the app may do", () => {
["POST", "/api/bots/bot_123/messages/msg_2/edit"],
["GET", "/api/bots/bot_123/overview"],
["GET", "/api/bots/bot_123/activity"],
+ ["GET", "/api/bots/bot_123/mcp-servers"],
["GET", "/api/team-memory"],
["POST", "/api/team-memory"],
["PATCH", "/api/team-memory/entry_1"],
@@ -166,6 +167,26 @@ describe("what it may not", () => {
});
});
+ it("reads a bot's MCP servers and nothing of MCP settings", () => {
+ expect(ask("GET", "/api/bots/bot_123/mcp-servers", false)?.status).toBe(401);
+ for (const [method, path] of [
+ ["POST", "/api/bots/bot_123/mcp-servers"],
+ ["PATCH", "/api/bots/bot_123/mcp-servers"],
+ ["PUT", "/api/bots/bot_123/mcp-servers"],
+ ["DELETE", "/api/bots/bot_123/mcp-servers"],
+ ["GET", "/api/bots/bot_123/mcp-servers/warehouse"],
+ ["GET", "/api/bots/bot_123/../mcp-servers"],
+ ["GET", "/api/mcp/servers"],
+ ["POST", "/api/mcp/servers"],
+ ["POST", "/api/mcp/servers/import"],
+ ["PATCH", "/api/mcp/servers/warehouse"],
+ ["POST", "/api/mcp/servers/warehouse/test"],
+ ["POST", "/api/mcp/servers/warehouse/sign-in"],
+ ] as Array<[string, string]>) {
+ expect(allowed(method, path), `${method} ${path}`).toBe(false);
+ }
+ });
+
it("keeps endpoint refresh authenticated and exact-method only", () => {
expect(ask("GET", "/api/companion/endpoints", false)?.status).toBe(401);
expect(ask("GET", "/api/companion/endpoints")).toBeNull();
diff --git a/docs/ios-companion.md b/docs/ios-companion.md
index 0b941de244..0be1c8f95f 100644
--- a/docs/ios-companion.md
+++ b/docs/ios-companion.md
@@ -403,6 +403,15 @@ The phone registers the apps it allows with `PUT /api/phones/self`. Behind the s
Bots see these apps as `PHONE_*` tools through the `device` MCP kind. Reads run silently and writes show up as activity rows. A send opens a sheet on the phone and goes only when the person taps Send there; OpenMausBot adds no card of its own. A turn that came from the phone does phone things on the phone; a turn at the computer works the usual way and changes the phone only when the person names it. Only the owner's phone is reachable, so team Clouds never expose it. The contract fixture `server/testing/fixtures/phone-jobs.json` is what the phone apps copy into their own test fixtures.
+## A bot's MCP servers
+
+The bot panel's Apps page reads `GET /api/bots/:id/mcp-servers`. It answers `{ servers: [{ name, enabled, on, offFor? }] }`
+for every bot's servers and the bot's own, in the order MCP server settings list them. `enabled` is the switch in
+those settings. `on` is the bot's switch: the server is enabled and in the bot's `mcpServers` list (no list means
+every enabled server). `offFor: true` means the server doesn't start for this bot. A bot that doesn't exist is a 404.
+Like the bot's overview it needs the admin scope, so a Team Cloud member's session is refused whichever bot it names.
+`GET /api/mcp/servers` stays closed to phones, since it carries each server's command, arguments and address.
+
## Source layout
```text
diff --git a/server/index.ts b/server/index.ts
index 193d164211..af0c068bcc 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -12530,7 +12530,7 @@ ROUTES.push(createInstanceRoutes({
cliProbeEnvironment, threadBusy, botForThread, activeGroupTurnForBot, checkInstance: testedAi.check,
}));
ROUTES.push(createMcpServerRoutes({
- cfg, sessions, mcpOAuth, teamConnections,
+ cfg, bot: (id) => store.bot(id), sessions, mcpOAuth, teamConnections,
cloudHome: CLOUD_HOME,
fallbackPublicUrl: FALLBACK_PUBLIC_URL,
mcpConfigBusy: { get: () => mcpConfigBusy, set: (busy) => { mcpConfigBusy = busy; } },
diff --git a/server/mcp-registry.ts b/server/mcp-registry.ts
index 97627fea9f..a24179a089 100644
--- a/server/mcp-registry.ts
+++ b/server/mcp-registry.ts
@@ -72,7 +72,7 @@ export function isRemoteMcpServer(server: McpServerSpec): server is RemoteMcpSpe
}
/** Whether `botId` may start this server: every bot may start one that is no bot's own. */
-export function mcpServerServes(server: McpServerSpec & { bot?: string }, botId: string | undefined): boolean {
+export function mcpServerServes(server: object & { bot?: string }, botId: string | undefined): boolean {
return !server.bot || server.bot === botId;
}
diff --git a/server/request-auth.test.ts b/server/request-auth.test.ts
index 645fad73ba..a4c765277a 100644
--- a/server/request-auth.test.ts
+++ b/server/request-auth.test.ts
@@ -139,7 +139,7 @@ describe("scopes", () => {
["POST", "/api/team-library/github"], ["POST", "/api/team-library/grok"], ["GET", "/api/team-library/cursor"],
["POST", "/api/team-library/cursor/sign-in"], ["POST", "/api/team-library/cursor/sign-out"],
["GET", "/api/bots/x/memory"], ["PUT", "/api/bots/x/memory"], ["PUT", "/api/section-context"], ["GET", "/api/threads/t/events"],
- ["GET", "/api/mcp/servers"], ["POST", "/api/mcp/servers"], ["POST", "/api/connectors/slack/authorize"],
+ ["GET", "/api/mcp/servers"], ["POST", "/api/mcp/servers"], ["GET", "/api/bots/x/mcp-servers"], ["POST", "/api/connectors/slack/authorize"],
["POST", "/api/bots/x/slack-management"], ["GET", "/api/bots/x/slack-management/extra"],
["PUT", "/api/config"], ["POST", "/api/auth/pairing"], ["GET", "/api/auth/sessions"], ["DELETE", "/api/auth/sessions/abc"],
["POST", "/api/live/session"], ["POST", "/api/live/call/end"], ["GET", "/api/live/call"], ["PATCH", "/api/live/settings"],
diff --git a/server/routes/mcp-servers.test.ts b/server/routes/mcp-servers.test.ts
index b2fd84ea52..e6491204d4 100644
--- a/server/routes/mcp-servers.test.ts
+++ b/server/routes/mcp-servers.test.ts
@@ -23,19 +23,22 @@ afterEach(async () => {
if (active) await new Promise<void>((resolve, reject) => active.close((error) => error ? reject(error) : resolve()));
});
-async function serve(options: { botsPath?: () => BrokerPath | null } = {}) {
+type Bot = { id: string; mcpServers?: string[] };
+
+async function serve(options: { botsPath?: () => BrokerPath | null; bots?: Bot[]; listed?: Record<string, Record<string, unknown>> } = {}) {
const cfg: Pick<AppConfig, "mcpServers"> = { mcpServers: {} };
const changes: string[] = [];
let busy = false;
const route = createMcpServerRoutes({
cfg,
+ bot: (id) => options.bots?.find((bot) => bot.id === id) ?? null,
sessions: { isLive: () => true },
mcpOAuth: new McpOAuthManager({ file: join(DATA_DIR, "mcp-route-oauth.json") }),
teamConnections: { personMcp: () => ["private"], people: {} as TeamConnectionsHost["people"] },
cloudHome: null,
fallbackPublicUrl: null,
mcpConfigBusy: { get: () => busy, set: (value) => { busy = value; } },
- mcpServerResponse: () => ({ servers: listMcpServers(cfg.mcpServers) }),
+ mcpServerResponse: () => ({ servers: listMcpServers(cfg.mcpServers).map((server) => ({ ...server, ...options.listed?.[server.name] })) }),
mcpPolicyRefusal: () => undefined,
persistMcpServers: (next) => { cfg.mcpServers = next; },
savedCustomDomain: () => null,
@@ -55,7 +58,7 @@ async function serve(options: { botsPath?: () => BrokerPath | null } = {}) {
const post = (path: string, body: unknown) => fetch(`${base}${path}`, {
method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
});
- return { cfg, post, changes, get: () => fetch(`${base}/api/mcp/servers`), remove: (name: string) => fetch(`${base}/api/mcp/servers/${name}`, { method: "DELETE" }) };
+ return { cfg, post, changes, base, get: () => fetch(`${base}/api/mcp/servers`), remove: (name: string) => fetch(`${base}/api/mcp/servers/${name}`, { method: "DELETE" }) };
}
it("says when a server is added, imported or removed on purpose, so a Cloud home's routines can wait while none is left", async () => {
@@ -103,6 +106,77 @@ it.each(["create", "import"])("accepts blank personal headers on %s and retains
}
});
+describe("a bot's MCP servers, as a phone reads them", () => {
+ const SERVERS = {
+ warehouse: { command: "npx", args: ["-y", "warehouse-mcp", "--token", "wh-arg-secret"], env: { WAREHOUSE_KEY: "wh-env-secret" }, enabled: true },
+ ada_notes: { command: "node", args: ["notes.js"], env: {}, enabled: true, bot: "ada" },
+ bea_files: { command: "node", args: ["files.js"], env: {}, enabled: true, bot: "bea" },
+ tickets: {
+ type: "http", url: "https://tickets.example.com/mcp?key=url-secret", headers: { Authorization: "Bearer header-secret" }, enabled: true,
+ oauth: { clientId: "tickets-client", clientSecret: "oauth-secret", scopes: ["read"] },
+ },
+ archive: { command: "node", args: ["archive.js"], env: {}, enabled: false },
+ };
+ async function servers(bot: Bot, listed?: Record<string, Record<string, unknown>>) {
+ const { cfg, base } = await serve({ bots: [bot, { id: "bea" }], ...(listed ? { listed } : {}) });
+ cfg.mcpServers = structuredClone(SERVERS);
+ return fetch(`${base}/api/bots/${bot.id}/mcp-servers`);
+ }
+
+ it("lists every bot's servers and the bot's own, in settings order, with every enabled one on when the bot has no list", async () => {
+ const response = await servers({ id: "ada" });
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ servers: [
+ { name: "warehouse", enabled: true, on: true },
+ { name: "ada_notes", enabled: true, on: true },
+ { name: "tickets", enabled: true, on: true },
+ { name: "archive", enabled: false, on: false },
+ ] });
+ });
+
+ it("turns on only the enabled servers in the bot's list", async () => {
+ expect(await (await servers({ id: "ada", mcpServers: ["tickets", "archive", "bea_files"] })).json()).toEqual({ servers: [
+ { name: "warehouse", enabled: true, on: false },
+ { name: "ada_notes", enabled: true, on: false },
+ { name: "tickets", enabled: true, on: true },
+ { name: "archive", enabled: false, on: false },
+ ] });
+ const none = await (await servers({ id: "ada", mcpServers: [] })).json() as { servers: { on: boolean }[] };
+ expect(none.servers.map((server) => server.on)).toEqual([false, false, false, false]);
+ });
+
+ it("marks a server that doesn't start for this bot, and not for the bots it starts for", async () => {
+ const listed = { warehouse: { offFor: ["ada"] }, tickets: { offFor: ["bea"] } };
+ expect(await (await servers({ id: "ada" }, listed)).json()).toEqual({ servers: [
+ { name: "warehouse", enabled: true, on: true, offFor: true },
+ { name: "ada_notes", enabled: true, on: true },
+ { name: "tickets", enabled: true, on: true },
+ { name: "archive", enabled: false, on: false },
+ ] });
+ });
+
+ it("gives names and switches only: no command, arguments, environment, address, headers, sign-in or policy", async () => {
+ const response = await servers({ id: "ada" }, {
+ tickets: { auth: "signed-in", managedBy: "Acme", scope: "team", redirectUri: "https://cloud.example.com/cb" },
+ warehouse: { offFor: ["ada"], managedBy: "Acme" },
+ });
+ const text = await response.text();
+ for (const server of (JSON.parse(text) as { servers: Record<string, unknown>[] }).servers) {
+ expect(Object.keys(server).filter((key) => !["name", "enabled", "on", "offFor"].includes(key)), server.name as string).toEqual([]);
+ }
+ for (const leaked of ["npx", "wh-arg-secret", "WAREHOUSE_KEY", "wh-env-secret", "tickets.example.com", "url-secret", "header-secret", "Authorization", "tickets-client", "oauth-secret", "Acme", "signed-in", "cloud.example.com"]) {
+ expect(text).not.toContain(leaked);
+ }
+ });
+
+ it("answers a bot that doesn't exist as not found", async () => {
+ const { base } = await serve({ bots: [{ id: "ada" }] });
+ const response = await fetch(`${base}/api/bots/nobody/mcp-servers`);
+ expect(response.status).toBe(404);
+ expect(await response.json()).toEqual({ error: "no such bot" });
+ });
+});
+
// The broker listens on a unix socket, which Windows refuses at a file path; the box runs only on a Linux Cloud home.
describe.skipIf(process.platform === "win32")("Test, where bots reach URL servers through the credential broker", () => {
const HEADERS = { Authorization: "Bearer team-orders", "CF-Access-Client-Id": "5c1d0e9a.access", "CF-Access-Client-Secret": "0f9e8d7c6b5a4938271605" };
diff --git a/server/routes/mcp-servers.ts b/server/routes/mcp-servers.ts
index 6091ec162c..03b22e139f 100644
--- a/server/routes/mcp-servers.ts
+++ b/server/routes/mcp-servers.ts
@@ -6,7 +6,7 @@ import type { TeamConnectionsHost } from "../host/team-connections-host.ts";
import { McpOAuthError, McpSignInError, mcpCallbackOrigin, withMcpSignIn, type McpOAuthManager } from "../mcp-oauth.ts";
import { brokeredServer, type BrokerPath } from "../bot-box/broker-probe.ts";
import { probeMcpServer, type McpProbeOptions, type McpProbeResult } from "../mcp-probe.ts";
-import { MAX_MCP_SERVERS, isRemoteMcpServer, mcpServerBody, parseMcpServerMutation, parseMcpServersImport, parseStoredMcpServer, type McpRunsOn, type StoredMcpServer, type StoredRemoteMcpServer } from "../mcp-registry.ts";
+import { MAX_MCP_SERVERS, isRemoteMcpServer, mcpServerBody, mcpServerServes, parseMcpServerMutation, parseMcpServersImport, parseStoredMcpServer, type McpRunsOn, type StoredMcpServer, type StoredRemoteMcpServer } from "../mcp-registry.ts";
import { personKey } from "../person-key.ts";
import { postizKeyHeaders } from "../postiz/connection.ts";
import { isLoopbackHost, isProxied, provesSameOrigin, requestOrigin } from "../request-auth.ts";
@@ -15,8 +15,22 @@ import type { BusyFlag } from "./config.ts";
import { PASS, type RouteHandler } from "./table.ts";
import { sessionMember } from "./team-phone.ts";
+type ListedMcpServer = { name: string; enabled: boolean; bot?: string; offFor?: readonly string[] };
+
+// Security: built field by field, never spread. The settings list carries commands, arguments and addresses that can
+// hold secrets, so it stays closed to phones and this is what they get instead.
+function botMcpServers(listed: readonly ListedMcpServer[], bot: { id: string; mcpServers?: readonly string[] | null }) {
+ return listed.filter((server) => mcpServerServes(server, bot.id)).map((server) => ({
+ name: server.name,
+ enabled: server.enabled,
+ on: server.enabled && (!bot.mcpServers || bot.mcpServers.includes(server.name)),
+ ...(server.offFor?.includes(bot.id) ? { offFor: true as const } : {}),
+ }));
+}
+
export interface McpServerRouteDeps {
cfg: Pick<AppConfig, "mcpServers" | "postiz">;
+ bot(id: string): { id: string; mcpServers?: readonly string[] | null } | null;
sessions: Pick<SessionRegistry, "isLive">;
mcpOAuth: McpOAuthManager;
teamConnections: Pick<TeamConnectionsHost, "personMcp" | "people">;
@@ -24,7 +38,7 @@ export interface McpServerRouteDeps {
fallbackPublicUrl: string | null;
mcpConfigBusy: BusyFlag;
/** Secrets as booleans, sign-in state attached. */
- mcpServerResponse(): Record<string, unknown>;
+ mcpServerResponse(): { servers: readonly ListedMcpServer[] };
mcpPolicyRefusal(name: string, server: object): string | undefined;
persistMcpServers(next: Record<string, unknown>): void;
savedCustomDomain(): string | null;
@@ -89,6 +103,13 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {
return json(res, 200, withServerDetails(mcpServerResponse()));
}
+ const ofBot = /^\/api\/bots\/([\w-]+)\/mcp-servers$/.exec(path);
+ if (method === "GET" && ofBot) {
+ const bot = deps.bot(ofBot[1]!);
+ if (!bot) return json(res, 404, { error: "no such bot" });
+ return json(res, 200, { servers: botMcpServers(mcpServerResponse().servers, bot) });
+ }
+
const mcpTest = /^\/api\/mcp\/servers\/([a-z][a-z0-9_-]{0,31})\/test$/.exec(path);
if (method === "POST" && mcpTest) {
const raw = cfg.mcpServers?.[mcpTest[1]];