Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Check tool selection, never wait, and match MCP server names exactly (#5494)
Milind Soni79d85d626f6d
diff --git a/server/bot-box/broker-mcp-refusal.test.ts b/server/bot-box/broker-mcp-refusal.test.tsindex 19292d09b2..360764a8b5 100644--- a/server/bot-box/broker-mcp-refusal.test.ts+++ b/server/bot-box/broker-mcp-refusal.test.ts@@ -60,7 +60,8 @@ describe.skipIf(process.platform === "win32")("an MCP server that refuses a boxeconst result = await callTool(mounted);expect(result.isError).toBe(true);expect(result.content[0]!.text).toContain('The MCP server "mail" needs a sign-in');- expect(result.content[0]!.text).toContain("Call mcp_server with action sign_in and name mail");+ expect(result.content[0]!.text, "no connected app given: the words stay as they were").toBe('The MCP server "mail" needs a sign-in before its tools work, and nobody has signed in (HTTP 401), so nothing ran. '+ + "Don't retry. Call mcp_server with action sign_in and name mail, then end your turn; if you can't, tell the person to sign in to mail in Apps, MCP servers.");expect(server!.calls).toEqual([]);const grant = brokeredServer(path, "mail", target);@@ -129,7 +130,8 @@ describe("the answer to a refused call", () => {it("points to the app already connected, with no card", () => {const text = textOf(refusedCallAnswer("mail", false, CALL, { slug: "googlecalendar", label: "Google Calendar", connected: true }));- expect(text).toBe(`${REFUSED} Google Calendar is already connected as a connected app here, so use the connected app's Google Calendar tools instead of this MCP server. Don't show a connect card for it.`);+ expect(text).toBe(`${REFUSED} Google Calendar is already connected as a connected app here, so use the connected app's Google Calendar tools instead of this MCP server. `+ + `Don't show a connect card for it. If you don't have those tools, call ${SIGN_IN.slice("Call ".length)}`);expect(text).not.toContain("COMPOSIO_MANAGE_CONNECTIONS");});diff --git a/server/bot-box/broker-mcp-refusal.ts b/server/bot-box/broker-mcp-refusal.tsindex 0c44169da1..2af77ee54f 100644--- a/server/bot-box/broker-mcp-refusal.ts+++ b/server/bot-box/broker-mcp-refusal.ts@@ -11,8 +11,8 @@ export const MAX_REFUSABLE_CALL_BYTES = 1_048_576;* use that app instead. */function signInWantedText(server: string, app?: McpServerApp): string {const refused = `The MCP server "${server}" needs a sign-in before its tools work, and nobody has signed in (HTTP 401), so nothing ran. Don't retry.`;- if (app?.connected) return `${refused} ${app.label} is already connected as a connected app here, so use the connected app's ${app.label} tools instead of this MCP server. Don't show a connect card for it.`;const signIn = `mcp_server with action sign_in and name ${server}, then end your turn; if you can't, tell the person to sign in to ${server} in Apps, MCP servers.`;+ if (app?.connected) return `${refused} ${app.label} is already connected as a connected app here, so use the connected app's ${app.label} tools instead of this MCP server. Don't show a connect card for it. If you don't have those tools, call ${signIn}`;if (!app) return `${refused} Call ${signIn}`;return `${refused} ${app.label} can be connected in one step with its connect card. Call COMPOSIO_MANAGE_CONNECTIONS with toolkits ${JSON.stringify([app.slug])} to show the card in this chat, then end your turn. Once it is connected, use the connected app's ${app.label} tools instead of this MCP server. If the card can't be shown, call ${signIn}`;}diff --git a/server/bot-box/broker-mcp.test.ts b/server/bot-box/broker-mcp.test.tsindex 72ba8d90d4..2a7810b9b5 100644--- a/server/bot-box/broker-mcp.test.ts+++ b/server/bot-box/broker-mcp.test.ts@@ -55,6 +55,33 @@ describe("remote MCP servers through the broker", () => {expect(credentials.stats().tokens).toBe(2);});+ withBroker("keeps a token while a server's app stays as it was, and gives a new one once when it becomes connected, never for a server sent credentials", async () => {+ const b = await broker();+ let connected = false;+ const appFor = () => ({ slug: "gmail", label: "Gmail", connected });+ const servers = { gmail: { type: "http" as const, url: "https://gmailmcp.googleapis.com/mcp/v1", headers: {} } };+ const url = (out: Record<string, unknown>, name: string) => (out[name] as { url: string }).url;+ const token = (address: string) => /\/b\/(omb_t0_[a-f0-9]{48})\//.exec(address)![1]!;+ const turn = { botId: "b1", threadId: "t1" };+ const first = url(brokerRemoteMcp(servers, turn, b, appFor), "gmail");+ expect(credentials.lookup(token(first), "mcp-gmail")).toMatchObject({ ok: true, grant: { mcpApp: { slug: "gmail", label: "Gmail", connected: false } } });+ expect(url(brokerRemoteMcp(servers, turn, b, appFor), "gmail"), "the app as it was").toBe(first);+ connected = true;+ const second = url(brokerRemoteMcp(servers, turn, b, appFor), "gmail");+ expect(second, "the app became connected").not.toBe(first);+ expect(credentials.lookup(token(second), "mcp-gmail")).toMatchObject({ ok: true, grant: { mcpApp: { connected: true } } });+ expect(url(brokerRemoteMcp(servers, turn, b, appFor), "gmail"), "then kept again").toBe(second);++ const signedIn = { gmail: { ...servers.gmail, headers: { authorization: "Bearer gmail-token" } } };+ const other = { botId: "b1", threadId: "t2" };+ connected = false;+ const kept = url(brokerRemoteMcp(signedIn, other, b, appFor), "gmail");+ expect(credentials.lookup(token(kept), "mcp-gmail")).toMatchObject({ ok: true, grant: { mcpServer: "gmail" } });+ expect((credentials.lookup(token(kept), "mcp-gmail") as { grant: { mcpApp?: unknown } }).grant.mcpApp).toBeUndefined();+ connected = true;+ expect(url(brokerRemoteMcp(signedIn, other, b, appFor), "gmail"), "a server sent credentials never carries the app").toBe(kept);+ });+withBroker("gives a conversation a new token after a URL server failed as its engine started, so the engine reconnects", async () => {const b = await broker();const url = (servers: Record<string, unknown>) => (servers.notion as { url: string }).url;diff --git a/server/bot-box/broker-mcp.ts b/server/bot-box/broker-mcp.tsindex cee1bf30dd..f3a3c08e0e 100644--- a/server/bot-box/broker-mcp.ts+++ b/server/bot-box/broker-mcp.ts@@ -30,7 +30,7 @@ export function mcpGrantName(name: string): string {export function forgetBrokeredMcp(): void { remembered.clear(); }/** The turn's custom servers with every URL server's headers moved to the broker; unchanged when the broker is off.- * `appFor`: the connected app a server's sign-in refusal points to instead (broker-mcp-refusal.ts). */+ * `appFor`: the connected app a sign-in refusal points to instead, for a server sent no credentials (broker-mcp-refusal.ts). */export function brokerRemoteMcp(custom: Record<string, McpServerSpec>,turn: BrokerTurn,@@ -45,7 +45,7 @@ export function brokerRemoteMcp(const brokered: string[] = [];for (const [name, server] of Object.entries(custom)) {if (!("url" in server) || typeof server.url !== "string" || !NAME.test(name)) { out[name] = server; continue; }- const app = appFor?.(name, server.url);+ const app = Object.values(server.headers ?? {}).some((value) => value !== "") ? null : appFor?.(name, server.url);grants[mcpGrantName(name)] = { upstream: server.url, headers: { ...server.headers }, mcpServer: name, ...(app ? { mcpApp: app } : {}) };brokered.push(name);}diff --git a/server/host/team-connections-host.test.ts b/server/host/team-connections-host.test.tsindex a70e12de32..e9f89b7736 100644--- a/server/host/team-connections-host.test.ts+++ b/server/host/team-connections-host.test.ts@@ -291,20 +291,53 @@ describe("apps each person connects", () => {expect(setup({ team: false }).host.connectRefusal({ threadId: "ada-chat", generation: "g" }, ["gmail"])).toBeNull();});- it("swaps an MCP server that wants a sign-in for its connected app only where this bot may use that app", async () => {- const { host, composio } = setup({ team: false });- composio.connectedServices.mockImplementation(async () => ({ googlecalendar: { connected: true, pending: false, status: "ACTIVE", accounts: [] } }) as never);- const open = () => undefined;- const lookup = await host.mcpServerApps({ id: "scout", name: "Scout" }, open);- expect(lookup("gmail", "https://mail.example/mcp")).toEqual({ slug: "gmail", label: "Gmail", connected: false });- expect(lookup("calendar", "https://calendarmcp.googleapis.com/mcp/v1")).toEqual({ slug: "googlecalendar", label: "Google Calendar", connected: true });- expect(lookup("mail", "https://mail.example/mcp"), "an unknown server").toBeNull();- expect((await host.mcpServerApps({ id: "scout", name: "Scout" }, (slug) => (slug === "gmail" ? "Gmail is off here." : undefined)))("gmail", ""), "refused by policy").toBeNull();- expect((await host.mcpServerApps({ id: "scout", name: "Scout", connectorScopes: { apps: { slack: "write" } } }, open))("gmail", ""), "outside its scopes").toBeNull();- expect((await host.mcpServerApps({ id: "scout", name: "Scout", connectorTools: { slack: { tools: "*" } } }, open))("gmail", ""), "outside its grants").toBeNull();- const team = setup();- team.host.scopes.set("app", "gmail", "person");- expect((await team.host.mcpServerApps({ id: "scout", name: "Scout" }, open))("gmail", ""), "a person's app on a Team Cloud").toBeNull();+ describe("the connected app an MCP server that wants a sign-in can be swapped for", () => {+ const SERVERS = { gmail: { type: "http", url: "https://mail.example/mcp", headers: {} }, calendar: { type: "http", url: "https://calendarmcp.googleapis.com/mcp/v1", headers: {} } } as Record<string, McpServerSpec>;+ const SCOUT = { id: "scout", name: "Scout" };+ const open = { servers: SERVERS, bridged: true, blocked: () => undefined };+ /** Calendar connected on the team's installation, read the way a turn reads it: with its connected-apps bridge. */+ async function calendarConnected(options: { team?: boolean } = {}) {+ const made = setup(options);+ made.composio.connectedServices.mockImplementation(async () => ({ googlecalendar: { connected: true, pending: false, status: "ACTIVE", accounts: [] } }) as never);+ await made.host.appsIntegrations(SCOUT, "main-chat", "gen-1");+ return made.host;+ }++ it("offers the card for an app not connected yet, and points to one already connected", async () => {+ const lookup = (await calendarConnected({ team: false })).mcpServerApps(SCOUT, open)!;+ expect(lookup("gmail", "https://mail.example/mcp")).toEqual({ slug: "gmail", label: "Gmail", connected: false });+ expect(lookup("calendar", "https://calendarmcp.googleapis.com/mcp/v1")).toEqual({ slug: "googlecalendar", label: "Google Calendar", connected: true });+ expect(lookup("mail", "https://mail.example/mcp"), "an unknown server").toBeNull();+ });++ it("does so on a Team Cloud for a team app on the team's bridge, never for a person's app", async () => {+ const host = await calendarConnected();+ expect(host.mcpServerApps(SCOUT, open)!("gmail", "")).toEqual({ slug: "gmail", label: "Gmail", connected: false });+ host.scopes.set("app", "gmail", "person");+ expect(host.mcpServerApps(SCOUT, open)!("gmail", "")).toBeNull();+ expect(host.mcpServerApps(SCOUT, open)!("calendar", "https://calendarmcp.googleapis.com/mcp/v1")?.connected).toBe(true);+ });++ it("gives no app without the turn's bridge, or where the bot's tool selection, scopes, grants or policy leave it out", async () => {+ const host = await calendarConnected({ team: false });+ expect(host.mcpServerApps(SCOUT, { ...open, bridged: false }), "no connected-apps bridge").toBeUndefined();+ expect(host.mcpServerApps({ ...SCOUT, composio: false }, open), "connected apps off for this bot").toBeUndefined();+ expect(host.mcpServerApps({ ...SCOUT, toolScope: { deny: ["mcp:composio:*"] } }, open), "its tool selection drops connected apps").toBeUndefined();+ expect(host.mcpServerApps({ ...SCOUT, toolScope: { allow: ["native:*"] } }, open), "its tool selection names no connected-apps tool").toBeUndefined();+ expect(host.mcpServerApps(SCOUT, { ...open, servers: { mail: { type: "http", url: "https://mail.example/mcp", headers: {} } } }), "no server stands for an app").toBeUndefined();+ const noCard = host.mcpServerApps({ ...SCOUT, toolScope: { deny: ["mcp:composio:COMPOSIO_MANAGE_CONNECTIONS"] } }, open)!;+ expect(noCard("gmail", ""), "no card it may show").toBeNull();+ expect(noCard("calendar", "https://calendarmcp.googleapis.com/mcp/v1")?.connected, "an app it already has").toBe(true);+ expect(host.mcpServerApps(SCOUT, { ...open, blocked: (slug) => (slug === "gmail" ? "Gmail is off here." : undefined) })!("gmail", ""), "refused by policy").toBeNull();+ expect(host.mcpServerApps({ ...SCOUT, connectorScopes: { apps: { slack: "write" } } }, open)!("gmail", ""), "outside its scopes").toBeNull();+ expect(host.mcpServerApps({ ...SCOUT, connectorTools: { slack: { tools: "*" } } }, open)!("gmail", ""), "outside its grants").toBeNull();+ });++ it("never waits for the apps connected: before the first read it knows none", () => {+ const { host, composio } = setup({ team: false });+ expect(host.mcpServerApps(SCOUT, open)!("calendar", "https://calendarmcp.googleapis.com/mcp/v1")).toEqual({ slug: "googlecalendar", label: "Google Calendar", connected: false });+ expect(composio.connectedServices).not.toHaveBeenCalled();+ });});});diff --git a/server/host/team-connections-host.ts b/server/host/team-connections-host.tsindex 1cbbdf8043..e9c79cd793 100644--- a/server/host/team-connections-host.ts+++ b/server/host/team-connections-host.ts@@ -25,8 +25,9 @@ import { projectApiKey } from "../composio-session.ts";import { appLabel, asPerson, ConnectionScopes, isProjectAccess, PeopleConnections, personAppOf, SCOPES_FILE, type PersonAppsAccess } from "../team-connections.ts";import { APP_TOOL_NAMES_ENV, APP_TOOLS_ENV, appToolsFor } from "../connector-app-tools.ts";import type { ConnectorScopes } from "../../shared/connector-scopes.ts";+import { allowsTool, canUseMcpServer, type ToolScope } from "../../shared/tool-scope.ts";-type Bot = { id: string; name: string; connectorTools?: Parameters<typeof Composio.mcpIntegration>[1]["connectorTools"]; connectorScopes?: ConnectorScopes };+type Bot = { id: string; name: string; connectorTools?: Parameters<typeof Composio.mcpIntegration>[1]["connectorTools"]; connectorScopes?: ConnectorScopes; composio?: boolean; toolScope?: ToolScope };type Integration = { command: string; args: string[]; env: Record<string, string> };type McpBot = { id: string; name: string; mcpServers?: string[] };@@ -101,8 +102,9 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {* is used at once, and read again in the background once it is a minute old. Only an installation's first answer is* waited for, at most a few seconds, and a failed first read is tried again soon; `primeApps` reads the team's at start. */const connectedApps = new Map<string, { at: number; apps: string[] | null; reading: Promise<void> | null }>();+ const appsKey = (as?: PersonAppsAccess) => isProjectAccess(as) ? `project\u0000${as.composio.userId}` : as ? createHash("sha256").update(as.url).update("\u0000").update(as.token).digest("hex") : "";const appsConnected = async (as?: PersonAppsAccess): Promise<string[]> => {- const key = isProjectAccess(as) ? `project\u0000${as.composio.userId}` : as ? createHash("sha256").update(as.url).update("\u0000").update(as.token).digest("hex") : "";+ const key = appsKey(as);const entry = connectedApps.get(key) ?? { at: -Infinity, apps: null, reading: null };connectedApps.set(key, entry);if (!entry.reading && Date.now() - entry.at >= (entry.apps ? APPS_FRESH_MS : APPS_RETRY_MS)) {@@ -274,16 +276,21 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {return out;},- /** For a turn with the team's connected-apps bridge: the connected app an MCP server that wants a sign-in can be swapped- * for, or null where this bot could not use that app: a `person` app, one its scopes or grants leave out, or one- * `blocked` refuses. */- async mcpServerApps(bot: Bot, blocked: (slug: string) => string | undefined): Promise<(name: string, url: string) => McpServerApp | null> {- const connected = await appsConnected(), apps = personApps();+ /** For a turn's URL MCP servers: the connected app a server that wants a sign-in can be swapped for, or null where this bot+ * could not use that app: no connected-apps bridge in the turn or none its tool selection allows, a `person` app, one+ * its scopes or grants leave out, or one `blocked` refuses; a card only where it may call COMPOSIO_MANAGE_CONNECTIONS.+ * Undefined when no server stands for an app. Never waits: the apps connected are the ones read last. */+ mcpServerApps(bot: Bot, input: { servers: Record<string, McpServerSpec>; bridged: boolean; blocked(slug: string): string | undefined }): ((name: string, url: string) => McpServerApp | null) | undefined {+ if (!input.bridged || bot.composio === false || !canUseMcpServer(bot.toolScope, "composio")) return undefined;+ if (!Object.entries(input.servers).some(([name, spec]) => "url" in spec && typeof spec.url === "string" && knownMcpServerApp(name, spec.url))) return undefined;+ const connected = connectedApps.get(appsKey())?.apps ?? [], apps = personApps();+ const card = allowsTool(bot.toolScope, { kind: "mcp", server: "composio", name: "COMPOSIO_MANAGE_CONNECTIONS" });return (name, url) => {const known = knownMcpServerApp(name, url);- if (!known || apps.includes(known.slug) || blocked(known.slug)) return null;+ if (!known || apps.includes(known.slug) || input.blocked(known.slug)) return null;if ((bot.connectorScopes && !bot.connectorScopes.apps[known.slug]) || (bot.connectorTools && !bot.connectorTools[known.slug])) return null;- return { ...known, connected: connected.includes(known.slug) };+ const isConnected = connected.includes(known.slug);+ return isConnected || card ? { ...known, connected: isConnected } : null;};},diff --git a/server/index.ts b/server/index.tsindex bce96a5db6..d6e7392972 100644--- a/server/index.ts+++ b/server/index.ts@@ -7908,7 +7908,7 @@ async function beginTurn(// User MCP servers' tools are never pre-allowed: every call rides the normal permission flow.if (instance.adapter.capabilities.customMcp === true && !proactive.fence.confines(threadId) && !botApiThread(threadId)) {const custom = await mcpServersHost.prepare(bot).then(() => teamConnections.turnMcp(bot, threadId, dispatchClaimId));- attachCustomMcp(integrations, { ...custom, ...lentMcp.mounts(bot, { botId: bot.id, threadId, generation: dispatchClaimId }) }, cfg, { botId: bot.id, threadId }, integrations.composio ? await teamConnections.mcpServerApps(bot, (slug) => managedPolicy.appsConnectRefusal([slug])) : undefined);+ attachCustomMcp(integrations, { ...custom, ...lentMcp.mounts(bot, { botId: bot.id, threadId, generation: dispatchClaimId }) }, cfg, { botId: bot.id, threadId }, teamConnections.mcpServerApps(bot, { servers: custom, bridged: Boolean(integrations.composio), blocked: (slug) => managedPolicy.appsConnectRefusal([slug]) }));if (Object.keys(custom).length) Object.assign(integrations, chatAppsMcp.turnMounts(custom, bot.toolScope));}if (!directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId)) throw new DirectTurnSetupCancelled("turn stopped while its tools were prepared"); const worksInWorkspace = supportsWorkspaceFiles(instance.driverKind);@@ -9825,7 +9825,7 @@ async function runClaimedGroupMemberTurn(return true;}if (instance.adapter.capabilities.customMcp === true) {- const custom = { ...await mcpServersHost.prepare(bot).then(() => teamConnections.turnMcp(bot, threadId, internalGeneration)), ...lentMcp.mounts(bot, { botId: bot.id, threadId, generation: internalGeneration }) }; attachCustomMcp(integrations, custom, cfg, { botId: bot.id, threadId }, integrations.composio ? await teamConnections.mcpServerApps(bot, (slug) => managedPolicy.appsConnectRefusal([slug])) : undefined); Object.assign(integrations, chatAppsMcp.turnMounts(custom, bot.toolScope));+ const custom = { ...await mcpServersHost.prepare(bot).then(() => teamConnections.turnMcp(bot, threadId, internalGeneration)), ...lentMcp.mounts(bot, { botId: bot.id, threadId, generation: internalGeneration }) }; attachCustomMcp(integrations, custom, cfg, { botId: bot.id, threadId }, teamConnections.mcpServerApps(bot, { servers: custom, bridged: Boolean(integrations.composio), blocked: (slug) => managedPolicy.appsConnectRefusal([slug]) })); Object.assign(integrations, chatAppsMcp.turnMounts(custom, bot.toolScope));}// An interrupt during connected-app setup must still stop the queued room operation before it starts a process.if (isCancelled?.()) return false;diff --git a/server/mcp-server-app.test.ts b/server/mcp-server-app.test.tsindex a65cc36655..3b4c28cce2 100644--- a/server/mcp-server-app.test.ts+++ b/server/mcp-server-app.test.ts@@ -7,9 +7,11 @@ describe("the connected app an MCP server stands for", () => {it.each([["any name", "https://gmailmcp.googleapis.com/mcp/v1", "gmail"],["any name", "https://calendarmcp.googleapis.com/mcp/v1", "googlecalendar"],+ ["Gmail-work", "https://gmailmcp.googleapis.com/mcp/v1", "gmail"],["gmail", "https://mcp.example/gmail", "gmail"],- ["Gmail-work", "https://mcp.example/", "gmail"],+ ["Gmail_MCP", "https://mcp.example/", "gmail"],["google-calendar", "https://mcp.example/", "googlecalendar"],+ ["googlecalendar-mcp", "https://mcp.example/", "googlecalendar"],["gcal", "not a url", "googlecalendar"],])("knows %s at %s as %s", (name, url, slug) => {expect(knownMcpServerApp(name, url)?.slug).toBe(slug);@@ -19,6 +21,11 @@ describe("the connected app an MCP server stands for", () => {["mail", "https://mail.example/mcp"],["gmailer", "https://mail.example/mcp"],["my-gmail", "https://mail.example/mcp"],+ ["Gmail-work", "https://mail.example/mcp"],+ ["gmail-filters", "https://mail.example/mcp"],+ ["gmail_to_notion", "https://mail.example/mcp"],+ ["gmail2", "https://mail.example/mcp"],+ ["gcal2notion", "https://cal.example/mcp"],["calendar", "https://cal.example/mcp"],["drive", "https://drivemcp.googleapis.com/mcp/v1"],["anything", "https://gmailmcp.googleapis.com.example/mcp"],diff --git a/server/mcp-server-app.ts b/server/mcp-server-app.tsindex ed5b5f3ba7..76cfb336f5 100644--- a/server/mcp-server-app.ts+++ b/server/mcp-server-app.ts@@ -10,9 +10,10 @@ const GMAIL: KnownApp = { slug: "gmail", label: "Gmail" };const CALENDAR: KnownApp = { slug: "googlecalendar", label: "Google Calendar" };const BY_HOST: Record<string, KnownApp> = { "gmailmcp.googleapis.com": GMAIL, "calendarmcp.googleapis.com": CALENDAR };+/** At any other address, only a name that is the app's own: "gmail-filters" or "gcal2notion" is another tool. */const BY_NAME: ReadonlyArray<readonly [RegExp, KnownApp]> = [- [/^gmail(?![a-z])/i, GMAIL],- [/^(?:google[-_ ]?calendar|gcal(?:endar)?)(?![a-z])/i, CALENDAR],+ [/^gmail(?:[-_]mcp)?$/i, GMAIL],+ [/^(?:google[-_]?calendar|gcal(?:endar)?)(?:[-_]mcp)?$/i, CALENDAR],];export function knownMcpServerApp(name: string, url: string): KnownApp | null {