Skip to content

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

20.0 KB
Raw Blame
import { mkdtempSync, rmSync } from "node:fs";
import { createServer, request as httpRequest, type RequestOptions, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, describe, expect, it } from "vitest";

import { openCredentialBroker, type CredentialBroker } from "../bot-box/broker.ts";
import type { BrokerPath } from "../bot-box/broker-probe.ts";
import { DATA_DIR, type AppConfig } from "../config.ts";
import { json, readBody } from "../harness/http.ts";
import type { TeamConnectionsHost } from "../host/team-connections-host.ts";
import { McpOAuthManager } from "../mcp-oauth.ts";
import { listMcpServers } from "../mcp-registry.ts";
import { startFakeHttpMcp, type FakeHttpMcp } from "../testing/fake-http-mcp-server.ts";
import { startFakeOAuth } from "../testing/fake-oauth-server.ts";
import { createMcpConfig } from "../host/mcp-config.ts";
import { forgetToolBudgets, noteToolBudget } from "../tool-budgets.ts";
import { createMcpServerRoutes } from "./mcp-servers.ts";
import { dispatchRoutes } from "./table.ts";

let server: Server | undefined;
afterEach(async () => {
  const active = server;
  server = undefined;
  if (active) await new Promise<void>((resolve, reject) => active.close((error) => error ? reject(error) : resolve()));
});

type Bot = { id: string; mcpServers?: string[] };

async function serve(options: { ownsVault?: boolean; keys?: Parameters<typeof createMcpConfig>[0]["keys"]; botsPath?: () => BrokerPath | null; bots?: Bot[]; listed?: Record<string, Record<string, unknown>>; probeAs?: (server: { bot?: string }) => { id?: string; cwd?: string } } = {}) {
  const cfg: Pick<AppConfig, "mcpServers"> = { mcpServers: {} };
  const changes: string[] = [];
  let busy = false;
  const mcpOAuth = new McpOAuthManager({ file: join(DATA_DIR, "mcp-route-oauth.json") });
  const teamConnections = { personMcp: () => ["private"], people: {} as TeamConnectionsHost["people"] };
  const mcpServerResponse = () => ({ servers: listMcpServers(cfg.mcpServers).map((server) => ({ ...server, ...options.listed?.[server.name] })) });
  const sessions = { isLive: () => true };
  const config = createMcpConfig({
    cfg, sessions, mcpOAuth, teamConnections,
    cloudHome: null,
    fallbackPublicUrl: null,
    mcpConfigBusy: { get: () => busy, set: (value) => { busy = value; } },
    mcpServerResponse,
    mcpPolicyRefusal: () => undefined,
    persistMcpServers: (next) => { cfg.mcpServers = next; },
    savedCustomDomain: () => null,
    connectionsChanged: (change) => { changes.push(change); },
    changed: () => {},
    ...(options.botsPath ? { botsPath: options.botsPath } : {}),
    ...(options.probeAs ? { probeAs: options.probeAs } : {}),
    ...(options.keys ? { keys: options.keys } : {}),
  });
  const route = createMcpServerRoutes({
    cfg, bot: (id) => options.bots?.find((bot) => bot.id === id) ?? null, sessions, mcpOAuth, teamConnections,
    cloudHome: null,
    ownsVault: () => options.ownsVault ?? true,
    fallbackPublicUrl: null,
    mcpServerResponse,
    savedCustomDomain: () => null,
    config,
  });
  const active = createServer(async (req, res) => {
    const url = new URL(req.url ?? "/", "http://localhost");
    await dispatchRoutes([route], {
      req, res, url, path: url.pathname, method: req.method ?? "GET",
      auth: { kind: "loopback", scopes: ["admin", "client"] }, json, readBody,
    });
  });
  server = active;
  await new Promise<void>((ready) => active.listen(0, "127.0.0.1", ready));
  const base = `http://127.0.0.1:${(active.address() as AddressInfo).port}`;
  const post = (path: string, body: unknown) => fetch(`${base}${path}`, {
    method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
  });
  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 () => {
  const { post, remove, changes } = await serve();
  const added = await post("/api/mcp/servers", { name: "warehouse", url: "https://data.example.com/mcp", headers: { Authorization: "" } });
  expect(added.status, await added.clone().text()).toBe(201);
  const imported = await post("/api/mcp/servers/import", { json: JSON.stringify({ mcpServers: { nightwatch: { type: "http", url: "https://nightwatch.example.com/mcp" } } }) });
  expect(imported.status, await imported.clone().text()).toBe(201);
  expect((await remove("warehouse")).status).toBe(200);
  expect((await remove("missing")).status).toBe(404);
  expect(changes).toEqual(["added", "added", "removed"]);
});

