Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
MCP sign-in refusal offers the connected app's card for Gmail and Google Calendar (#5490)
Milind Soni872592ef0aff
diff --git a/docs/bot-box.md b/docs/bot-box.mdindex a381d667f5..fab626b4dd 100644--- a/docs/bot-box.md+++ b/docs/bot-box.md@@ -101,7 +101,10 @@ ends. A server that answers directly but not through the broker fails the test wserver", never "Connected", and says the fault is ours. A tool call a URL server refuses with HTTP 401 is answered by thebroker as a failed tool result that names the server and what to do (`server/bot-box/broker-mcp-refusal.ts`): passed through,the 401 starts the engine's own sign-in, which cannot work because the broker drops any `Authorization` the engine sends, and-Claude Code then says only "Error dialing <address>", since the address holds a token. Connected apps (Composio) were already behind the harness+Claude Code then says only "Error dialing <address>", since the address holds a token. When nobody signed in and the server+is one a connected app covers (Gmail or Google Calendar, known by its address or name, `server/mcp-server-app.ts`), and the+turn can use that app, the answer offers the app's connect card first, or says to use the app when it is already connected.+Connected apps (Composio) 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, Greenference, ModelGo, Cerebras, MiniMax, Kimi, Cursor, Factory,diff --git a/server/bot-box/broker-mcp-refusal.test.ts b/server/bot-box/broker-mcp-refusal.test.tsindex cca5cecdf4..19292d09b2 100644--- a/server/bot-box/broker-mcp-refusal.test.ts+++ b/server/bot-box/broker-mcp-refusal.test.ts@@ -15,6 +15,7 @@ import { brokerUrl, openCredentialBroker, type CredentialBroker } from "./brokerimport type { McpServerSpec, RemoteMcpSpec } from "../contracts.ts";import { McpHttpError, RemoteMcpClient } from "../mcp-http.ts";import { probeMcpServer } from "../mcp-probe.ts";+import type { McpServerApp } from "../mcp-server-app.ts";import { startFakeHttpMcp, type FakeHttpMcp, type FakeHttpMcpOptions } from "../testing/fake-http-mcp-server.ts";import { startFakeOAuth, type FakeOAuth } from "../testing/fake-oauth-server.ts";@@ -33,7 +34,7 @@ describe.skipIf(process.platform === "win32")("an MCP server that refuses a boxeif (dir) rmSync(dir, { recursive: true, force: true });});- async function boxed(options: FakeHttpMcpOptions, headers: Record<string, string> = {}) {+ async function boxed(options: FakeHttpMcpOptions, headers: Record<string, string> = {}, app?: McpServerApp) {oauth = await startFakeOAuth();server = await startFakeHttpMcp({ guard: "listed-tools", acceptBearer: () => false, wwwAuthenticate: oauth.challenge, tools: [READ], ...options });dir = mkdtempSync(join(tmpdir(), "omb-broker-refusal-"));@@ -41,7 +42,7 @@ describe.skipIf(process.platform === "win32")("an MCP server that refuses a boxebridge = await openBridge({ port: 0, socket: credentials.socketPath });const broker: BoxBroker = { port: (bridge.address() as AddressInfo).port, mintForThread: credentials.mintForThread, touchThread: credentials.touchThread, revokeThread: credentials.revokeThread, lookup: credentials.lookup };const custom: Record<string, McpServerSpec> = { mail: { type: "http", url: server.url, headers } };- const mounted = brokerRemoteMcp(custom, TURN, broker).mail as RemoteMcpSpec;+ const mounted = brokerRemoteMcp(custom, TURN, broker, app ? () => app : undefined).mail as RemoteMcpSpec;return { mounted, target: { type: "http" as const, url: server.url, headers, enabled: true }, path: { broker, socketPath: credentials.socketPath } };}const callTool = async (spec: RemoteMcpSpec) => {@@ -69,6 +70,14 @@ describe.skipIf(process.platform === "win32")("an MCP server that refuses a boxe} finally { await grant.done(); }});+ it("offers the connected app's card when the server stands for an app this turn can connect", async () => {+ const { mounted } = await boxed({}, {}, { slug: "gmail", label: "Gmail", connected: false });+ const text = (await callTool(mounted)).content[0]!.text;+ expect(text).toContain('Call COMPOSIO_MANAGE_CONNECTIONS with toolkits ["gmail"] to show the card in this chat, then end your turn.');+ expect(text).toContain("If the card can't be shown, call mcp_server with action sign_in and name mail");+ expect(server!.calls).toEqual([]);+ });+it("says the key or sign-in was refused when the broker sent one", async () => {const { mounted } = await boxed({}, { Authorization: "Bearer stale" });const result = await callTool(mounted);@@ -102,6 +111,34 @@ describe.skipIf(process.platform === "win32")("an MCP server that refuses a boxe});describe("the answer to a refused call", () => {+ const textOf = (answer: string | null) => (JSON.parse(answer!) as { result: { content: Array<{ text: string }> } }).result.content[0]!.text;+ const CALL = '{"jsonrpc":"2.0","id":1,"method":"tools/call"}';+ const SIGN_IN = "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.";+ const REFUSED = '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.';++ it("names only the server's own sign-in when no connected app stands in for it", () => {+ expect(textOf(refusedCallAnswer("mail", false, CALL))).toBe(`${REFUSED} ${SIGN_IN}`);+ });++ it("offers the app's connect card first, and the server's sign-in second", () => {+ expect(textOf(refusedCallAnswer("mail", false, CALL, { slug: "gmail", label: "Gmail", connected: false }))).toBe(`${REFUSED} `+ + "Gmail can be connected in one step with its connect card. Call COMPOSIO_MANAGE_CONNECTIONS with toolkits [\"gmail\"] to show the card in this chat, then end your turn. "+ + "Once it is connected, use the connected app's Gmail tools instead of this MCP server. "+ + `If the card can't be shown, call ${SIGN_IN.slice("Call ".length)}`);+ });++ 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).not.toContain("COMPOSIO_MANAGE_CONNECTIONS");+ });++ it("keeps a refused key or sign-in about the server alone", () => {+ const text = textOf(refusedCallAnswer("mail", true, CALL, { slug: "gmail", label: "Gmail", connected: false }));+ expect(text).toContain('The MCP server "mail" refused the sign-in or key it was sent');+ expect(text).not.toContain("COMPOSIO_MANAGE_CONNECTIONS");+ });+it("keeps the request's own id, string or number", () => {expect(JSON.parse(refusedCallAnswer("mail", false, '{"jsonrpc":"2.0","id":"a-1","method":"tools/call"}')!)).toMatchObject({ id: "a-1", result: { isError: true } });expect(JSON.parse(refusedCallAnswer("mail", false, '{"jsonrpc":"2.0","id":7,"method":"tools/call"}')!)).toMatchObject({ id: 7, result: { isError: true } });diff --git a/server/bot-box/broker-mcp-refusal.ts b/server/bot-box/broker-mcp-refusal.tsindex a7d9a96453..0c44169da1 100644--- a/server/bot-box/broker-mcp-refusal.ts+++ b/server/bot-box/broker-mcp-refusal.ts@@ -2,19 +2,30 @@// engine's own sign-in, which cannot succeed: the credential broker drops any Authorization the engine sends. Claude Code then// reports only "Error dialing <address>", because the address holds a broker token and it redacts the reason. So the call is// answered here, as a failed tool result the model reads, naming the server and what to do. Only text a model reads.+import type { McpServerApp } from "../mcp-server-app.ts";/** The request bodies kept to answer a refused call; a larger call passes the 401 through. */export const MAX_REFUSABLE_CALL_BYTES = 1_048_576;+/** What the bot hears when `server` wants a sign-in nobody gave it. `app`: the connected app it stands for, when this turn can+ * 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) 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}`;+}+/** The JSON-RPC answer for a refused `tools/call`, or null when `body` is anything else and the 401 should pass through.* `sentCredentials`: the broker added a key or sign-in to the refused request. */-export function refusedCallAnswer(server: string, sentCredentials: boolean, body: string): string | null {+export function refusedCallAnswer(server: string, sentCredentials: boolean, body: string, app?: McpServerApp): string | null {let frame: unknown;try { frame = JSON.parse(body); } catch { return null; }const { id, method } = (frame && typeof frame === "object" && !Array.isArray(frame) ? frame : {}) as { id?: unknown; method?: unknown };if (method !== "tools/call" || (typeof id !== "string" && typeof id !== "number")) return null;const text = sentCredentials? `The MCP server "${server}" refused the sign-in or key it was sent (HTTP 401), so nothing ran. Don't retry. If it signs in, call mcp_server with action sign_in and name ${server}, then end your turn; otherwise tell the person to update its key in Apps, MCP servers.`- : `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. Call 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.`;+ : signInWantedText(server, app);return JSON.stringify({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text }], isError: true } });}diff --git a/server/bot-box/broker-mcp.ts b/server/bot-box/broker-mcp.tsindex 4ec19d398d..cee1bf30dd 100644--- a/server/bot-box/broker-mcp.ts+++ b/server/bot-box/broker-mcp.ts@@ -8,6 +8,7 @@ import { createHash } from "node:crypto";import { listNames } from "../../shared/place-view.ts";import type { McpServerSpec } from "../contracts.ts";+import type { McpServerApp } from "../mcp-server-app.ts";import { serverLine } from "../server-lines.ts";import { botBox, type BoxBroker } from "./box.ts";import { brokerUrl } from "./broker.ts";@@ -28,17 +29,24 @@ export function mcpGrantName(name: string): string {/** Test seam: forget every remembered token. */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. */-export function brokerRemoteMcp(custom: Record<string, McpServerSpec>, turn: BrokerTurn, broker: BoxBroker | null = botBox.broker()): Record<string, McpServerSpec> {+/** 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). */+export function brokerRemoteMcp(+ custom: Record<string, McpServerSpec>,+ turn: BrokerTurn,+ broker: BoxBroker | null = botBox.broker(),+ appFor?: (name: string, url: string) => McpServerApp | null,+): Record<string, McpServerSpec> {if (!broker) return custom;// A turn starting on this conversation keeps its earlier grants alive (a long-lived engine process reuses them).broker.touchThread(turn.threadId);const out: Record<string, McpServerSpec> = {};- const grants: Record<string, { upstream: string; headers: Record<string, string>; mcpServer: string }> = {};+ const grants: Record<string, { upstream: string; headers: Record<string, string>; mcpServer: string; mcpApp?: McpServerApp }> = {};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; }- grants[mcpGrantName(name)] = { upstream: server.url, headers: { ...server.headers }, mcpServer: name };+ const app = appFor?.(name, server.url);+ grants[mcpGrantName(name)] = { upstream: server.url, headers: { ...server.headers }, mcpServer: name, ...(app ? { mcpApp: app } : {}) };brokered.push(name);}if (!brokered.length) return custom;diff --git a/server/bot-box/broker.ts b/server/bot-box/broker.tsindex d0d76fc49e..bc6a54a72d 100644--- a/server/bot-box/broker.ts+++ b/server/bot-box/broker.ts@@ -9,6 +9,7 @@ import { request as httpsRequest } from "node:https";import type { Socket } from "node:net";import { MAX_REFUSABLE_CALL_BYTES, refusedCallAnswer } from "./broker-mcp-refusal.ts";+import type { McpServerApp } from "../mcp-server-app.ts";export const BROKER_TOKEN_PREFIX = "omb_t0_";/** A token minted for a process lives this long at most; the process's exit ends it sooner. */@@ -25,6 +26,8 @@ export interface BrokerGrant {headers: Record<string, string>;/** On an MCP server's grant for a turn: its name, so a tool call it refuses with HTTP 401 is answered in words (broker-mcp-refusal.ts). */mcpServer?: string;+ /** With `mcpServer`: the connected app that refusal points the bot to instead. */+ mcpApp?: McpServerApp;}export interface BrokerToken {@@ -98,7 +101,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, headers: { ...grant.headers }, ...(grant.mcpServer ? { mcpServer: grant.mcpServer } : {}) }]));+ const grants = Object.fromEntries(Object.entries(input.grants).map(([name, grant]) => [name, { upstream: grant.upstream, headers: { ...grant.headers }, ...(grant.mcpServer ? { mcpServer: grant.mcpServer } : {}), ...(grant.mcpApp ? { mcpApp: { ...grant.mcpApp } } : {}) }]));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 };};@@ -142,7 +145,7 @@ export function openCredentialBroker(options: CredentialBrokerOptions): Promise<if (!mcpServer || answer.statusCode !== 401) return relay(answer);const decide = () => {const sentCredentials = Object.values(verdict.grant.headers).some((value) => value !== "");- const refusal = sentBytes <= MAX_REFUSABLE_CALL_BYTES ? refusedCallAnswer(mcpServer, sentCredentials, Buffer.concat(sent).toString("utf8")) : null;+ const refusal = sentBytes <= MAX_REFUSABLE_CALL_BYTES ? refusedCallAnswer(mcpServer, sentCredentials, Buffer.concat(sent).toString("utf8"), verdict.grant.mcpApp) : null;if (refusal === null) return relay(answer);answer.resume();res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" }).end(refusal);diff --git a/server/host/team-connections-host.test.ts b/server/host/team-connections-host.test.tsindex 2396159873..a70e12de32 100644--- a/server/host/team-connections-host.test.ts+++ b/server/host/team-connections-host.test.ts@@ -290,6 +290,22 @@ describe("apps each person connects", () => {expect(host.connectRefusal({ threadId: "ada-chat", generation: "g", connectorsFor: ADA }, ["slack"])).toMatch(/Slack is Acme's, connected once for everyone by its owner or an admin/);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();+ });});const BOT = { id: "bot-1", name: "Bot" };diff --git a/server/host/team-connections-host.ts b/server/host/team-connections-host.tsindex 76e899a795..1cbbdf8043 100644--- a/server/host/team-connections-host.ts+++ b/server/host/team-connections-host.ts@@ -18,6 +18,7 @@ import { advertisedGrants } from "../connector-advertisement.ts";import { appSandboxAllowed, serviceSlugFor } from "../connector-verdict.ts";import { type McpOAuthManager, type McpRefreshOutcome, type McpSignInPhase, withMcpSignIn, withoutPendingSignIn } from "../mcp-oauth.ts";import { isRemoteMcpServer, parseStoredMcpServer, type McpOAuthClientConfig } from "../mcp-registry.ts";+import { knownMcpServerApp, type McpServerApp } from "../mcp-server-app.ts";import { OWN_APPS_SERVER } from "../../shared/own-apps.ts";import { managedComposioBrokerOff } from "../composio-broker-access.ts";import { projectApiKey } from "../composio-session.ts";@@ -273,6 +274,19 @@ 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();+ return (name, url) => {+ const known = knownMcpServerApp(name, url);+ if (!known || apps.includes(known.slug) || 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) };+ };+ },+/** Whose installation a relayed frame goes to: the team's (none named), or the member's own after checking the turn* still acts for them. A refusal is the plain line the bot gets back. */relayActor(capability: { threadId: string; generation: string; connectorsFor?: string }): { access?: PersonAppsAccess; refusal?: string } {diff --git a/server/index.ts b/server/index.tsindex 9409364a59..a8e413e942 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 });+ 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);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 }); 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 }, integrations.composio ? await teamConnections.mcpServerApps(bot, (slug) => managedPolicy.appsConnectRefusal([slug])) : undefined); 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-result-budget.ts b/server/mcp-result-budget.tsindex 6bfaa0cf98..4ed59a4471 100644--- a/server/mcp-result-budget.ts+++ b/server/mcp-result-budget.ts@@ -2,6 +2,7 @@ import { brokerRemoteMcp, type BrokerTurn } from "./bot-box/broker-mcp.ts";import type { AppConfig } from "./config.ts";import type { McpServerSpec, SendTurnInput } from "./contracts.ts";import { parseStoredMcpServer } from "./mcp-registry.ts";+import type { McpServerApp } from "./mcp-server-app.ts";export function customMcpResultBudgets(cfg: AppConfig, names: readonly string[]): Record<string, number> {const out: Record<string, number> = {};@@ -21,9 +22,11 @@ export function attachCustomMcp(cfg: AppConfig,/** The turn, so a URL server's secret headers stay with the credential broker on a boxed Cloud home (server/bot-box). */turn?: BrokerTurn,+ /** The connected app a URL server's sign-in refusal points to instead, when this turn can use it. */+ appFor?: (name: string, url: string) => McpServerApp | null,): void {if (!Object.keys(custom).length) return;- integrations.custom = turn ? brokerRemoteMcp(custom, turn) : custom;+ integrations.custom = turn ? brokerRemoteMcp(custom, turn, undefined, appFor) : custom;const budgets = customMcpResultBudgets(cfg, Object.keys(custom));if (Object.keys(budgets).length) integrations.customResultBudgets = budgets;}diff --git a/server/mcp-server-app.test.ts b/server/mcp-server-app.test.tsnew file mode 100644index 0000000000..a65cc36655--- /dev/null+++ b/server/mcp-server-app.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from "vitest";++import { CURATED_CONNECTOR_SLUGS } from "../shared/connector-curated.ts";+import { knownMcpServerApp } from "./mcp-server-app.ts";++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", "https://mcp.example/gmail", "gmail"],+ ["Gmail-work", "https://mcp.example/", "gmail"],+ ["google-calendar", "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);+ });++ it.each([+ ["mail", "https://mail.example/mcp"],+ ["gmailer", "https://mail.example/mcp"],+ ["my-gmail", "https://mail.example/mcp"],+ ["calendar", "https://cal.example/mcp"],+ ["drive", "https://drivemcp.googleapis.com/mcp/v1"],+ ["anything", "https://gmailmcp.googleapis.com.example/mcp"],+ ])("leaves %s at %s alone", (name, url) => {+ expect(knownMcpServerApp(name, url)).toBeNull();+ });++ it("names only apps the connected-apps catalog has", () => {+ for (const [name, url] of [["gmail", ""], ["gcal", ""]] as const) {+ expect(CURATED_CONNECTOR_SLUGS).toContain(knownMcpServerApp(name, url)!.slug);+ }+ });+});diff --git a/server/mcp-server-app.ts b/server/mcp-server-app.tsnew file mode 100644index 0000000000..ed5b5f3ba7--- /dev/null+++ b/server/mcp-server-app.ts@@ -0,0 +1,21 @@+// The connected app an MCP server stands for, read from its address or its name alone, never from the network. Only apps+// listed here: an unknown server is never offered an app that may not be the same one.+import type { CuratedConnectorSlug } from "../shared/connector-curated.ts";++/** The connected app an MCP server that wants a sign-in can be swapped for in this turn. `connected`: it is connected already. */+export interface McpServerApp { slug: string; label: string; connected: boolean }++type KnownApp = { slug: CuratedConnectorSlug; label: string };+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 };+const BY_NAME: ReadonlyArray<readonly [RegExp, KnownApp]> = [+ [/^gmail(?![a-z])/i, GMAIL],+ [/^(?:google[-_ ]?calendar|gcal(?:endar)?)(?![a-z])/i, CALENDAR],+];++export function knownMcpServerApp(name: string, url: string): KnownApp | null {+ const host = URL.canParse(url) ? new URL(url).hostname.toLowerCase() : "";+ return (Object.hasOwn(BY_HOST, host) ? BY_HOST[host] : undefined) ?? BY_NAME.find(([pattern]) => pattern.test(name))?.[1] ?? null;+}