Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(box): the credential broker reaches an MCP server at exactly its own address (#3779)
Milind Soni1fee5d86b2b7
diff --git a/docs/bot-box.md b/docs/bot-box.mdindex 659fc670a3..3621e1c3fa 100644--- a/docs/bot-box.md+++ b/docs/bot-box.md@@ -75,7 +75,10 @@ drops whatever credential header the client sent, adds the real key, and forward(the base URL the server had, or the provider's default); the box cannot choose the upstream. A URL MCP server'sheaders ride the same way (`server/bot-box/broker-mcp.ts`): the turn's server list carries`http://127.0.0.1:18080/b/<token>/mcp-<name>` with no headers, and that token is kept for the conversation's later-turns while the servers are the same, so a long-lived engine process keeps its MCP sessions. Connected apps (Composio,+turns while the servers are the same, so a long-lived engine process keeps its MCP sessions. A request for the grant+itself goes to the upstream exactly as it was given (a server at `/mcp` is reached at `/mcp`, never `/mcp/`, which a+Cloudflare Worker answers with 404), anything below it below that address, with the client's query beside the+upstream's own. Connected apps (Composio,HighLevel) were already behind the harness (`/api/internal/connectors/*` with a per-turn bearer) and stay there.A key whose CLI takes no base URL from the environment (xAI, Mistral, Groq, Cerebras, MiniMax, Kimi, Cursor, Factory,diff --git a/server/bot-box/broker.test.ts b/server/bot-box/broker.test.tsindex 4d71854708..2b631876f9 100644--- a/server/bot-box/broker.test.ts+++ b/server/bot-box/broker.test.ts@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";-import { BROKER_PROCESS_TTL_MS, BROKER_THREAD_TTL_MS, BROKER_TOKEN_PREFIX, brokerUrl, openCredentialBroker, type CredentialBroker } from "./broker.ts";+import { BROKER_PROCESS_TTL_MS, BROKER_THREAD_TTL_MS, BROKER_TOKEN_PREFIX, brokerUrl, openCredentialBroker, upstreamUrl, type CredentialBroker } from "./broker.ts";const REAL_KEY = "sk-ant-real-key-0123456789abcdef";@@ -120,4 +120,29 @@ linuxBox("the credential broker", () => {await start();expect(() => broker.mintForProcess({ grants: { "../x": { upstream: "http://127.0.0.1:9", headers: {} } } })).toThrow(/grant name/);});++ it("forwards a request for the grant itself to the upstream exactly as given, and anything below it below the upstream", async () => {+ const port = await start();+ const headers = { authorization: `Bearer ${REAL_KEY}` };+ const minted = broker.mintForThread({ threadId: "t1", grants: {+ "mcp-hq": { upstream: `http://127.0.0.1:${port}/mcp?team=acme`, headers },+ "mcp-slash": { upstream: `http://127.0.0.1:${port}/mcp/`, headers },+ } });+ for (const path of ["/mcp-hq", "/mcp-hq?session=1", "/mcp-hq/messages", "/mcp-slash", "/mcp-slash/"]) {+ expect((await call(broker.socketPath, "POST", `/b/${minted.token}${path}`, {}, "{}")).status, path).toBe(200);+ }+ // A Cloudflare Worker serves /mcp and answers /mcp/ with 404: the server's own address is never given a slash.+ expect(seen.map((request) => request.url)).toEqual(["/mcp?team=acme", "/mcp?team=acme&session=1", "/mcp/messages?team=acme", "/mcp/", "/mcp/"]);+ });+});++describe("the upstream address", () => {+ it("is the upstream as given for the grant itself, the client's path below it, and both queries", () => {+ expect(upstreamUrl("https://hq.example/mcp", "", "")?.href).toBe("https://hq.example/mcp");+ expect(upstreamUrl("https://hq.example/mcp/", "", "")?.href).toBe("https://hq.example/mcp/");+ expect(upstreamUrl("https://api.example/v1/", "/messages", "?beta=1")?.href).toBe("https://api.example/v1/messages?beta=1");+ expect(upstreamUrl("https://api.example", "/v1/messages", "")?.href).toBe("https://api.example/v1/messages");+ expect(upstreamUrl("https://hq.example/mcp?key=abc", "", "?session=2")?.href).toBe("https://hq.example/mcp?key=abc&session=2");+ expect(upstreamUrl("not a url", "", "")).toBeNull();+ });});diff --git a/server/bot-box/broker.ts b/server/bot-box/broker.tsindex ada068584a..3ecab778c9 100644--- a/server/bot-box/broker.ts+++ b/server/bot-box/broker.ts@@ -66,6 +66,17 @@ export function brokerUrl(port: number, token: string, grant: string): string {return `http://127.0.0.1:${port}/b/${token}/${grant}`;}+/** Where a request for `/b/<token>/<grant><path><query>` goes: the grant's upstream exactly as it was given when the+ * client asks for the grant itself (an MCP server at `/mcp` is not one at `/mcp/`: a Cloudflare Worker answers that 404),+ * the client's path below it otherwise, and the client's query beside the upstream's own. */+export function upstreamUrl(upstream: string, path: string, query: string): URL | null {+ let url: URL;+ try { url = new URL(upstream); } catch { return null; }+ if (path) url.pathname = `${url.pathname.replace(/\/+$/, "")}${path}`;+ if (query.length > 1) url.search = url.search ? `${url.search}&${query.slice(1)}` : query;+ return url;+}+const hashToken = (token: string) => createHash("sha256").update(token).digest();export function openCredentialBroker(options: CredentialBrokerOptions): Promise<CredentialBroker> {@@ -83,7 +94,7 @@ export function openCredentialBroker(options: CredentialBrokerOptions): Promise<for (const name of Object.keys(input.grants)) if (!GRANT.test(name)) throw new Error(`Not a grant name: ${name.slice(0, 40)}`);const token = `${BROKER_TOKEN_PREFIX}${randomBytes(24).toString("hex")}`;const expiresAt = now() + (input.ttlMs ?? (bound === "process" ? BROKER_PROCESS_TTL_MS : BROKER_THREAD_TTL_MS));- const grants = Object.fromEntries(Object.entries(input.grants).map(([name, grant]) => [name, { upstream: grant.upstream.replace(/\/+$/, ""), headers: { ...grant.headers } }]));+ const grants = Object.fromEntries(Object.entries(input.grants).map(([name, grant]) => [name, { upstream: grant.upstream, headers: { ...grant.headers } }]));tokens.set(hashToken(token).toString("hex"), { hash: hashToken(token), botId: input.botId ?? null, threadId: input.threadId ?? null, expiresAt, grants, bound });return { token, botId: input.botId ?? null, threadId: input.threadId ?? null, expiresAt, grants };};@@ -105,11 +116,11 @@ export function openCredentialBroker(options: CredentialBrokerOptions): Promise<const refuse = (status: number, error: string) => { res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify({ error })); req.resume(); };const match = /^\/b\/([^/]+)\/([^/?]+)(\/[^?]*)?(\?.*)?$/.exec(req.url ?? "");if (!match) return refuse(404, "not_found");- const [, token = "", grant = "", path = "/", query = ""] = match;+ const [, token = "", grant = "", path = "", query = ""] = match;const verdict = lookup(token, grant);if (!verdict.ok) return refuse(verdict.status, verdict.error);- let upstream: URL;- try { upstream = new URL(`${verdict.grant.upstream}${path}${query}`); } catch { return refuse(502, "bad_upstream"); }+ const upstream = upstreamUrl(verdict.grant.upstream, path, query);+ if (!upstream) return refuse(502, "bad_upstream");const headers: Record<string, string | string[]> = {};for (const [name, value] of Object.entries(req.headers)) if (value !== undefined && !HOP_BY_HOP.has(name) && !CREDENTIAL_HEADERS.has(name)) headers[name] = value;for (const [name, value] of Object.entries(verdict.grant.headers)) headers[name.toLowerCase()] = value;diff --git a/server/team-personal-mcp-broker.e2e.test.ts b/server/team-personal-mcp-broker.e2e.test.tsnew file mode 100644index 0000000000..8a79d5a954--- /dev/null+++ b/server/team-personal-mcp-broker.e2e.test.ts@@ -0,0 +1,113 @@+// A Team Cloud member's own remote MCP server, and the team's server behind a gateway, reached from a boxed turn: the+// turn's server list points the engine at the box's credential broker, which adds each server's headers (the member's+// own key, the gateway's service-token headers) and forwards to the server. A server that answers only at its own path,+// as a Cloudflare Worker serves /mcp and not /mcp/, must be reached at exactly that path. The box itself is Linux-only,+// so a loopback listener bridged to the broker's socket stands in for the box's bridge, and the MCP client is the one+// the server's own probes use.+import { mkdtempSync, rmSync } from "node:fs";+import { connect, createServer, type AddressInfo, type Server } from "node:net";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { BOX_BROKER_PORT, type BoxBroker } from "./bot-box/box.ts";+import { brokerRemoteMcp, forgetBrokeredMcp } from "./bot-box/broker-mcp.ts";+import { openCredentialBroker, type CredentialBroker } from "./bot-box/broker.ts";+import type { AppConfig } from "./config.ts";+import type { McpServerSpec, RemoteMcpSpec } from "./contracts.ts";+import { createTeamConnectionsHost } from "./host/team-connections-host.ts";+import { RemoteMcpClient } from "./mcp-http.ts";+import { McpOAuthManager } from "./mcp-oauth.ts";+import { probeMcpServer } from "./mcp-probe.ts";+import { personKey } from "./person-key.ts";+import { startFakeHttpMcp, type FakeHttpMcp } from "./testing/fake-http-mcp-server.ts";++const ADA = personKey({ id: "", email: "[email protected]" });+const ADA_KEY = "Bearer ada-own-wedding-key";+const CLIENT_ID = "5c1d0e9a.access", CLIENT_SECRET = "0f9e8d7c6b5a4938271605";++// 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")("a member's own MCP server and the team's gateway server, from a boxed turn", () => {+ let dir = "", own: FakeHttpMcp, gateway: FakeHttpMcp, credentials: CredentialBroker, bridge: Server, broker: BoxBroker;+ let mounted: Record<string, McpServerSpec> = {};++ beforeAll(async () => {+ dir = mkdtempSync(join(tmpdir(), "omb-team-box-mcp-"));+ own = await startFakeHttpMcp({ exactPath: true, tools: [{ name: "plan_seating" }], requireHeader: { name: "Authorization", value: ADA_KEY } });+ gateway = await startFakeHttpMcp({+ exactPath: true, tools: [{ name: "lookup_order" }],+ requireHeaders: { "CF-Access-Client-Id": CLIENT_ID, "CF-Access-Client-Secret": CLIENT_SECRET, Authorization: "Bearer team-orders" },+ });+ const cfg = { mcpServers: {+ "mi-boda-hq": { type: "http", url: own.url, headers: { Authorization: "Bearer the-admin's-own" }, enabled: true },+ orders: { type: "http", url: gateway.url, headers: { Authorization: "Bearer team-orders", "CF-Access-Client-Id": CLIENT_ID, "CF-Access-Client-Secret": CLIENT_SECRET }, enabled: true },+ } } as unknown as AppConfig;+ const host = createTeamConnectionsHost({+ team: { id: "team-acme-1", name: "Acme" }, dataDir: dir, cfg: () => cfg, adminOrigin: "https://cloud.example.test", harnessUrl: "http://127.0.0.1:1",+ audienceOf: (threadId) => (threadId === "ada-chat" ? `member:${ADA}` : "team"),+ requester: (threadId) => (threadId === "ada-chat" ? ADA : null),+ mint: (capability) => `tok-${capability.threadId}`,+ mcpOAuth: new McpOAuthManager({ file: join(dir, "mcp-oauth.json") }),+ botMcp: () => Object.fromEntries(Object.entries(cfg.mcpServers ?? {}).map(([name, raw]) => {+ const server = raw as { url: string; headers: Record<string, string> };+ return [name, { type: "http", url: server.url, headers: server.headers } as McpServerSpec];+ })),+ isSessionLive: () => true,+ brokerUrl: () => null,+ composio: { configured: () => false, mcpIntegration: async () => null, connectedServices: async () => ({}), connectedServiceSlugs: async () => [], authorizeService: async () => { throw new Error("unused"); }, removeService: async () => {} } as never,+ });+ // Ada connects the wedding server with her own key; the gateway server stays the team's.+ host.scopes.set("mcp", "mi-boda-hq", "person");+ host.people.putKey(ADA, "[email protected]", "mi-boda-hq", { url: own.url, header: "Authorization", value: ADA_KEY });++ credentials = await openCredentialBroker({ socketPath: join(dir, "broker.sock") });+ // Inside a box, 127.0.0.1:<broker port> is a bridge to the broker's socket; a TCP listener stands in for it here.+ bridge = createServer((socket) => {+ const upstream = connect(credentials.socketPath);+ socket.pipe(upstream).pipe(socket);+ upstream.on("error", () => socket.destroy());+ socket.on("error", () => upstream.destroy());+ });+ await new Promise<void>((resolve) => bridge.listen(0, "127.0.0.1", resolve));+ broker = { port: (bridge.address() as AddressInfo).port, mintForThread: credentials.mintForThread, touchThread: credentials.touchThread, revokeThread: credentials.revokeThread, lookup: credentials.lookup };+ expect(BOX_BROKER_PORT).toBe(18080);++ // Ada's own turn in her private chat, as the server mounts it for a boxed engine.+ const custom = await host.turnMcp({}, "ada-chat", "gen-1");+ expect((custom["mi-boda-hq"] as RemoteMcpSpec).headers).toEqual({ Authorization: ADA_KEY });+ mounted = brokerRemoteMcp(custom, { botId: "scout", threadId: "ada-chat" }, broker);+ });++ afterAll(async () => {+ forgetBrokeredMcp();+ await new Promise((resolve) => bridge?.close(resolve));+ await credentials?.close();+ await own?.close();+ await gateway?.close();+ if (dir) rmSync(dir, { recursive: true, force: true });+ });++ it("gives the engine only the broker's address for each, with no header", () => {+ for (const name of ["mi-boda-hq", "orders"]) {+ const server = mounted[name] as RemoteMcpSpec;+ expect(server.url, name).toMatch(new RegExp(`^http://127\\.0\\.0\\.1:${broker.port}/b/omb_t0_[a-f0-9]{48}/mcp-${name}$`));+ expect(server.headers, name).toEqual({});+ }+ const listed = JSON.stringify(mounted);+ for (const secret of [ADA_KEY, CLIENT_SECRET, "team-orders"]) expect(listed).not.toContain(secret);+ });++ it("reaches each server at exactly its own path, with its headers, and calls its tools", async () => {+ for (const [name, server, tool] of [["mi-boda-hq", own, "plan_seating"], ["orders", gateway, "lookup_order"]] as const) {+ expect(await probeMcpServer({ ...(mounted[name] as RemoteMcpSpec), enabled: true }), name).toMatchObject({ ok: true, tools: [{ name: tool }] });+ const client = new RemoteMcpClient(mounted[name] as RemoteMcpSpec);+ const signal = AbortSignal.timeout(10_000);+ await client.initialize("engine", signal);+ expect(await client.request("tools/call", { name: tool, arguments: {} }, signal), name).toEqual({ content: [{ type: "text", text: "remote execution recorded" }] });+ await client.close();+ expect(server.seenPaths.length, name).toBeGreaterThanOrEqual(3);+ expect(server.seenPaths.map((path) => path.split("?")[0]), name).toEqual(server.seenPaths.map(() => "/mcp"));+ }+ expect(own.seenHeaders.every((headers) => headers.authorization === ADA_KEY), "only Ada's own key, never the admin's").toBe(true);+ });+});diff --git a/server/testing/fake-http-mcp-server.ts b/server/testing/fake-http-mcp-server.tsindex b1b812ae8b..3093c0ca71 100644--- a/server/testing/fake-http-mcp-server.ts+++ b/server/testing/fake-http-mcp-server.ts@@ -55,6 +55,9 @@ export interface FakeHttpMcpOptions {resources?: FakeHttpMcpResource[];/** serverInfo.title in the initialize answer */serverTitle?: string;+ /** answer only at the server's own path (/mcp; /sse and /messages for SSE) and 404 anywhere else, as a Cloudflare+ * Worker's McpAgent serves /mcp and not /mcp/ */+ exactPath?: boolean;}export interface FakeHttpMcpResource {@@ -118,6 +121,8 @@ export interface FakeHttpMcpTool {export interface FakeHttpMcp {url: string;seenHeaders: IncomingMessage["headers"][];+ /** every request's path and query, as it arrived */+ seenPaths: string[];calls: unknown[];/** tools/list requests now waiting out `toolsDelayMs` */readonly delayedToolsLists: number;@@ -146,6 +151,7 @@ function readBody(req: IncomingMessage): Promise<string> {export async function startFakeHttpMcp(options: FakeHttpMcpOptions = {}): Promise<FakeHttpMcp> {const transport = options.transport ?? "http";const seenHeaders: FakeHttpMcp["seenHeaders"] = [];+ const seenPaths: string[] = [];const streams = new Set<ServerResponse>();const calls: unknown[] = [];let delayedToolsLists = 0;@@ -212,6 +218,11 @@ export async function startFakeHttpMcp(options: FakeHttpMcpOptions = {}): Promisconst handle: RequestListener = (req, res) => {void (async () => {seenHeaders.push({ ...req.headers });+ seenPaths.push(req.url ?? "");+ if (options.exactPath && !(transport === "sse" ? ["/sse", "/messages"] : ["/mcp"]).includes((req.url ?? "").split("?")[0]!)) {+ res.writeHead(404, { "content-type": "text/plain" }).end("Not found");+ return;+ }if (options.requireHeaders && Object.entries(options.requireHeaders).some(([name, value]) => req.headers[name.toLowerCase()] !== value)) {res.writeHead(403, { "content-type": "text/plain" }).end("Forbidden");return;@@ -319,6 +330,7 @@ export async function startFakeHttpMcp(options: FakeHttpMcpOptions = {}): Promisreturn {url: `${options.tls ? "https" : "http"}://${host === "::1" ? "[::1]" : host}:${port}/${transport === "sse" ? "sse" : "mcp"}`,seenHeaders,+ seenPaths,calls,get delayedToolsLists() { return delayedToolsLists; },get toolsLists() { return toolsLists; },