it("a server arriving from a move is given the Vault items it names, by id only; nothing else in a request grants one", async () => {
  const given: Array<[string, readonly string[]]> = [];
  const { cfg, post, base } = await serve({ keys: { grant: (name: string, items: readonly string[]) => given.push([name, items]), warm: async () => {}, forgetServer: () => {}, resolve: (_n: string, server: object) => ({ ok: true, server }), oauthClient: (_n: string, o: object) => o, usedBy: () => [], given: () => [] } as never });
  const item = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
  const added = await post("/api/mcp/servers", { name: "stripe", command: "npx", args: ["x"], env: { KEY: `vault:${item}` }, vaultKeys: [item, "not an id", 7] });
  expect(added.status, await added.clone().text()).toBe(201);
  expect(given).toEqual([["stripe", [item]]]);
  expect((cfg.mcpServers as Record<string, { env: Record<string, string> }>).stripe.env).toEqual({ KEY: `vault:${item}` });
  given.length = 0;
  expect((await fetch(`${base}/api/mcp/servers/stripe`, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ command: "npx", args: ["y"], env: { KEY: true } }) })).status).toBe(200);
  expect(given).toEqual([]);
  const replaced = await fetch(`${base}/api/mcp/servers/stripe`, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ command: "npx", args: ["y"], env: { KEY: true }, vaultKeys: [item] }) });
  expect(replaced.status, await replaced.clone().text()).toBe(200);
  expect(given).toEqual([["stripe", [item]]]);
});

it("a Team Cloud takes no vaultKeys: an admin's server can't be given a member's saved secret", async () => {
  const given: Array<[string, readonly string[]]> = [];
  const { post } = await serve({ ownsVault: false, keys: { grant: (name: string, items: readonly string[]) => given.push([name, items]), warm: async () => {}, forgetServer: () => {}, resolve: (_n: string, server: object) => ({ ok: true, server }), oauthClient: (_n: string, o: object) => o, usedBy: () => [], given: () => [] } as never });
  const item = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
  const added = await post("/api/mcp/servers", { name: "stripe", command: "npx", args: ["x"], env: { KEY: `vault:${item}` }, vaultKeys: [item] });
  expect(added.status, await added.clone().text()).toBe(201);
  expect(given).toEqual([]);
});

it("adds a command server sent with type stdio, as other MCP clients write it, and keeps the old shape working", async () => {
  const { cfg, post } = await serve();
  const typed = await post("/api/mcp/servers", { name: "notes", type: "stdio", command: "npx", args: ["-y", "notes-mcp"] });
  expect(typed.status, await typed.clone().text()).toBe(201);
  const plain = await post("/api/mcp/servers", { name: "files", command: "npx", args: ["-y", "files-mcp"] });
  expect(plain.status, await plain.clone().text()).toBe(201);
  expect(cfg.mcpServers).toEqual({
    notes: { command: "npx", args: ["-y", "notes-mcp"], env: {}, enabled: false },
    files: { command: "npx", args: ["-y", "files-mcp"], env: {}, enabled: false },
  });
});

it.each([["private", "person"], ["public", "team"]])("lists the scope of %s in reads and mutation responses", async (name, scope) => {
  const { post, get } = await serve();
  const response = await post("/api/mcp/servers", { name, url: "https://mail.example.com/mcp", headers: { Authorization: "" } });
  expect(response.status).toBe(201);
  expect(await response.json()).toMatchObject({ servers: [{ name, scope }] });
  expect(await (await get()).json()).toMatchObject({ servers: [{ name, scope }] });
});

