Skip to content

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

MCP: a URL server whose address is no MCP endpoint is left out of turns, said once, tried again on its own (#7000)

Milind Sonid0276e8a3df1
diff --git a/server/bot-box/broker-probe.ts b/server/bot-box/broker-probe.ts
index 3f4f8be325..8c2bb320b9 100644
--- a/server/bot-box/broker-probe.ts
+++ b/server/bot-box/broker-probe.ts
@@ -42,7 +42,8 @@ export function brokeredServer(path: BrokerPath, name: string, server: { url: st
fetch: brokered,
done: async () => {
path.broker.revokeThread(threadId);
- await agent?.close().catch(() => {});
+ // Not awaited: a connection the server holds open (an event stream) must not hold the caller up.
+ void agent?.close().catch(() => {});
},
};
}
diff --git a/server/host/mcp-servers-host.test.ts b/server/host/mcp-servers-host.test.ts
index 5aac60a20d..7b5c4eebea 100644
--- a/server/host/mcp-servers-host.test.ts
+++ b/server/host/mcp-servers-host.test.ts
@@ -11,6 +11,8 @@ import { providerToolAllowKey } from "../provider-tool-allow.ts";
import { VaultStore } from "../vault-store.ts";
import { createMcpKeys } from "../vault/mcp-keys.ts";
import { claimedNotice, createMcpServersHost, startCheckTimeout } from "./mcp-servers-host.ts";
+import type { BrokerPath } from "../bot-box/broker-probe.ts";
+import { notMcpError, type UrlAnswer } from "./mcp-url-checks.ts";
const dirs: string[] = [];
afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
@@ -25,7 +27,7 @@ function script(data: string, ...parts: string[]): string {
return path;
}
-function setup(options: { boxed?: boolean; data?: string; bots?: Array<{ id: string; name: string; mcpServers?: string[]; toolScope?: unknown }> } = {}) {
+function setup(options: { boxed?: boolean; data?: string; bots?: Array<{ id: string; name: string; mcpServers?: string[]; toolScope?: unknown }>; urls?: Record<string, UrlAnswer>; policy?: <T extends object>(servers: Record<string, T>) => Record<string, T>; botsPath?: () => BrokerPath | null } = {}) {
const data = options.data ?? mkdtempSync(join(tmpdir(), "omb-mcp-host-"));
if (!options.data) dirs.push(data);
const cfg: AppConfig = {
@@ -39,6 +41,8 @@ function setup(options: { boxed?: boolean; data?: string; bots?: Array<{ id: str
} as AppConfig;
const told: Array<{ text: string; about: string }> = [];
const started: string[] = [];
+ const probed: string[] = [];
+ const fetchers: Array<Record<string, string>> = [];
const host = createMcpServersHost({
dataDir: data,
cfg: () => cfg,
@@ -46,7 +50,8 @@ function setup(options: { boxed?: boolean; data?: string; bots?: Array<{ id: str
bots: () => options.bots ?? [IRIS, PAUL, ROSA, NOTES_ONLY, NO_SERVERS],
startsServers: (botId) => botId !== NO_SERVERS.id,
boxed: () => options.boxed ?? true,
- policy: (servers) => servers,
+ policy: options.policy ?? ((servers) => servers),
+ ...(options.botsPath ? { botsPath: options.botsPath } : {}),
tell: (text, about) => told.push({ text, about: about.id }),
// The image's python has no `mcp` module: these start only in Iris's own box, where it is installed.
start: async (name, server, botId) => {
@@ -54,8 +59,14 @@ function setup(options: { boxed?: boolean; data?: string; bots?: Array<{ id: str
if (name === "broken") return { ok: false, error: "The server stopped before the MCP handshake finished." };
return server.command === "/usr/bin/python3" && botId !== "iris" ? { ok: false, error: "No module named 'mcp'" } : { ok: true };
},
+ // No network: a URL server answers as `urls` says, else it lists no tools.
+ probeUrl: async (server, via) => {
+ probed.push(server.url);
+ if (via?.fetch) fetchers.push(server.headers);
+ return options.urls?.[server.url] ?? { ok: true };
+ },
});
- return { cfg, host, told, started, data };
+ return { cfg, host, told, started, data, probed, fetchers };
}
it("moves servers in one bot's folders to that bot once, says so once, and keeps them out of every other bot's turns", async () => {
@@ -153,6 +164,67 @@ it("leaves servers reached by URL alone", async () => {
expect(host.mounted(PAUL).linear).toEqual({ type: "http", url: "https://mcp.linear.app/mcp", headers: {} });
});
+it("leaves out a URL server whose address is no MCP endpoint, says so once, and keeps one that timed out or wants a key", async () => {
+ const PAGE = "https://docs.example.test/pages/1/", SLOW = "https://slow.example.test/mcp", KEYED = "https://keyed.example.test/mcp";
+ const { cfg, host, told, probed } = setup({ boxed: false, bots: [PAUL], urls: {
+ [PAGE]: { ok: false, status: 405 },
+ [SLOW]: { ok: false },
+ [KEYED]: { ok: false, status: 401 },
+ } });
+ cfg.mcpServers!.wiki = { type: "http", url: PAGE, headers: {}, enabled: true };
+ cfg.mcpServers!.slow = { type: "http", url: SLOW, headers: {}, enabled: true };
+ cfg.mcpServers!.keyed = { type: "http", url: KEYED, headers: {}, enabled: true };
+ expect(Object.keys(host.mounted(PAUL)), "before its check a URL server is mounted as before").toContain("wiki");
+ host.boot();
+ await host.health.settled();
+ expect(probed.sort()).toEqual([PAGE, KEYED, SLOW]);
+ expect(Object.keys(host.mounted(PAUL)).sort()).toEqual(["keyed", "notes", "slow"]);
+ expect(host.off(PAUL)).toContainEqual({ name: "wiki", error: notMcpError(405) });
+ expect(host.off(PAUL).map((off) => off.name)).not.toContain("slow");
+ expect(host.listing({ name: "wiki" }).offFor).toEqual(["paul"]);
+ expect(told.map((entry) => entry.text)).toContain("The Wiki tool doesn't start, so it's off for now. It comes back on its own once it starts.");
+
+ host.boot();
+ host.health.engineFailed(PAUL.id, ["wiki"]);
+ await host.health.settled();
+ expect(told.filter((entry) => entry.text.startsWith("The Wiki tool")), "said once").toHaveLength(1);
+
+ // The person fixes the address: it is mounted again at once and checked again.
+ cfg.mcpServers!.wiki = { type: "http", url: "https://mcp.example.test/wiki", headers: {}, enabled: true };
+ expect(Object.keys(host.mounted(PAUL))).toContain("wiki");
+ host.health.changed("wiki");
+ await host.health.settled();
+ expect(Object.keys(host.mounted(PAUL))).toContain("wiki");
+ expect(host.off(PAUL).map((off) => off.name)).not.toContain("wiki");
+});
+
+it("never contacts a URL server the organisation's policy blocks", async () => {
+ const { cfg, host, probed } = setup({ boxed: false, bots: [PAUL], policy: (servers) => Object.fromEntries(Object.entries(servers).filter(([name]) => name !== "blocked")) });
+ cfg.mcpServers!.blocked = { type: "http", url: "https://blocked.example.test/mcp", headers: {}, enabled: true };
+ host.boot();
+ host.health.changed("blocked");
+ host.health.engineFailed(PAUL.id, ["blocked"]);
+ await host.health.settled();
+ expect(probed).toEqual([]);
+});
+
+it("where turns are boxed, checks a URL server through the credential broker as turns reach it, with no headers of its own", async () => {
+ const minted: Array<{ threadId: string; grants: Record<string, { upstream: string; headers: Record<string, string> }> }> = [], revoked: string[] = [];
+ const path: BrokerPath = { socketPath: "/nonexistent/broker.sock", broker: {
+ port: 4567,
+ mintForThread: (grant: { threadId: string; grants: Record<string, { upstream: string; headers: Record<string, string> }> }) => { minted.push(grant); return { token: "tok" }; },
+ revokeThread: (threadId: string) => { revoked.push(threadId); },
+ } as unknown as BrokerPath["broker"] };
+ const { cfg, host, probed, fetchers } = setup({ boxed: true, bots: [PAUL], botsPath: () => path });
+ cfg.mcpServers!.wiki = { type: "http", url: "https://wiki.example.test/mcp", headers: { "x-api-key": "key-1" }, enabled: true };
+ host.health.changed("wiki");
+ await host.health.settled();
+ expect(probed).toEqual(["http://127.0.0.1:4567/b/tok/mcp-wiki"]);
+ expect(fetchers).toEqual([{}]);
+ expect(minted[0]!.grants["mcp-wiki"]).toMatchObject({ upstream: "https://wiki.example.test/mcp", headers: { "x-api-key": "key-1" } });
+ expect(revoked).toEqual([minted[0]!.threadId]);
+});
+
it("a package runner's first check waits for its download; any other program's keeps the short wait", () => {
for (const command of ["uvx", "npx", "/opt/homebrew/bin/uvx", "npx.cmd"]) expect(startCheckTimeout(command), command).toBe(120_000);
for (const command of ["node", "python3", "/usr/local/bin/my-server"]) expect(startCheckTimeout(command), command).toBeUndefined();
diff --git a/server/host/mcp-servers-host.ts b/server/host/mcp-servers-host.ts
index 7bb7267878..4aa9c24da6 100644
--- a/server/host/mcp-servers-host.ts
+++ b/server/host/mcp-servers-host.ts
@@ -12,9 +12,11 @@ import { MCP_RESTART_ENV } from "../mcp-app-catalog.ts";
import { grantMover, grantServersMark, storedGrantSpec, type GrantServer } from "../mcp-grant-spec.ts";
import { createMcpHealth, nameList, toolLabel, type McpHealthDeps } from "../mcp-health.ts";
import { probeMcpServer } from "../mcp-probe.ts";
-import { isRemoteMcpServer, parseStoredMcpServer, type StoredStdioMcpServer } from "../mcp-registry.ts";
+import { isRemoteMcpServer, parseStoredMcpServer, type StoredRemoteMcpServer, type StoredStdioMcpServer } from "../mcp-registry.ts";
import type { McpKeys } from "../vault/mcp-keys.ts";
import { canUseMcpServer } from "../../shared/tool-scope.ts";
+import { brokeredServer, type BrokerPath } from "../bot-box/broker-probe.ts";
+import { createMcpUrlChecks, initializeAnswer, withoutRedirects } from "./mcp-url-checks.ts";
type Bot = { id: string; name: string; mcpServers?: string[]; toolScope?: unknown; alwaysAllow?: string[] };
/** A server left out of a bot's turns, with why; `key`: its Vault key is off, as against it not starting. */
@@ -34,6 +36,12 @@ export interface McpServersHostDeps {
/** Whether bots' turns run boxed here, each seeing only its own folders. */
boxed(): boolean;
start?: McpHealthDeps["start"];
+ /** The servers each person connects with their own key: never checked on their own, which would send no one's key. */
+ personMcp?(): readonly string[];
+ /** How a URL server is checked: initializeAnswer. */
+ probeUrl?: typeof initializeAnswer;
+ /** The credential broker bots' turns reach URL servers through, or null where turns aren't boxed. */
+ botsPath?(): BrokerPath | null;
/** A server's `vault:<id>` keys, read when it is launched or called. */
keys?: McpKeys;
/** Drops a server's sign-in: its tokens and any sign-in still open. */
@@ -69,6 +77,16 @@ export function enabledCommandServers(cfg: AppConfig): Record<string, StdioMcpSp
return out;
}
+/** The enabled URL servers this computer's bots reach, by name. */
+export function enabledUrlServers(cfg: AppConfig): Record<string, StoredRemoteMcpServer> {
+ const out: Record<string, StoredRemoteMcpServer> = {};
+ for (const [name, raw] of Object.entries(cfg.mcpServers ?? {})) {
+ const parsed = parseStoredMcpServer(name, raw);
+ if (parsed.ok && isRemoteMcpServer(parsed.server) && parsed.server.enabled && !parsed.server.runsOn) out[name] = parsed.server;
+ }
+ return out;
+}
+
/** Whether this listed server's key is gone from the Vault: said beside it, so the person knows to give it a new one. */
function keyRemoved(keys: McpKeys, cfg: AppConfig, name: string): boolean {
const parsed = parseStoredMcpServer(name, cfg.mcpServers?.[name]);
@@ -119,10 +137,40 @@ export function createMcpServersHost(deps: McpServersHostDeps) {
start,
tell: deps.tell,
});
+ const urls = createMcpUrlChecks({
+ // The organisation's policy first: a server it blocks is never contacted.
+ servers: () => {
+ const personal = new Set(deps.personMcp?.() ?? []);
+ return deps.policy(Object.fromEntries(Object.entries(enabledUrlServers(deps.cfg())).filter(([name]) => !personal.has(name))));
+ },
+ users: (name) => deps.bots().filter((bot) => started(bot).includes(name)),
+ probe: async (name, server) => {
+ const stored = server as StoredRemoteMcpServer;
+ await deps.keys?.warm(name, stored);
+ const resolved = deps.keys ? deps.keys.resolve(name, stored) : { ok: true as const, server: stored };
+ // A server whose Vault key is off is off for that reason (keyed), not checked: no answer either way.
+ if (!resolved.ok || !("url" in resolved.server)) return { ok: false };
+ const probe = deps.probeUrl ?? initializeAnswer, path = deps.botsPath?.() ?? null;
+ if (!path) return probe(resolved.server);
+ const brokered = brokeredServer(path, name, resolved.server);
+ try {
+ return await probe({ ...resolved.server, url: brokered.url, headers: {} }, { fetch: withoutRedirects(brokered.fetch) });
+ } finally {
+ await brokered.done();
+ }
+ },
+ tell: deps.tell,
+ file: join(deps.dataDir, "mcp-url-checks.json"),
+ });
const restarts = new Map<string, number>();
- const health = { ...checks, changed(name: string): void { restarts.set(name, (restarts.get(name) ?? 0) + 1); checks.changed(name); } };
+ const health = {
+ ...checks,
+ changed(name: string): void { restarts.set(name, (restarts.get(name) ?? 0) + 1); checks.changed(name); urls.changed([name]); },
+ engineFailed(botId: string, names: readonly string[]): void { checks.engineFailed(botId, names); urls.engineFailed(names); },
+ async settled(): Promise<void> { await Promise.all([checks.settled(), urls.settled()]); },
+ };
- const mounted = (bot: Bot): Record<string, McpServerSpec> => withRestarts(health.usable(bot.id, keyed(bot).servers), restarts);
+ const mounted = (bot: Bot): Record<string, McpServerSpec> => withRestarts(urls.usable(health.usable(bot.id, keyed(bot).servers)), restarts);
/** `servers` as a saved "Always allow" names them (mcp-grant-spec.ts): no Vault key's value and no restart count. */
const grantSpecs = (servers: Record<string, McpServerSpec>): Record<string, McpServerSpec> => {
const stored = deps.cfg().mcpServers ?? {};
@@ -165,9 +213,9 @@ export function createMcpServersHost(deps: McpServersHostDeps) {
await health.prepare(bot.id, started(bot));
moveGrants(bot);
},
- off: (bot: Bot): McpServerOff[] => [...health.off(bot.id, started(bot)), ...keyed(bot).off.filter(({ name }) => canUseMcpServer(bot.toolScope, name))],
+ off: (bot: Bot): McpServerOff[] => [...health.off(bot.id, started(bot)), ...urls.off(started(bot)), ...keyed(bot).off.filter(({ name }) => canUseMcpServer(bot.toolScope, name))],
listing: <T extends { name: string }>(server: T): T & { offFor?: string[]; keyOff?: true } => {
- const offFor = health.offFor(server.name);
+ const offFor = [...health.offFor(server.name), ...urls.offFor(server.name)];
const keyGone = deps.keys ? keyRemoved(deps.keys, deps.cfg(), server.name) : false;
return { ...server, ...(offFor.length ? { offFor } : {}), ...(keyGone ? { keyOff: true as const } : {}) };
},
@@ -205,6 +253,7 @@ export function createMcpServersHost(deps: McpServersHostDeps) {
}
}
health.checkAll();
+ urls.checkAll();
},
};
}
diff --git a/server/host/mcp-url-checks.test.ts b/server/host/mcp-url-checks.test.ts
new file mode 100644
index 0000000000..ffaf5dcdf6
--- /dev/null
+++ b/server/host/mcp-url-checks.test.ts
@@ -0,0 +1,153 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { createServer, type IncomingHttpHeaders, type RequestListener, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, expect, it } from "vitest";
+
+import { createMcpUrlChecks, initializeAnswer, RECHECK_AFTER_ENGINE_MS, RECHECK_NOT_MCP_MS, type UrlAnswer } from "./mcp-url-checks.ts";
+
+const servers: Server[] = [];
+const dirs: string[] = [];
+afterEach(async () => {
+ await Promise.all(servers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))));
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+async function serve(handler: RequestListener): Promise<string> {
+ const server = createServer(handler);
+ servers.push(server);
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ return `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+}
+
+const WIKI = { wiki: { type: "http" as const, url: "https://wiki.example.test/", headers: {} } };
+const PAUL = { id: "paul", name: "Paul" };
+
+/** Checks over WIKI whose probe answers `answer()`, with a settable clock; `probes` counts the probes. */
+function checksOf(answer: () => UrlAnswer | Promise<UrlAnswer>, options: { file?: string; servers?: () => Record<string, { url: string }> } = {}) {
+ let clock = 1_000, probes = 0;
+ const told: string[] = [];
+ const checks = createMcpUrlChecks({
+ servers: options.servers ?? (() => WIKI), users: () => [PAUL], tell: (text) => told.push(text), now: () => clock,
+ probe: async () => { probes += 1; return answer(); }, ...(options.file ? { file: options.file } : {}),
+ });
+ return { checks, told, probes: () => probes, tick: (ms: number) => { clock += ms; } };
+}
+
+it("tries a server left out again after half an hour, keeping it out meanwhile, and lets it back once it answers as MCP", async () => {
+ let answer: UrlAnswer = { ok: false, status: 405 };
+ const { checks, probes, tick } = checksOf(() => answer);
+ checks.checkAll();
+ await checks.settled();
+ expect(Object.keys(checks.usable({ ...WIKI }))).toEqual([]);
+ tick(RECHECK_NOT_MCP_MS - 1);
+ expect(Object.keys(checks.usable({ ...WIKI }))).toEqual([]);
+ await checks.settled();
+ expect(probes(), "not due yet").toBe(1);
+ answer = { ok: true };
+ tick(1);
+ expect(Object.keys(checks.usable({ ...WIKI })), "out until the new check says otherwise").toEqual([]);
+ await checks.settled();
+ expect(probes()).toBe(2);
+ expect(Object.keys(checks.usable({ ...WIKI }))).toEqual(["wiki"]);
+});
+
+it("keeps a server left out when a recheck merely times out: only a real MCP answer brings it back", async () => {
+ let answer: UrlAnswer = { ok: false, status: 405 };
+ const { checks, probes, tick } = checksOf(() => answer);
+ checks.checkAll();
+ await checks.settled();
+ answer = { ok: false };
+ tick(RECHECK_NOT_MCP_MS);
+ checks.usable({ ...WIKI });
+ await checks.settled();
+ expect(probes()).toBe(2);
+ expect(Object.keys(checks.usable({ ...WIKI })), "a timeout proves nothing").toEqual([]);
+ tick(RECHECK_NOT_MCP_MS - 1);
+ checks.usable({ ...WIKI });
+ await checks.settled();
+ expect(probes(), "the failed recheck counts as a try").toBe(2);
+});
+
+it("keeps a server in that answered 404 (it may hide until signed in), a redirect, or a probe that throws", async () => {
+ for (const answer of [() => ({ ok: false, status: 404 }) as UrlAnswer, () => ({ ok: false, status: 307 }) as UrlAnswer, (): UrlAnswer => { throw new Error("boom"); }]) {
+ const { checks } = checksOf(answer);
+ checks.changed(["wiki"]);
+ await checks.settled();
+ expect(checks.off(["wiki"])).toEqual([]);
+ }
+});
+
+it("checks a server an engine reports failed at most once per address in ten minutes; a change is checked at once", async () => {
+ const { checks, probes, tick } = checksOf(() => ({ ok: true }));
+ for (let session = 0; session < 5; session += 1) {
+ checks.engineFailed(["wiki"]);
+ await checks.settled();
+ }
+ expect(probes()).toBe(1);
+ checks.changed(["wiki"]);
+ await checks.settled();
+ expect(probes()).toBe(2);
+ tick(RECHECK_AFTER_ENGINE_MS);
+ checks.engineFailed(["wiki"]);
+ await checks.settled();
+ expect(probes()).toBe(3);
+});
+
+it("tells the person once, across restarts, and again for a server whose address changed", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-url-checks-"));
+ dirs.push(dir);
+ const file = join(dir, "mcp-url-checks.json");
+ let current: Record<string, { url: string }> = WIKI;
+ for (let start = 0; start < 2; start += 1) {
+ const { checks, told } = checksOf(() => ({ ok: false, status: 405 }), { file, servers: () => current });
+ checks.checkAll();
+ await checks.settled();
+ expect(told, `start ${start}`).toHaveLength(start === 0 ? 1 : 0);
+ }
+ current = { wiki: { url: "https://wiki.example.test/other" } };
+ const { checks, told } = checksOf(() => ({ ok: false, status: 405 }), { file, servers: () => current });
+ checks.checkAll();
+ await checks.settled();
+ expect(told).toHaveLength(1);
+});
+
+it("reads a web page's answer to MCP's first request as its HTTP status, and a refused connection as no status", async () => {
+ // A web page that serves GET only.
+ const page = await serve((request, response) => {
+ response.writeHead(request.method === "GET" ? 200 : 405, { "content-type": "text/html" });
+ response.end("<html></html>");
+ });
+ expect(await initializeAnswer({ type: "http", url: `${page}/pages/1/`, headers: {} }, { timeoutMs: 10_000 })).toEqual({ ok: false, status: 405 });
+ expect(await initializeAnswer({ type: "http", url: "http://127.0.0.1:9/mcp", headers: {} }, { timeoutMs: 10_000 })).toEqual({ ok: false });
+});
+
+it("counts a server of MCP's older HTTP+SSE transport, saved as http, as MCP: it refuses the POST but streams to a GET", async () => {
+ const legacy = await serve((request, response) => {
+ if (request.method !== "GET") return void response.writeHead(405).end();
+ response.writeHead(200, { "content-type": "text/event-stream" });
+ response.write("event: endpoint\ndata: /messages?session=1\n\n");
+ });
+ expect(await initializeAnswer({ type: "http", url: `${legacy}/sse`, headers: {} }, { timeoutMs: 10_000 })).toEqual({ ok: true });
+});
+
+it("reads a legacy SSE server whatever case its content type is in, and a POST 405 whose GET tells nothing as no answer", async () => {
+ const upper = await serve((request, response) => {
+ if (request.method !== "GET") return void response.writeHead(405).end();
+ response.writeHead(200, { "content-type": "Text/Event-Stream" });
+ response.write("event: endpoint\ndata: /messages?session=1\n\n");
+ });
+ expect(await initializeAnswer({ type: "http", url: `${upper}/sse`, headers: {} }, { timeoutMs: 10_000 })).toEqual({ ok: true });
+ const refused = await serve((request, response) => { response.writeHead(request.method === "GET" ? 401 : 405).end(); });
+ expect(await initializeAnswer({ type: "http", url: `${refused}/mcp`, headers: {} }, { timeoutMs: 10_000 }), "neither MCP nor a page").toEqual({ ok: false });
+});
+
+it("never follows a redirect, so a server's keys never reach another address", async () => {
+ const seen: IncomingHttpHeaders[] = [];
+ const elsewhere = await serve((request, response) => { seen.push(request.headers); response.writeHead(405).end(); });
+ const moved = await serve((_request, response) => { response.writeHead(307, { location: `${elsewhere}/mcp` }).end(); });
+ const answer = await initializeAnswer({ type: "http", url: `${moved}/mcp`, headers: { "x-api-key": "key-value-1", authorization: "Bearer token-1" } }, { timeoutMs: 10_000 });
+ expect(seen).toEqual([]);
+ expect(answer).toEqual({ ok: false, status: 307 });
+});
diff --git a/server/host/mcp-url-checks.ts b/server/host/mcp-url-checks.ts
new file mode 100644
index 0000000000..7d48300862
--- /dev/null
+++ b/server/host/mcp-url-checks.ts
@@ -0,0 +1,198 @@
+// A URL MCP server whose address answers MCP's first request with HTTP 405 is no MCP endpoint (a web page that takes no
+// POST). Every engine fails it at every session start, and a server that failed there makes the conversation's engine
+// start again from cold on its next turn (bot-box/broker-mcp.ts, drivers/codex.ts), so one such entry cost every turn of
+// every bot that has it. It is left out of turns as a command server that does not start is (mcp-health.ts), the person
+// hears it once (across restarts), and it is tried again on its own. Only that definite answer turns a server off: a
+// timeout, a refused key, a redirect or an unreachable host may pass on the next try, and such a server stays in; one that
+// refuses the POST but answers a GET with an event stream speaks MCP's older HTTP+SSE transport and stays in too. Where
+// bots' turns are boxed the check goes through the credential broker, as their turns do, so the egress rules apply; it
+// never follows a redirect, so a server's keys never reach another address.
+import { createHash } from "node:crypto";
+import { readFileSync } from "node:fs";
+
+import { writeFileAtomic } from "../atomic.ts";
+import type { McpServerSpec, RemoteMcpSpec } from "../contracts.ts";
+import { offNotice } from "../mcp-health.ts";
+import { MAX_REMOTE_MCP_BYTES, McpHttpError, REMOTE_MCP_STARTUP_MS, RemoteMcpClient } from "../mcp-http.ts";
+
+/** What an address that is no MCP endpoint answers MCP's initialize with. Not 404: a server that hides behind it until
+ * signed in would be turned off by a check that sends no sign-in. */
+export const NOT_MCP_STATUSES: ReadonlySet<number> = new Set([405]);
+/** A server left out is tried again after this long, as a command server that did not start is. */
+export const RECHECK_NOT_MCP_MS = 30 * 60_000;
+/** An engine reports a failed server at every session start: one check per server address in this long is enough. */
+export const RECHECK_AFTER_ENGINE_MS = 10 * 60_000;
+
+type Bot = { id: string; name: string };
+type UrlServer = { url: string; type?: string; headers?: Record<string, string> };
+/** How the server answered MCP's first request: `status` when it answered with an HTTP error. */
+export type UrlAnswer = { ok: true } | { ok: false; status?: number };
+
+/** A fetch that never follows a redirect: the server's headers, its keys among them, would go along to another address.
+ * A redirect is then an answer like any other HTTP status, which keeps a server in. */
+export const withoutRedirects = (base: typeof fetch = fetch): typeof fetch => (input, init) => base(input, { ...init, redirect: "manual" });
+
+/** MCP's backwards-compatibility rule for an address that refuses the POST: a server of the older HTTP+SSE transport
+ * answers a GET with an event stream ("sse"). A GET that is answered with anything else is a plain page ("not"); one that
+ * fails, is refused or redirects tells nothing ("unknown"). */
+async function speaksSse(server: UrlServer, fetchImpl: typeof fetch, signal: AbortSignal): Promise<"sse" | "not" | "unknown"> {
+ const stop = new AbortController();
+ try {
+ const response = await fetchImpl(server.url, {
+ method: "GET", headers: { ...server.headers, accept: "text/event-stream" }, signal: AbortSignal.any([signal, stop.signal]),
+ });
+ if (!response.ok) return "unknown";
+ // Media types are case-insensitive (RFC 9110).
+ return (response.headers.get("content-type") ?? "").toLowerCase().includes("text/event-stream") ? "sse" : "not";
+ } catch {
+ return "unknown";
+ } finally {
+ stop.abort();
+ }
+}
+
+/** MCP's first request and nothing more: no tool list and no sign-in discovery, so a check reads nothing and costs the
+ * server a request or two. `fetch`: how to reach it (a bot's broker); never one that follows redirects. */
+export async function initializeAnswer(server: RemoteMcpSpec, options: { fetch?: typeof fetch; timeoutMs?: number } = {}): Promise<UrlAnswer> {
+ const fetchImpl = options.fetch ?? withoutRedirects();
+ const signal = AbortSignal.timeout(options.timeoutMs ?? REMOTE_MCP_STARTUP_MS);
+ const client = new RemoteMcpClient(server, { maxBytes: MAX_REMOTE_MCP_BYTES, fetch: fetchImpl });
+ try {
+ await client.initialize("OpenMausBot", signal);
+ return { ok: true };
+ } catch (error) {
+ const status = error instanceof McpHttpError && error.kind === "status" ? error.status : undefined;
+ if (status !== undefined && NOT_MCP_STATUSES.has(status) && server.type !== "sse") {
+ const sse = await speaksSse(server, fetchImpl, signal);
+ // An inconclusive GET is no answer either way: an included server stays in, an excluded one stays out.
+ if (sse !== "not") return sse === "sse" ? { ok: true } : { ok: false };
+ }
+ return status !== undefined ? { ok: false, status } : { ok: false };
+ } finally {
+ await client.close().catch(() => {});
+ }
+}
+
+export interface McpUrlChecksDeps {
+ /** The enabled URL servers the organisation's policy allows, by name. */
+ servers(): Record<string, UrlServer>;
+ /** The bots whose turns start `name`. */
+ users(name: string): Bot[];
+ /** Sends the server MCP's first request (initializeAnswer). */
+ probe(name: string, server: UrlServer): Promise<UrlAnswer>;
+ /** Says it to the person, once. */
+ tell(text: string, about: Bot): void;
+ /** Where the servers the person was told about are kept, so a restart does not tell them again. */
+ file?: string;
+ now?(): number;
+}
+
+/** The plain words a bot and the person get for a server left out. */
+export const notMcpError = (status: number) =>
+ `Its address answered HTTP ${status} to MCP's first request, so it is not an MCP server endpoint. Check the server's URL.`;
+
+/** The server's identity for its check: where it is and how it is reached, so a fixed URL is checked again. */
+const urlKey = (server: UrlServer) => createHash("sha256")
+ .update(JSON.stringify([server.url, server.type ?? "http", Object.entries(server.headers ?? {}).sort()])).digest("hex").slice(0, 32);
+
+export function createMcpUrlChecks(deps: McpUrlChecksDeps) {
+ const now = deps.now ?? Date.now;
+ const off = new Map<string, { key: string; at: number; error: string }>();
+ const told = new Set<string>();
+ if (deps.file) {
+ try {
+ const saved = JSON.parse(readFileSync(deps.file, "utf8")) as { told?: unknown };
+ if (Array.isArray(saved.told)) for (const id of saved.told) if (typeof id === "string") told.add(id);
+ } catch {}
+ }
+ const saveTold = () => {
+ if (!deps.file) return;
+ // Only servers still configured as they were told about: a changed or removed one is told about afresh.
+ const current = new Set(Object.entries(deps.servers()).map(([name, server]) => `${name}\u0000${urlKey(server)}`));
+ for (const id of told) if (!current.has(id)) told.delete(id);
+ try { writeFileAtomic(deps.file, JSON.stringify({ told: [...told] }), { mode: 0o600 }); } catch (error) { console.warn("[mcp] could not save URL server checks:", error); }
+ };
+ const checkedAt = new Map<string, number>();
+ const running = new Map<string, Promise<void>>();
+
+ const check = (name: string, force: boolean): Promise<void> => {
+ const server = deps.servers()[name];
+ if (!server) { off.delete(name); return Promise.resolve(); }
+ const key = urlKey(server);
+ const id = `${name}\u0000${key}`;
+ const pending = running.get(id);
+ if (pending) return pending;
+ const last = checkedAt.get(id);
+ if (!force && last !== undefined && now() - last < RECHECK_AFTER_ENGINE_MS) return Promise.resolve();
+ checkedAt.set(id, now());
+ const work = deps.probe(name, server).catch((): UrlAnswer => ({ ok: false })).then((answer) => {
+ const current = deps.servers()[name];
+ if (!current || urlKey(current) !== key) return;
+ if (answer.ok) {
+ off.delete(name);
+ return;
+ }
+ if (answer.status === undefined || !NOT_MCP_STATUSES.has(answer.status)) {
+ // An answer that is no MCP answer (a timeout, a refusal) proves nothing either way: a server left out stays out
+ // until it answers as MCP, so it does not flip in and out on a busy computer; one in stays in.
+ const entry = off.get(name);
+ if (entry?.key === key) entry.at = now();
+ return;
+ }
+ off.set(name, { key, at: now(), error: notMcpError(answer.status) });
+ if (told.has(id)) return;
+ told.add(id);
+ saveTold();
+ const about = deps.users(name)[0];
+ if (about) deps.tell(offNotice(name, null), about);
+ }).finally(() => running.delete(id));
+ running.set(id, work);
+ return work;
+ };
+
+ /** The server's entry while it still describes the server as configured now. */
+ const offNow = (name: string) => {
+ const entry = off.get(name), server = deps.servers()[name];
+ return entry && server && entry.key === urlKey(server) ? entry : undefined;
+ };
+
+ return {
+ /** `mounted` without the URL servers that are no MCP endpoint; one due to be tried again is, in the background. */
+ usable<T extends McpServerSpec>(mounted: Record<string, T>): Record<string, T> {
+ return Object.fromEntries(Object.entries(mounted).filter(([name]) => {
+ const entry = offNow(name);
+ if (entry && now() - entry.at >= RECHECK_NOT_MCP_MS) void check(name, true);
+ return !entry;
+ }));
+ },
+ /** Which of `names` are left out, with why. */
+ off(names: readonly string[]): Array<{ name: string; error: string }> {
+ return names.flatMap((name) => {
+ const entry = offNow(name);
+ return entry ? [{ name, error: entry.error }] : [];
+ });
+ },
+ /** Who a server is left out for, by bot id. */
+ offFor(name: string): string[] {
+ return offNow(name) ? deps.users(name).map((bot) => bot.id) : [];
+ },
+ /** A server was added, changed or turned on: checked now. */
+ changed(names: readonly string[]): void {
+ for (const name of names) if (deps.servers()[name]) void check(name, true);
+ },
+ /** The bot's AI reported these did not connect: each is checked, at most once per address in RECHECK_AFTER_ENGINE_MS. */
+ engineFailed(names: readonly string[]): void {
+ for (const name of names) if (deps.servers()[name]) void check(name, false);
+ },
+ /** In the background, every enabled URL server some bot's turns start. */
+ checkAll(): void {
+ for (const name of Object.keys(deps.servers())) if (deps.users(name).length) void check(name, false);
+ },
+ /** Settles once every check started so far has. */
+ async settled(): Promise<void> {
+ while (running.size) await Promise.all(running.values());
+ },
+ };
+}
+
+export type McpUrlChecks = ReturnType<typeof createMcpUrlChecks>;
diff --git a/server/index.ts b/server/index.ts
index 74309df0c0..7c5597f775 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -1351,7 +1351,7 @@ const attributeUsage = createUsageAttribution({ section: (botId) => store.bot(bo
} usageCapGate.booked(row.botId);
}
-const providerAuthSessions = new ProviderAuthSessions({ signedIn: (instanceId) => limitTakeover.signedIn(instanceId) }); const mcpServersHost = createMcpServersHost({ dataDir: DATA_DIR, cfg: () => cfg, moveGrants: (bot, move) => moveSavedGrants(store, bot, move), persist: persistMcpServers, bots: () => store.bots, policy: (servers) => managedPolicy.filterMcp(servers), tell: (text, about) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), startsServers: (botId) => { const bot = store.bot(botId); return Boolean(bot && registry.get(bot.modelSelection.instanceId)?.adapter.capabilities.customMcp === true); }, boxed: () => botBox.enabled(), keys: mcpKeys, forgetSignIn: (name) => mcpOAuth.forget(name) });
+const providerAuthSessions = new ProviderAuthSessions({ signedIn: (instanceId) => limitTakeover.signedIn(instanceId) }); const mcpServersHost = createMcpServersHost({ dataDir: DATA_DIR, cfg: () => cfg, personMcp: () => teamConnections.personMcp(), botsPath: () => brokerPath(botBox), moveGrants: (bot, move) => moveSavedGrants(store, bot, move), persist: persistMcpServers, bots: () => store.bots, policy: (servers) => managedPolicy.filterMcp(servers), tell: (text, about) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), startsServers: (botId) => { const bot = store.bot(botId); return Boolean(bot && registry.get(bot.modelSelection.instanceId)?.adapter.capabilities.customMcp === true); }, boxed: () => botBox.enabled(), keys: mcpKeys, forgetSignIn: (name) => mcpOAuth.forget(name) });
const mcpOAuth = new McpOAuthManager({
file: join(DATA_DIR, "mcp-oauth.json"),
isOwnerLive: (owner) => owner === "loopback" || sessions.isLive(owner) || isCardOwnerLive(store, owner),