it.each(["create", "import"])("rejects personal header values on %s without saving any server", async (action) => {
  const { cfg, post } = await serve();
  const entry = { url: "https://mail.example.com/mcp", headers: { Authorization: "Bearer private-secret" } };
  const response = action === "create"
    ? await post("/api/mcp/servers", { name: "private", ...entry })
    : await post("/api/mcp/servers/import", { json: JSON.stringify({ mcpServers: { public: { url: "https://public.example.com/mcp" }, private: entry } }) });

  expect(response.status).toBe(400);
  const body = await response.json() as { error: string; errorKey: string };
  expect(body.error).toMatch(/personal.*header|header.*personal/i);
  expect(body.errorKey).toBe("serverError.mcp.personalHeadersShared");
  expect(JSON.stringify(body)).not.toContain("private-secret");
  expect(cfg.mcpServers).toEqual({});
});

it("keeps the sign-in refusal's localization code in the HTTP response", async () => {
  const { post } = await serve();
  expect((await post("/api/mcp/servers", { name: "private", url: "https://mail.example.com/mcp", headers: { Authorization: "" } })).status).toBe(201);
  const response = await post("/api/mcp/servers/private/test", {});
  expect(response.status).toBe(403);
  expect(await response.json()).toEqual({
    error: "Sign in to the team to test your own connection.",
    errorKey: "serverError.mcp.testSignInFirst",
  });
});

it.each(["create", "import"])("accepts blank personal headers on %s and retains team header values", async (action) => {
  const { cfg, post } = await serve();
  for (const [name, value] of [["private", ""], ["public", "Bearer team-secret"]] as const) {
    const entry = { type: "http", url: "https://mail.example.com/mcp", headers: { Authorization: value } };
    const response = action === "create"
      ? await post("/api/mcp/servers", { name, ...entry })
      : await post("/api/mcp/servers/import", { json: JSON.stringify({ mcpServers: { [name]: entry } }) });
    expect(response.status).toBe(201);
    expect(cfg.mcpServers?.[name]).toMatchObject({ headers: { Authorization: value } });
  }
});

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", errorKey: "serverError.bot.missing" });
  });
});

// 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" };
  let dir = "", broker: CredentialBroker | undefined, mcp: FakeHttpMcp | undefined;
  afterEach(async () => {
    await broker?.close();
    await mcp?.close();
    broker = undefined; mcp = undefined;
    if (dir) rmSync(dir, { recursive: true, force: true });
  });
  /** A broker; `slash` forwards a request for the server's own address with a slash added, as the broker once did. */
  async function brokerPath(slash = false): Promise<BrokerPath> {
    dir = mkdtempSync(join(tmpdir(), "omb-mcp-test-route-"));
    const request = ((target: RequestOptions, callback: Parameters<typeof httpRequest>[1]) =>
      httpRequest({ ...target, path: slash ? String(target.path).replace(/^\/mcp(?=\?|$)/, "/mcp/") : target.path }, callback as never)) as typeof httpRequest;
    broker = await openCredentialBroker({ socketPath: join(dir, "b.sock"), request });
    return { broker: { port: 18080, mintForThread: broker.mintForThread, revokeThread: broker.revokeThread }, socketPath: broker.socketPath };
  }
  async function tested(path: BrokerPath, url: string) {
    const route = await serve({ botsPath: () => path });
    expect((await route.post("/api/mcp/servers", { name: "orders", type: "http", url, headers: HEADERS })).status).toBe(201);
    return await (await route.post("/api/mcp/servers/orders/test", {})).json() as Record<string, unknown>;
  }

  it("connects through the broker, which adds the server's headers, as a bot's turn does", async () => {
    mcp = await startFakeHttpMcp({ exactPath: true, tools: [{ name: "lookup_order" }], requireHeaders: HEADERS });
    expect(await tested(await brokerPath(), mcp.url)).toMatchObject({ ok: true, tools: [{ name: "lookup_order" }] });
    expect(broker!.stats(), "every request went through the broker, and its grant is gone").toMatchObject({ tokens: 0 });
    expect(broker!.stats().forwarded).toBeGreaterThanOrEqual(2);
  });

  it("asks for a sign-in from a server that lists tools to anyone and refuses calls, with no 'fault is ours' fallback", async () => {
    const issuer = await startFakeOAuth();
    mcp = await startFakeHttpMcp({ exactPath: true, guard: "tools/call", acceptBearer: issuer.isValid, wwwAuthenticate: issuer.challenge, tools: [{ name: "buy" }] });
    try {
      const path = await brokerPath();
      const route = await serve({ botsPath: () => path });
      expect((await route.post("/api/mcp/servers", { name: "shop", type: "http", url: mcp.url, headers: {} })).status).toBe(201);
      const result = await (await route.post("/api/mcp/servers/shop/test", {})).json();
      expect(result).toEqual({ ok: false, auth: "required", error: "This server needs you to sign in." });
      expect(mcp.refusedCalls).toHaveLength(1);
      expect(mcp.calls).toEqual([]);
      expect(broker!.stats().forwarded).toBeGreaterThanOrEqual(4);
    } finally {
      await issuer.close();
    }
  });

  it("never says Connected when bots can't reach a server that answers directly, and says the fault is ours", async () => {
    mcp = await startFakeHttpMcp({ exactPath: true, tools: [{ name: "lookup_order" }], requireHeaders: HEADERS });
    const result = await tested(await brokerPath(true), mcp.url);
    expect(result).toEqual({ ok: false, reason: "unreachable", error: "Your bots can't reach this server: The server answered HTTP 404. It answers when tested directly, so the fault is on our side, not in your settings: tell us with @devs in any chat." });
  });

  it("says a server that answers neither way can't be reached, as before", async () => {
    mcp = await startFakeHttpMcp({});
    const url = mcp.url;
    await mcp.close();
    mcp = undefined;
    expect(await tested(await brokerPath(), url)).toEqual({ ok: false, error: "Could not reach this address. Check the URL and your network.", reason: "unreachable" });
  });
});

describe("a bot's tool budget and a command server's Test", () => {
  afterEach(() => forgetToolBudgets());

  it("gives a bot's last chat turn's tool budget, nothing before one ran, and not found for no bot", async () => {
    const { base } = await serve({ bots: [{ id: "ada" }] });
    expect(await (await fetch(`${base}/api/bots/ada/tool-budget`)).json()).toEqual({ budget: null });
    const budget = { limit: 128, listed: 127, servers: [{ name: "notes", tools: 124, direct: true }, { name: "sogni", tools: 30, direct: false }] };
    noteToolBudget("ada", budget);
    expect(await (await fetch(`${base}/api/bots/ada/tool-budget`)).json()).toEqual({ budget });
    expect((await fetch(`${base}/api/bots/nobody/tool-budget`)).status).toBe(404);
  });

  it("starts a command server for Test as its bot's turn would", async () => {
    const seen: Array<string | undefined> = [];
    const fake = fileURLToPath(new URL("../testing/fake-mcp-server.ts", import.meta.url));
    const { cfg, post } = await serve({ probeAs: (server) => { seen.push(server.bot ?? "any bot"); return {}; } });
    cfg.mcpServers = {
      notes: { command: process.execPath, args: ["--experimental-strip-types", fake], env: {}, enabled: true },
      own: { command: process.execPath, args: ["--experimental-strip-types", fake], env: {}, enabled: true, bot: "ada" },
    };
    expect(await (await post("/api/mcp/servers/notes/test", {})).json()).toMatchObject({ ok: true, tools: [{ name: "read_notes" }] });
    expect(await (await post("/api/mcp/servers/own/test", {})).json()).toMatchObject({ ok: true });
    expect(seen).toEqual(["any bot", "ada"]);
  });
});