Skip to content

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

Say which MCP server needs a sign-in, and stop Test passing when every call is refused (#5105)

Milind Soni542f8e55f3f9
diff --git a/docs/bot-box.md b/docs/bot-box.md
index f2b15f7b01..b3003c20c0 100644
--- a/docs/bot-box.md
+++ b/docs/bot-box.md
@@ -93,7 +93,10 @@ Cloudflare Worker answers with 404), anything below it below that address, with
upstream's own. MCP Settings → **Test** reaches a URL server the same way where turns are boxed
(`server/bot-box/broker-probe.ts`): a grant made like a turn's, through the broker's socket, revoked when the test
ends. A server that answers directly but not through the broker fails the test with "Your bots can't reach this
-server", never "Connected", and says the fault is ours. Connected apps (Composio) were already behind the harness
+server", never "Connected", and says the fault is ours. A tool call a URL server refuses with HTTP 401 is answered by the
+broker 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
(`/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, Cerebras, MiniMax, Kimi, Cursor, Factory,
diff --git a/docs/custom-mcp-servers.md b/docs/custom-mcp-servers.md
index e09a69d9b1..cfd753fbdb 100644
--- a/docs/custom-mcp-servers.md
+++ b/docs/custom-mcp-servers.md
@@ -117,7 +117,11 @@ button. Sign in opens the provider's page in your browser, which returns to
OpenMausBot when you approve. The server then shows **Signed in**, and Test
lists its tools. A server that lists its tools before you sign in but refuses
tool calls the same way (an HTTP 401 pointing at those sign-in details) shows
-**Sign in** too.
+**Sign in** too. Test first calls a tool name no server has. If the server
+answers that without asking who is calling, as Gmail's MCP server does, Test
+calls one of the server's own tools once, with no arguments: only a tool the
+server marks read-only and not destructive, and that requires arguments, so it
+has nothing to work on. Background checks never do this.
- **Which servers work.** The authorization server must support PKCE with
S256. If it lets apps register themselves (dynamic client registration),
diff --git a/server/bot-box/broker-mcp-refusal.test.ts b/server/bot-box/broker-mcp-refusal.test.ts
new file mode 100644
index 0000000000..cca5cecdf4
--- /dev/null
+++ b/server/bot-box/broker-mcp-refusal.test.ts
@@ -0,0 +1,118 @@
+// A URL server that lists its tools to anyone and refuses every tool call without a sign-in, reached the way a boxed turn
+// reaches it: the turn's grant, a real broker on its socket and the box's own bridge to the broker's loopback port.
+import { mkdtempSync, rmSync } from "node:fs";
+import type { AddressInfo, Server } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { openBridge } from "./box-bridge.ts";
+import type { BoxBroker } from "./box.ts";
+import { refusedCallAnswer } from "./broker-mcp-refusal.ts";
+import { brokerRemoteMcp, forgetBrokeredMcp } from "./broker-mcp.ts";
+import { brokeredServer } from "./broker-probe.ts";
+import { brokerUrl, openCredentialBroker, type CredentialBroker } from "./broker.ts";
+import type { McpServerSpec, RemoteMcpSpec } from "../contracts.ts";
+import { McpHttpError, RemoteMcpClient } from "../mcp-http.ts";
+import { probeMcpServer } from "../mcp-probe.ts";
+import { startFakeHttpMcp, type FakeHttpMcp, type FakeHttpMcpOptions } from "../testing/fake-http-mcp-server.ts";
+import { startFakeOAuth, type FakeOAuth } from "../testing/fake-oauth-server.ts";
+
+const READ = { name: "get_thread", annotations: { readOnlyHint: true }, inputSchema: { type: "object", required: ["threadId"] } };
+const TURN = { botId: "bot-1", threadId: "thread-1" };
+
+describe.skipIf(process.platform === "win32")("an MCP server that refuses a boxed turn's tool call", () => {
+ let dir = "", credentials: CredentialBroker | undefined, bridge: Server | undefined, server: FakeHttpMcp | undefined, oauth: FakeOAuth | undefined;
+ afterEach(async () => {
+ forgetBrokeredMcp();
+ await new Promise((resolve) => (bridge ? bridge.close(resolve) : resolve(undefined)));
+ await credentials?.close();
+ await server?.close();
+ await oauth?.close();
+ credentials = bridge = server = oauth = undefined;
+ if (dir) rmSync(dir, { recursive: true, force: true });
+ });
+
+ async function boxed(options: FakeHttpMcpOptions, headers: Record<string, string> = {}) {
+ oauth = await startFakeOAuth();
+ server = await startFakeHttpMcp({ guard: "listed-tools", acceptBearer: () => false, wwwAuthenticate: oauth.challenge, tools: [READ], ...options });
+ dir = mkdtempSync(join(tmpdir(), "omb-broker-refusal-"));
+ credentials = await openCredentialBroker({ socketPath: join(dir, "b.sock") });
+ bridge = 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;
+ return { mounted, target: { type: "http" as const, url: server.url, headers, enabled: true }, path: { broker, socketPath: credentials.socketPath } };
+ }
+ const callTool = async (spec: RemoteMcpSpec) => {
+ const client = new RemoteMcpClient(spec);
+ const signal = AbortSignal.timeout(10_000);
+ try {
+ await client.initialize("engine", signal);
+ expect(await client.request("tools/list", {}, signal)).toMatchObject({ tools: [{ name: "get_thread" }] });
+ return await client.request("tools/call", { name: "get_thread", arguments: { threadId: "t" } }, signal) as { isError?: boolean; content: Array<{ text: string }> };
+ } finally { await client.close(); }
+ };
+
+ it("tells the engine which server needs a sign-in and what to do, and Test no longer says it works", async () => {
+ const { mounted, target, path } = await boxed({});
+ const 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(server!.calls).toEqual([]);
+
+ const grant = brokeredServer(path, "mail", target);
+ try {
+ await expect(probeMcpServer(target, 8_000, undefined, { tryReadOnlyTool: true, via: { url: grant.url, fetch: grant.fetch } }))
+ .resolves.toEqual({ ok: false, auth: "required", error: "This server needs you to sign in." });
+ } finally { await grant.done(); }
+ });
+
+ 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);
+ expect(result.isError).toBe(true);
+ expect(result.content[0]!.text).toContain('The MCP server "mail" refused the sign-in or key it was sent');
+ expect(result.content[0]!.text).not.toContain("stale");
+ });
+
+ it("leaves a tool call the server accepts alone", async () => {
+ const { mounted } = await boxed({ acceptBearer: () => true });
+ await expect(callTool(mounted)).resolves.toEqual({ content: [{ type: "text", text: "remote execution recorded" }] });
+ });
+
+ it("still passes a refused initialize through, so the engine reports the server as not connected", async () => {
+ const { mounted } = await boxed({ guard: "every-request" });
+ const client = new RemoteMcpClient(mounted);
+ await expect(client.initialize("engine", AbortSignal.timeout(10_000))).rejects.toMatchObject({ status: 401 });
+ await expect(client.initialize("engine", AbortSignal.timeout(10_000))).rejects.toBeInstanceOf(McpHttpError);
+ await client.close();
+ });
+
+ it("keeps a 401 as a 401 on a grant that isn't a turn's MCP server", async () => {
+ const { target, path } = await boxed({});
+ const { token } = credentials!.mintForThread({ threadId: "other", grants: { "mcp-mail": { upstream: target.url, headers: {} } } });
+ const client = new RemoteMcpClient({ type: "http", url: brokerUrl(path.broker.port, token, "mcp-mail"), headers: {} });
+ const signal = AbortSignal.timeout(10_000);
+ await client.initialize("engine", signal);
+ await expect(client.request("tools/call", { name: "get_thread", arguments: {} }, signal)).rejects.toMatchObject({ status: 401 });
+ await client.close();
+ });
+});
+
+describe("the answer to a refused call", () => {
+ 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 } });
+ });
+
+ it.each([
+ ["another method", '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'],
+ ["a notification", '{"jsonrpc":"2.0","method":"tools/call"}'],
+ ["a batch", '[{"jsonrpc":"2.0","id":1,"method":"tools/call"}]'],
+ ["not JSON", "<html>"],
+ ])("passes %s through", (_label, body) => {
+ expect(refusedCallAnswer("mail", false, body)).toBeNull();
+ });
+});
diff --git a/server/bot-box/broker-mcp-refusal.ts b/server/bot-box/broker-mcp-refusal.ts
new file mode 100644
index 0000000000..a7d9a96453
--- /dev/null
+++ b/server/bot-box/broker-mcp-refusal.ts
@@ -0,0 +1,20 @@
+// What a boxed engine hears when an MCP server refuses one of its tool calls with HTTP 401. Passed through, the 401 starts the
+// 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.
+
+/** 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;
+
+/** 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 {
+ 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.`;
+ 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.ts
index 08ecd4cf99..4ec19d398d 100644
--- a/server/bot-box/broker-mcp.ts
+++ b/server/bot-box/broker-mcp.ts
@@ -34,11 +34,11 @@ export function brokerRemoteMcp(custom: Record<string, McpServerSpec>, turn: Bro
// 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> }> = {};
+ const grants: Record<string, { upstream: string; headers: Record<string, string>; mcpServer: string }> = {};
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 } };
+ grants[mcpGrantName(name)] = { upstream: server.url, headers: { ...server.headers }, mcpServer: name };
brokered.push(name);
}
if (!brokered.length) return custom;
diff --git a/server/bot-box/broker.ts b/server/bot-box/broker.ts
index f2866b7e6d..d0d76fc49e 100644
--- a/server/bot-box/broker.ts
+++ b/server/bot-box/broker.ts
@@ -8,6 +8,8 @@ import { createServer, request as httpRequest, type IncomingMessage, type Server
import { request as httpsRequest } from "node:https";
import type { Socket } from "node:net";
+import { MAX_REFUSABLE_CALL_BYTES, refusedCallAnswer } from "./broker-mcp-refusal.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. */
export const BROKER_PROCESS_TTL_MS = 24 * 60 * 60_000;
@@ -21,6 +23,8 @@ export interface BrokerGrant {
upstream: string;
/** Headers the broker adds (the real key); the same names from the client are dropped. */
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;
}
export interface BrokerToken {
@@ -94,7 +98,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 } }]));
+ const grants = Object.fromEntries(Object.entries(input.grants).map(([name, grant]) => [name, { upstream: grant.upstream, headers: { ...grant.headers }, ...(grant.mcpServer ? { mcpServer: grant.mcpServer } : {}) }]));
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 };
};
@@ -124,11 +128,26 @@ export function openCredentialBroker(options: CredentialBrokerOptions): Promise<
for (const [name, value] of Object.entries(verdict.grant.headers)) headers[name.toLowerCase()] = value;
headers.host = upstream.host;
const send = requestFn ?? (upstream.protocol === "https:" ? httpsRequest : httpRequest);
- const forwarded = send({ protocol: upstream.protocol, host: upstream.hostname, port: upstream.port || (upstream.protocol === "https:" ? 443 : 80), method: req.method, path: `${upstream.pathname}${upstream.search}`, headers }, (answer) => {
+ const relay = (answer: IncomingMessage) => {
const out: Record<string, string | string[]> = {};
for (const [name, value] of Object.entries(answer.headers)) if (value !== undefined && !HOP_BY_HOP.has(name)) out[name] = value;
res.writeHead(answer.statusCode ?? 502, out);
answer.pipe(res);
+ };
+ const mcpServer = req.method === "POST" ? verdict.grant.mcpServer : undefined;
+ const sent: Buffer[] = [];
+ let sentBytes = 0;
+ if (mcpServer) req.on("data", (chunk: Buffer) => { sentBytes += chunk.length; if (sentBytes <= MAX_REFUSABLE_CALL_BYTES) sent.push(chunk); });
+ const forwarded = send({ protocol: upstream.protocol, host: upstream.hostname, port: upstream.port || (upstream.protocol === "https:" ? 443 : 80), method: req.method, path: `${upstream.pathname}${upstream.search}`, headers }, (answer) => {
+ 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;
+ if (refusal === null) return relay(answer);
+ answer.resume();
+ res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" }).end(refusal);
+ };
+ if (req.readableEnded) decide(); else req.once("end", decide);
});
stats.forwarded += 1;
forwarded.on("error", () => { if (!res.headersSent) res.writeHead(502, { "content-type": "application/json" }).end(JSON.stringify({ error: "upstream_unreachable" })); else res.destroy(); });
diff --git a/server/host/mcp-config.test.ts b/server/host/mcp-config.test.ts
index 27352a6f1a..da6f499d1c 100644
--- a/server/host/mcp-config.test.ts
+++ b/server/host/mcp-config.test.ts
@@ -112,6 +112,13 @@ describe("shared MCP config", () => {
probe.mockRestore();
});
+ it("says which server it could not find", async () => {
+ const { config } = fixture();
+ const missing = { status: 404, error: 'MCP server "mail" not found. It may have been removed: check Apps → MCP servers.' };
+ expect(config.remove("mail")).toEqual(missing);
+ await expect(config.test("mail", { signal: new AbortController().signal })).resolves.toEqual(missing);
+ });
+
it("a write while busy returns 409 \"MCP servers are already being updated.\"", () => {
const { config, changed, setBusy } = fixture();
setBusy(true);
diff --git a/server/host/mcp-config.ts b/server/host/mcp-config.ts
index bba64d71c0..ff47baf384 100644
--- a/server/host/mcp-config.ts
+++ b/server/host/mcp-config.ts
@@ -2,7 +2,7 @@ import { userError, type UserError } from "../user-errors.ts";
import { withMcpSignIn, type McpOAuthManager } from "../mcp-oauth.ts";
import { brokeredServer, type BrokerPath } from "../bot-box/broker-probe.ts";
import { probeMcpServer, sendsCredentials, type McpProbeOptions, type McpProbeResult } from "../mcp-probe.ts";
-import { MAX_MCP_SERVERS, isRemoteMcpServer, parseStoredMcpServer, type McpRunsOn, type StoredMcpServer, type StoredRemoteMcpServer } from "../mcp-registry.ts";
+import { MAX_MCP_SERVERS, isRemoteMcpServer, mcpServerNotFound, parseStoredMcpServer, type McpRunsOn, type StoredMcpServer, type StoredRemoteMcpServer } from "../mcp-registry.ts";
import { postizKeyHeaders } from "../postiz/connection.ts";
import type { AppConfig } from "../config.ts";
import type { ChatAppsMcp } from "../chat-apps-mcp.ts";
@@ -124,7 +124,7 @@ export function createMcpConfig(deps: McpConfigDeps & { changed(): void }): McpC
const saved = (status: number): McpConfigResult => ({ status, body: mcpServerResponse() });
const stored = (name: string) => {
const current = cfg.mcpServers ?? {};
- if (!Object.hasOwn(current, name)) return { result: { status: 404, error: "MCP server not found." } as McpConfigResult };
+ if (!Object.hasOwn(current, name)) return { result: { status: 404, error: mcpServerNotFound(name) } as McpConfigResult };
const existing = parseStoredMcpServer(name, current[name]);
return existing.ok ? { current, existing: existing.server } : { result: { status: 400, error: existing.error } as McpConfigResult };
};
@@ -219,7 +219,7 @@ export function createMcpConfig(deps: McpConfigDeps & { changed(): void }): McpC
}),
remove: (name) => write(() => {
const current = cfg.mcpServers ?? {};
- if (!Object.hasOwn(current, name)) return { status: 404, error: "MCP server not found." };
+ if (!Object.hasOwn(current, name)) return { status: 404, error: mcpServerNotFound(name) };
const next = { ...current };
delete next[name];
persistMcpServers(next);
@@ -231,7 +231,7 @@ export function createMcpConfig(deps: McpConfigDeps & { changed(): void }): McpC
}),
test: async (name, { signal, person, asBot, lender }) => {
const raw = cfg.mcpServers?.[name];
- if (raw === undefined) return { status: 404, error: "MCP server not found." };
+ if (raw === undefined) return { status: 404, error: mcpServerNotFound(name) };
const parsed = parseStoredMcpServer(name, raw);
if (!parsed.ok) return { status: 400, error: parsed.error };
const { runsOn } = parsed.server;
@@ -260,7 +260,7 @@ export function createMcpConfig(deps: McpConfigDeps & { changed(): void }): McpC
sentSignIn = true;
}
}
- const options = { ...(personal ? {} : appCatalog?.probeOptions(name, parsed.server) ?? {}), ...(asBot ? { asBot } : isRemoteMcpServer(target) ? {} : { asBot: deps.probeAs?.(target) ?? {} }) };
+ const options = { tryReadOnlyTool: true, ...(personal ? {} : appCatalog?.probeOptions(name, parsed.server) ?? {}), ...(asBot ? { asBot } : isRemoteMcpServer(target) ? {} : { asBot: deps.probeAs?.(target) ?? {} }) };
const viaBots = isRemoteMcpServer(target) ? deps.botsPath?.() ?? null : null;
const result = viaBots && isRemoteMcpServer(target)
? await probeAsBots(viaBots, name, target, signal, options)
diff --git a/server/index.ts b/server/index.ts
index 6ecff4b7c6..5aeadecdab 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -219,7 +219,7 @@ import {
isRemoteMcpServer,
parseStoredMcpServer,
} from "./mcp-registry.ts";
-import { attachCustomMcp } from "./mcp-result-budget.ts";
+import { attachCustomMcp } from "./mcp-result-budget.ts"; import { mcpToolProblem } from "./mcp-failure.ts";
import { MCP_OAUTH_CALLBACK_PATH, McpOAuthManager } from "./mcp-oauth.ts";
import {
GROUP_GOAL_WAIT_MAX_MS,
@@ -6461,7 +6461,7 @@ bus.subscribe((event: RuntimeEvent) => {
const existing = store.messagesFor(event.threadId).find((m) => m.id === messageId)?.tool;
toolName = existing?.name ?? "tool";
store.patchMessage(event.threadId, messageId, {
- tool: { ...existing, name: toolName, ok: event.ok, output: event.output === undefined ? undefined : scrubHeldSecrets(event.output) },
+ tool: { ...existing, name: toolName, ok: event.ok, output: event.output === undefined ? undefined : scrubHeldSecrets(event.output), ...mcpToolProblem(toolName, event.ok, event.output, Object.keys(cfg.mcpServers ?? {}), threadLanguage(event.threadId)) },
});
toolMessageByItem.delete(itemKey);
}
diff --git a/server/mcp-failure.test.ts b/server/mcp-failure.test.ts
new file mode 100644
index 0000000000..91b048af0d
--- /dev/null
+++ b/server/mcp-failure.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from "vitest";
+
+import { mcpFailureKind, mcpServerOfTool, mcpToolProblem } from "./mcp-failure.ts";
+
+describe("why an MCP step failed", () => {
+ it.each([
+ ['The MCP server "mail" needs a sign-in before its tools work, and nobody has signed in (HTTP 401), so nothing ran.', "sign-in"],
+ ['The MCP server "mail" refused the sign-in or key it was sent (HTTP 401), so nothing ran.', "refused"],
+ ['MCP server "mail" needs authentication', "sign-in"],
+ ['MCP server "mail" needs additional permissions (scope: "x")', "sign-in"],
+ ['MCP server "mail" rejected the Authorization header in its config', "refused"],
+ ['MCP server "mail" is not connected: boom', "cant-connect"],
+ ['MCP server "mail" session expired', "cant-connect"],
+ ['Dynamic Client Registration rejected (HTTP 404): {"error":"not_found"}', "sign-in"],
+ ["HTTP 401 dialing http://127.0.0.1:18080/b/REDACTED/mcp-mail", "sign-in"],
+ ["HTTP 403 dialing http://127.0.0.1:18080/b/REDACTED/mcp-mail", "refused"],
+ ["HTTP 404 dialing http://127.0.0.1:18080/b/REDACTED/mcp-mail", "not-found"],
+ ["HTTP 504 dialing http://127.0.0.1:18080/b/REDACTED/mcp-mail", "timeout"],
+ ["Error dialing http://127.0.0.1:18080/b/REDACTED/mcp-mail", "cant-connect"],
+ ["TypeError dialing http://127.0.0.1:18080/b/REDACTED/mcp-mail (ECONNREFUSED)", "cant-connect"],
+ ["ECONNREFUSED: Unable to connect. Is the computer able to access the url?", "cant-connect"],
+ ["MCP error -32001: Request timed out", "timeout"],
+ ["MCP error -32000: Connection closed", "cant-connect"],
+ ["MCP error -32603: This MCP server refused its credentials (HTTP 401). If it uses a sign-in", "refused"],
+ ["This MCP server's address was not found (HTTP 404). Check its URL.", "not-found"],
+ ["Could not reach this MCP server. Check its URL and that it is online.", "cant-connect"],
+ ["MCP request timed out; execution outcome may be uncertain", "timeout"],
+ ["MCP server exited before the session closed", "cant-connect"],
+ ["<tool_use_error>MCP server \"mail\" needs authentication</tool_use_error>", "sign-in"],
+ ] as const)("%s", (output, kind) => {
+ expect(mcpFailureKind(output)).toBe(kind);
+ });
+
+ it.each([
+ ["the chat runtime's result", JSON.stringify({ ok: false, result: "MCP request timed out; execution outcome may be uncertain" }, null, 2), "timeout"],
+ ["MCP's own content list", JSON.stringify([{ type: "text", text: 'MCP server "mail" needs authentication' }], null, 2), "sign-in"],
+ ["a chat-runtime tool's own error", JSON.stringify({ ok: false, result: "Thread not found" }, null, 2), null],
+ ])("reads through %s", (_label, output, kind) => {
+ expect(mcpFailureKind(output)).toBe(kind);
+ });
+
+ it.each(["Thread not found", "Invalid query: HTTP 401 from example.com", "The page answered 404", "Request failed because the mailbox is full"])("leaves the tool's own error alone: %s", (output) => {
+ expect(mcpFailureKind(output)).toBeNull();
+ });
+});
+
+describe("which server a step belongs to", () => {
+ const servers = ["mail", "mail-work", "my.notes"];
+ it.each([
+ ["mcp__mail__search", "mail"],
+ ["mcp__mail-work__search", "mail-work"],
+ ["mail__search", "mail"],
+ ["mail.search", "mail"],
+ ["mail_search", "mail"],
+ ["my_notes_read", "my.notes"],
+ ])("%s", (tool, server) => { expect(mcpServerOfTool(tool, servers)).toBe(server); });
+
+ it.each(["mcp__agents__list_bots", "Bash", "mailbox_search"])("none for %s", (tool) => { expect(mcpServerOfTool(tool, servers)).toBeUndefined(); });
+});
+
+describe("the line a person reads", () => {
+ const servers = ["mail"];
+ it("names the server, the reason and what to do", () => {
+ expect(mcpToolProblem("mcp__mail__search", false, 'The MCP server "mail" needs a sign-in before its tools work.', servers))
+ .toEqual({ problem: "mail needs you to sign in before its tools work. Open Apps → MCP servers and sign in to it." });
+ expect(mcpToolProblem("mcp__mail__search", false, "TypeError dialing http://127.0.0.1:18080/b/REDACTED/mcp-mail (ECONNREFUSED)", servers))
+ .toEqual({ problem: "Couldn't connect to mail. Test it in Apps → MCP servers to see why." });
+ });
+
+ it.each([
+ ["a step that worked", "mcp__mail__search", true, "MCP request timed out"],
+ ["a step with no output", "mcp__mail__search", false, undefined],
+ ["a tool's own error", "mcp__mail__search", false, "Thread not found"],
+ ["a tool of no configured server", "Bash", false, "MCP request timed out"],
+ ])("has none for %s", (_label, tool, ok, output) => {
+ expect(mcpToolProblem(tool, ok, output, servers)).toEqual({});
+ });
+});
diff --git a/server/mcp-failure.ts b/server/mcp-failure.ts
new file mode 100644
index 0000000000..3e37bc6eff
--- /dev/null
+++ b/server/mcp-failure.ts
@@ -0,0 +1,78 @@
+// The words a person reads when a step on one of their MCP servers fails: which server, why, and what to do. Only failures
+// worded by an MCP client or by this server's own proxies are recognised. A tool's own error ("thread not found") is that
+// tool's answer rather than the server failing, so it gets no line and its output speaks for itself.
+import { serverLine, type ServerLineKey } from "./server-lines.ts";
+
+export type McpFailureKind = "sign-in" | "refused" | "not-found" | "timeout" | "cant-connect";
+
+const KIND_LINE: Readonly<Record<McpFailureKind, ServerLineKey>> = {
+ "sign-in": "server.mcp.problem.signIn",
+ refused: "server.mcp.problem.refused",
+ "not-found": "server.mcp.problem.notFound",
+ timeout: "server.mcp.problem.timeout",
+ "cant-connect": "server.mcp.problem.cantConnect",
+};
+
+const NAMED = String.raw`(?:The )?MCP server "[^"]+"`;
+const FAILURES: ReadonlyArray<readonly [RegExp, McpFailureKind]> = [
+ // The credential broker's own answers (bot-box/broker-mcp-refusal.ts).
+ [new RegExp(`^${NAMED} needs a sign-in\\b`), "sign-in"],
+ [new RegExp(`^${NAMED} refused the sign-in or key\\b`), "refused"],
+ // Claude Code's words for a server it can't use.
+ [new RegExp(`^${NAMED} needs (?:authentication|additional permissions)\\b`), "sign-in"],
+ [new RegExp(`^${NAMED} rejected\\b`), "refused"],
+ [new RegExp(`^${NAMED} (?:is not connected|session expired)\\b`), "cant-connect"],
+ [/^Dynamic Client Registration rejected\b/, "sign-in"],
+ [/^HTTP 401 dialing /, "sign-in"],
+ [/^HTTP 403 dialing /, "refused"],
+ [/^HTTP 404 dialing /, "not-found"],
+ [/^HTTP (?:408|504) dialing /, "timeout"],
+ // Any other "<cause> dialing <address>": Claude Code hides the cause when the address holds a token.
+ [/^\S+(?: \d{3})? dialing /, "cant-connect"],
+ [/^(?:ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ENETUNREACH)\b/, "cant-connect"],
+ [/^ETIMEDOUT\b/, "timeout"],
+ // The remote proxy's words (mcp-remote-proxy.ts) and the MCP SDK's.
+ [/^This MCP server refused (?:its credentials|the request)\b/, "refused"],
+ [/^This MCP server's address was not found\b/, "not-found"],
+ [/^Could not reach this MCP server\b/, "cant-connect"],
+ [/^Request timed out\b/, "timeout"],
+ [/^Connection closed\b/, "cant-connect"],
+ // The chat runtime's MCP client (drivers/chat-mcp-tools.ts).
+ [/^MCP (?:request|startup) timed out\b/, "timeout"],
+ [/^MCP (?:server could not start|server exited|server input closed|session closed)\b/, "cant-connect"],
+];
+
+/** What the engine said, out of the JSON a step's output may be: the chat runtime's `{ ok, result }`, or MCP's own content list. */
+function reportedText(output: string): string {
+ try {
+ const parsed = JSON.parse(output) as { result?: unknown } | Array<{ text?: unknown }>;
+ const text = Array.isArray(parsed) ? parsed[0]?.text : parsed?.result;
+ return typeof text === "string" ? text : output;
+ } catch {
+ return output;
+ }
+}
+
+/** Why an MCP step failed, from the first line of what the engine reported; null when it is the tool's own error. */
+export function mcpFailureKind(output: string): McpFailureKind | null {
+ const first = reportedText(output).replace(/^\s*<tool_use_error>\s*/, "").split("\n", 1)[0]!.trim().replace(/^(?:Error: )?(?:MCP error -?\d+: )/, "");
+ return FAILURES.find(([pattern]) => pattern.test(first))?.[1] ?? null;
+}
+
+/** The configured MCP server a step's tool belongs to, as each engine spells it: after `mcp__` with two underscores before
+ * the tool (Claude Code), two underscores alone (ACP), one (the chat runtime, Pi), or a dot. The longest name that fits wins. */
+export function mcpServerOfTool(tool: string, servers: readonly string[]): string | undefined {
+ const name = tool.toLowerCase();
+ return [...servers].sort((a, b) => b.length - a.length).find((server) => {
+ const own = server.toLowerCase(), flat = own.replace(/[^a-z0-9_]+/g, "_");
+ return name.startsWith(`mcp__${own}__`) || name.startsWith(`${own}__`) || name.startsWith(`${own}.`) || name.startsWith(`${flat}_`);
+ });
+}
+
+/** The `problem` line for a finished step: only a failed step on a configured MCP server whose failure is recognised has one. */
+export function mcpToolProblem(tool: string, ok: boolean | undefined, output: string | undefined, servers: readonly string[], language?: string): { problem?: string } {
+ if (ok !== false || !output) return {};
+ const server = mcpServerOfTool(tool, servers);
+ const kind = server ? mcpFailureKind(output) : null;
+ return server && kind ? { problem: serverLine(language, KIND_LINE[kind], { name: server }) } : {};
+}
diff --git a/server/mcp-probe.test.ts b/server/mcp-probe.test.ts
index 886950933b..d06ca81d90 100644
--- a/server/mcp-probe.test.ts
+++ b/server/mcp-probe.test.ts
@@ -263,6 +263,69 @@ describe("remote MCP probe", () => {
}
});
+ describe("a server that answers an unknown tool before it asks who is calling, as Gmail's MCP server does", () => {
+ const read = { name: "get_thread", annotations: { readOnlyHint: true, destructiveHint: false }, inputSchema: { type: "object", required: ["threadId"] } };
+ const asked = { tryReadOnlyTool: true };
+
+ it("needs a sign-in, found with one read-only tool that has nothing to work on, and nothing runs", async () => {
+ const oauth = await startFakeOAuth();
+ const fake = await startFakeHttpMcp({ guard: "listed-tools", acceptBearer: oauth.isValid, wwwAuthenticate: oauth.challenge, tools: [buy, read] });
+ try {
+ await expect(probeMcpServer(anonymous(fake.url), 8_000, undefined, asked))
+ .resolves.toEqual({ ok: false, auth: "required", error: "This server needs you to sign in." });
+ expect(fake.refusedCalls).toEqual([{ name: "get_thread", arguments: {} }]);
+ expect(fake.calls).toEqual([]);
+ } finally {
+ await fake.close();
+ await oauth.close();
+ }
+ });
+
+ it("calls no real tool in a check nobody asked for", async () => {
+ const oauth = await startFakeOAuth();
+ const fake = await startFakeHttpMcp({ guard: "listed-tools", acceptBearer: oauth.isValid, wwwAuthenticate: oauth.challenge, tools: [read] });
+ try {
+ await expect(probeMcpServer(anonymous(fake.url), 8_000)).resolves.toMatchObject({ ok: true });
+ expect(fake.refusedCalls).toEqual([]);
+ } finally {
+ await fake.close();
+ await oauth.close();
+ }
+ });
+
+ it.each([
+ ["not marked read-only", { name: "trash", inputSchema: { type: "object", required: ["id"] } }],
+ ["marked read-only and destructive", { name: "purge", annotations: { readOnlyHint: true, destructiveHint: true }, inputSchema: { type: "object", required: ["id"] } }],
+ ["read-only but able to run with no arguments", { name: "list_labels", annotations: { readOnlyHint: true }, inputSchema: { type: "object" } }],
+ ])("never calls a tool %s", async (_label, tool) => {
+ const oauth = await startFakeOAuth();
+ const fake = await startFakeHttpMcp({ guard: "listed-tools", acceptBearer: oauth.isValid, wwwAuthenticate: oauth.challenge, tools: [tool] });
+ try {
+ await expect(probeMcpServer(anonymous(fake.url), 8_000, undefined, asked)).resolves.toMatchObject({ ok: true });
+ expect(fake.refusedCalls).toEqual([]);
+ expect(fake.calls).toEqual([]);
+ } finally {
+ await fake.close();
+ await oauth.close();
+ }
+ });
+
+ it("stays connected when sign-in is optional and the read-only tool only complains about its arguments", async () => {
+ const oauth = await startFakeOAuth();
+ const fake = await startFakeHttpMcp({
+ tools: [read],
+ wellKnown: { "/.well-known/oauth-protected-resource/mcp": protectedResource(oauth.issuer) },
+ callError: (params) => ({ code: -32602, message: `Bad arguments for ${(params as { name: string }).name}` }),
+ });
+ try {
+ await expect(probeMcpServer(anonymous(fake.url), 8_000, undefined, asked)).resolves.toMatchObject({ ok: true });
+ } finally {
+ await fake.close();
+ await oauth.close();
+ }
+ });
+ });
+
it("finds the protected-resource document without a www-authenticate hint", async () => {
const oauth = await startFakeOAuth();
const fake = await startFakeHttpMcp({
diff --git a/server/mcp-probe.ts b/server/mcp-probe.ts
index 745bac6069..8dd1790809 100644
--- a/server/mcp-probe.ts
+++ b/server/mcp-probe.ts
@@ -30,7 +30,9 @@ export type McpProbeResult =
export const SIGN_IN_REQUIRED = "This server needs you to sign in.";
/** A tool name no server defines, so calling it runs nothing and the answer says only whether tool calls need a sign-in.
* Observed 2026-10-31: mcp.agentcard.sh answers it HTTP 401 with `resource_metadata`; huggingface.co/mcp, whose sign-in is
- * optional and which also serves an RFC 9728 document, answers JSON-RPC -32602 "not found". */
+ * optional and which also serves an RFC 9728 document, answers JSON-RPC -32602 "not found". Observed 2026-11-09:
+ * gmailmcp.googleapis.com lists its tools to anyone and answers this name -32602 as well, but refuses every real tool with
+ * HTTP 401, so a server that answers this name is asked again with one of its own tools (`harmlessListedTool`). */
export const SIGN_IN_CHECK_TOOL = "openmausbot.sign-in-check";
const SIGN_IN_CHECK_MS = 5_000;
const DISCOVERY_MS = 5_000;
@@ -46,6 +48,9 @@ export interface McpProbeOptions {
/** Reach a URL server as a bot's turn does: at `url` with `fetch` and no headers of its own (the credential broker adds
* them, server/bot-box/broker-probe.ts). A sign-in is still looked for at the server's own address. */
via?: { url: string; fetch: typeof fetch };
+ /** Someone asked for this test: a server that answers the unknown tool may be asked once more with a real read-only tool.
+ * Background checks never call a real tool. */
+ tryReadOnlyTool?: boolean;
}
const MAX_STDOUT_BYTES = MAX_REMOTE_MCP_BYTES;
@@ -126,20 +131,41 @@ async function asksForSignIn(url: string, refusal: McpHttpError, at: RefusedAt,
return meta !== null && (at === "connect" || meta.source === "protected-resource");
}
-/** After a tools/list that carried no credentials: do tool calls need a sign-in? One call of SIGN_IN_CHECK_TOOL through
- * the same client. Only HTTP 401 behind a protected-resource document means yes. Any other answer, a timeout or a network
- * failure keeps the verdict Connected. A server that really lists that name is never called. */
-async function callsNeedSignIn(client: RemoteMcpClient, url: string, listed: unknown[], signal: AbortSignal): Promise<boolean> {
- if (listed.some((tool) => (tool as { name?: unknown } | null)?.name === SIGN_IN_CHECK_TOOL)) return false;
+/** A tool the server itself marks read-only and not destructive, and that cannot run without arguments: called with none, so
+ * a server that checks arguments before it runs anything runs nothing, and any other at worst does one read. */
+export function harmlessListedTool(listed: unknown[]): string | undefined {
+ for (const entry of listed) {
+ const tool = entry as { name?: unknown; annotations?: { readOnlyHint?: unknown; destructiveHint?: unknown }; inputSchema?: { required?: unknown } } | null;
+ if (typeof tool?.name !== "string" || !tool.name || tool.annotations?.readOnlyHint !== true || tool.annotations.destructiveHint === true) continue;
+ if (Array.isArray(tool.inputSchema?.required) && tool.inputSchema.required.length > 0) return tool.name;
+ }
+ return undefined;
+}
+
+/** `sign-in`: an HTTP 401 behind a protected-resource document. `answered`: the server replied at the MCP level, without
+ * asking who was calling. `unclear`: anything else (another status, a timeout, a network failure). */
+async function signInCheck(client: RemoteMcpClient, url: string, name: string, signal: AbortSignal): Promise<"sign-in" | "answered" | "unclear"> {
try {
- await client.request("tools/call", { name: SIGN_IN_CHECK_TOOL, arguments: {} }, AbortSignal.any([signal, AbortSignal.timeout(SIGN_IN_CHECK_MS)]));
- return false;
+ await client.request("tools/call", { name, arguments: {} }, AbortSignal.any([signal, AbortSignal.timeout(SIGN_IN_CHECK_MS)]));
+ return "answered";
} catch (error) {
- return error instanceof McpHttpError && error.kind === "status" && error.status === 401
- && await asksForSignIn(url, error, "call", signal);
+ if (error instanceof McpRpcError) return "answered";
+ return error instanceof McpHttpError && error.kind === "status" && error.status === 401 && await asksForSignIn(url, error, "call", signal) ? "sign-in" : "unclear";
}
}
+/** After a tools/list that carried no credentials: do tool calls need a sign-in? One call of SIGN_IN_CHECK_TOOL through the
+ * same client, and when the server answers that without asking who is calling and `tryReadOnly` is set, one call of a
+ * harmless tool of its own. Only HTTP 401 behind a protected-resource document means yes; any other answer, a timeout or a
+ * network failure keeps the verdict Connected. A server that really lists the check's name is never called. */
+async function callsNeedSignIn(client: RemoteMcpClient, url: string, listed: unknown[], signal: AbortSignal, tryReadOnly: boolean): Promise<boolean> {
+ if (listed.some((tool) => (tool as { name?: unknown } | null)?.name === SIGN_IN_CHECK_TOOL)) return false;
+ const unknownTool = await signInCheck(client, url, SIGN_IN_CHECK_TOOL, signal);
+ if (unknownTool !== "answered" || !tryReadOnly) return unknownTool === "sign-in";
+ const real = harmlessListedTool(listed);
+ return real !== undefined && await signInCheck(client, url, real, signal) === "sign-in";
+}
+
async function probeRemoteMcpServer(
server: StoredRemoteMcpServer,
timeoutMs: number,
@@ -159,7 +185,7 @@ async function probeRemoteMcpServer(
const tools = result && typeof result === "object" ? (result as { tools?: unknown }).tools : undefined;
if (!Array.isArray(tools)) return { ok: false, error: "The server did not return a valid MCP tools list." };
observeProbe(options, tools, client.extensions ?? "unknown");
- if (!sendsCredentials(server) && await callsNeedSignIn(client, server.url, tools, combined)) {
+ if (!sendsCredentials(server) && await callsNeedSignIn(client, server.url, tools, combined, options.tryReadOnlyTool === true)) {
return { ok: false, auth: "required", error: SIGN_IN_REQUIRED };
}
const secrets = server.oauth?.clientSecret ? { ...server.headers, "oauth.clientSecret": server.oauth.clientSecret } : server.headers;
diff --git a/server/mcp-registry.ts b/server/mcp-registry.ts
index 1ebe178b56..e6f6d8bb82 100644
--- a/server/mcp-registry.ts
+++ b/server/mcp-registry.ts
@@ -89,6 +89,9 @@ const resultBudgetSchema = z.number({ message: "The result size limit must be a
.min(0, "The result size limit cannot be negative.")
.max(MAX_RESULT_BUDGET, `The result size limit can be at most ${MAX_RESULT_BUDGET.toLocaleString("en-US")} characters; use 0 for no limit.`);
const MCP_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
+
+/** A server the request named is not saved here: its name, in the words every route answers with. */
+export const mcpServerNotFound = (name: string): string => `MCP server "${name}" not found. It may have been removed: check Apps → MCP servers.`;
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
/** An HTTP header field name: RFC 9110 token characters. */
const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/;
diff --git a/server/routes/mcp-servers.ts b/server/routes/mcp-servers.ts
index fc59868892..63defb9466 100644
--- a/server/routes/mcp-servers.ts
+++ b/server/routes/mcp-servers.ts
@@ -2,7 +2,7 @@ import { userError, userErrorFields } from "../user-errors.ts";
import { hostedWorkspaceConfiguration } from "../enterprise.ts";
import { runsElsewhere, type McpConfig, type McpConfigDeps, type McpConfigResult } from "../host/mcp-config.ts";
import { McpOAuthError, McpSignInError, mcpCallbackOrigin } from "../mcp-oauth.ts";
-import { isRemoteMcpServer, mcpServerBody, mcpServerServes, parseMcpServerMutation, parseMcpServersImport, parseStoredMcpServer, type StoredMcpServer } from "../mcp-registry.ts";
+import { isRemoteMcpServer, mcpServerBody, mcpServerNotFound, mcpServerServes, parseMcpServerMutation, parseMcpServersImport, parseStoredMcpServer, type StoredMcpServer } from "../mcp-registry.ts";
import { personKey } from "../person-key.ts";
import type { RequestAuth } from "../request-auth.ts";
import { toolBudgetOf } from "../tool-budgets.ts";
@@ -103,7 +103,7 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {
const [, name, action, flowId] = mcpSignIn;
const raw = cfg.mcpServers?.[name!];
const parsed = raw === undefined ? null : parseStoredMcpServer(name!, raw);
- if (!parsed?.ok) return json(res, 404, { error: "MCP server not found." });
+ if (!parsed?.ok) return json(res, 404, { error: mcpServerNotFound(name!) });
if (!isRemoteMcpServer(parsed.server)) return json(res, 400, { error: "Only servers reached by URL can be signed in to." });
if (parsed.server.runsOn) return json(res, 409, { error: runsElsewhere(parsed.server.runsOn) });
const url = parsed.server.url;
@@ -199,7 +199,7 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {
if (method === "DELETE") return answer(res, json, config.remove(name));
const body = await readBody(req);
const current = cfg.mcpServers ?? {};
- if (!Object.hasOwn(current, name)) return json(res, 404, { error: "MCP server not found." });
+ if (!Object.hasOwn(current, name)) return json(res, 404, { error: mcpServerNotFound(name) });
const existing = parseStoredMcpServer(name, current[name]);
if (!existing.ok) return json(res, 400, { error: existing.error });
if (method === "PATCH") {
diff --git a/server/routes/team-connections.ts b/server/routes/team-connections.ts
index 69994b2320..1c84690309 100644
--- a/server/routes/team-connections.ts
+++ b/server/routes/team-connections.ts
@@ -13,7 +13,7 @@ import type { AdminActionRow } from "../admin-activity.ts";
import type { AppConfig } from "../config.ts";
import type { TeamConnectionsHost } from "../host/team-connections-host.ts";
import { McpOAuthError, McpSignInError, mcpCallbackOrigin } from "../mcp-oauth.ts";
-import { isRemoteMcpServer, parseStoredMcpServer } from "../mcp-registry.ts";
+import { isRemoteMcpServer, mcpServerNotFound, parseStoredMcpServer } from "../mcp-registry.ts";
import { personKey } from "../person-key.ts";
import { provesSameOrigin, requestOrigin, type RequestAuth } from "../request-auth.ts";
import { APP_SLUG, appLabel, MCP_NAME, personKeyHeader } from "../team-connections.ts";
@@ -58,7 +58,7 @@ export function createTeamConnectionRoutes(deps: TeamConnectionRouteDeps): Route
}
if (kind === "mcp") {
const found = server(id);
- if (!found) return json(res, 404, { error: "MCP server not found." });
+ if (!found) return json(res, 404, { error: mcpServerNotFound(id) });
if (scope === "person" && !isRemoteMcpServer(found)) return json(res, 409, { error: "Only a server reached by its address can be connected by each person." });
}
const before = deps.host.scopes.scope(kind, id);
diff --git a/server/testing/fake-http-mcp-server.ts b/server/testing/fake-http-mcp-server.ts
index 14d31c2518..5de593d050 100644
--- a/server/testing/fake-http-mcp-server.ts
+++ b/server/testing/fake-http-mcp-server.ts
@@ -20,8 +20,9 @@ export interface FakeHttpMcpOptions {
/** WWW-Authenticate value sent with a 401 */
wwwAuthenticate?: string;
/** which requests `requireHeader`, `requireHeaders` and `acceptBearer` guard: every request (default), or only tools/call,
- * as mcp.agentcard.sh does (initialize and tools/list answer anyone) */
- guard?: "every-request" | "tools/call";
+ * as mcp.agentcard.sh does (initialize and tools/list answer anyone), or only tools/call of a tool it lists, as
+ * gmailmcp.googleapis.com does (an unknown tool name is answered -32602 before anyone is asked to sign in) */
+ guard?: "every-request" | "tools/call" | "listed-tools";
/** JSON documents served to GET at these paths of this server's own origin; a function receives the origin, for documents
* that must name it */
wellKnown?: Record<string, unknown | ((origin: string) => unknown)>;
@@ -239,9 +240,13 @@ export async function startFakeHttpMcp(options: FakeHttpMcpOptions = {}): Promis
res.writeHead(404, { "content-type": "text/plain" }).end("Not found");
return;
}
- const guardsCallsOnly = options.guard === "tools/call";
+ const guardsCallsOnly = options.guard === "tools/call" || options.guard === "listed-tools";
const body = guardsCallsOnly && req.method === "POST" ? await readBody(req) : undefined;
- const early = body === undefined ? undefined : JSON.parse(body || "{}") as { method?: unknown; params?: unknown };
+ const early = body === undefined ? undefined : JSON.parse(body || "{}") as { id?: unknown; method?: unknown; params?: { name?: unknown } };
+ if (options.guard === "listed-tools" && early?.method === "tools/call" && !(tools ?? []).some((tool) => tool.name === early.params?.name)) {
+ res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ jsonrpc: "2.0", id: early.id, error: { code: -32602, message: "Tools Call name is not found in the list of tools" } }));
+ return;
+ }
const guarded = !guardsCallsOnly || early?.method === "tools/call";
if (guarded && options.requireHeaders && Object.entries(options.requireHeaders).some(([name, value]) => req.headers[name.toLowerCase()] !== value)) {
res.writeHead(403, { "content-type": "text/plain" }).end("Forbidden");
diff --git a/shared/wire-tool.ts b/shared/wire-tool.ts
index b14001c2fb..f0fb4cfb1c 100644
--- a/shared/wire-tool.ts
+++ b/shared/wire-tool.ts
@@ -13,6 +13,8 @@ export interface WireTool extends ServerToolText {
place?: PlaceRow;
/** error rows: epoch ms when the usage limit that stopped the turn resets. */
limitResetsAt?: number;
+ /** A failed step on an MCP server, in the reader's language: which server, why, and what to do. */
+ problem?: string;
/** Provider item identity, scoped to the owning turn. */
itemId?: string;
/** Whether the harness captured the full redacted result. Private
diff --git a/src/components/ToolActivity.simple.test.ts b/src/components/ToolActivity.simple.test.ts
index 1c3a0db34b..4b6aa82cff 100644
--- a/src/components/ToolActivity.simple.test.ts
+++ b/src/components/ToolActivity.simple.test.ts
@@ -33,6 +33,20 @@ describe("ToolActivity in Simple mode", () => {
}
});
+ it("says which MCP server failed and why on the row itself, whole, in both modes, with the tool's name in the details", () => {
+ const problem = "mail needs you to sign in before its tools work. Open Apps → MCP servers and sign in to it.";
+ for (const advanced of [false, true]) {
+ mode.advanced = advanced;
+ const html = render({ name: "mcp__mail__search_threads", ok: false, problem, output: "Error dialing http://127.0.0.1:18080/b/REDACTED/mcp-mail" });
+ expect(html, `advanced ${advanced}`).toContain(`<span class="min-w-0 max-w-[30rem] leading-5 font-medium">${problem}</span>`);
+ expect(html, `advanced ${advanced}`).toMatch(/data-testid="tool-name">mcp__mail__search_threads</);
+ }
+ });
+
+ it("keeps the problem line off a step that did not fail", () => {
+ expect(render({ name: "mcp__mail__search_threads", ok: true, problem: "mail needs you to sign in." })).not.toContain("mail needs you to sign in.");
+ });
+
it("keeps a command off the row, where it reads as a plain step", () => {
const html = render({ name: "Bash", ok: false, summary: "pnpm test --filter api", input: "pnpm test --filter api" });
expect(html).toContain("Run a command · Failed · Tool details");
diff --git a/src/components/ToolActivity.tsx b/src/components/ToolActivity.tsx
index c524bcae3c..173cf20905 100644
--- a/src/components/ToolActivity.tsx
+++ b/src/components/ToolActivity.tsx
@@ -22,7 +22,8 @@ export function ToolActivity({ tool, place = null, live = false, source }: { too
const advanced = useAdvancedMode();
const notice = isNoticeCode(tool.nameCode);
const summary = routineLineText(tool.summaryCode, tool.summary ?? "", tool.summaryParams);
- const label = advanced && !notice ? tool.label ?? tool.name : toolStepLabel(tool);
+ const problem = failed ? tool.problem : undefined;
+ const label = problem ?? (advanced && !notice ? tool.label ?? tool.name : toolStepLabel(tool));
const status = tool.ok === undefined ? (live ? t("toolDetail.running") : t("toolDetail.unverified")) : failed ? t("toolDetail.failed") : t("toolDetail.completed");
return (
<details onToggle={(event) => setExpanded(event.currentTarget.open)} className="group/tool w-fit max-w-full rounded-xl border border-hairline/40 bg-panel text-[13px] open:w-[min(38rem,100%)]" data-testid="tool-activity">
@@ -34,7 +35,7 @@ export function ToolActivity({ tool, place = null, live = false, source }: { too
>
<span className="shrink-0" aria-hidden="true">{tool.ok === undefined ? (live ? <WorkingDots size={3.5} /> : <Circle size={13} />) : failed ? <X size={13} /> : <Check size={13} className="text-success" />}</span>
{place && <PlaceIcon place={place} size={13} className="shrink-0 opacity-70" role="img" aria-label={t(placeLabelKey(place))} data-testid="tool-place" />}
- <span className={cn("min-w-0 max-w-[30rem] truncate leading-5", advanced && !notice ? "font-mono" : "font-medium")}>{label}</span>
+ <span className={cn("min-w-0 max-w-[30rem]", !problem && "truncate", "leading-5", advanced && !notice && !problem ? "font-mono" : "font-medium")}>{label}</span>
{advanced && tool.summary && tool.summary !== tool.name && !nameIsCommand(tool.name) && <span className="min-w-0 flex-1 truncate font-mono" title={summary}>{summary}</span>}
<ChevronRight size={13} className="ml-auto shrink-0 group-open/tool:rotate-90" aria-hidden="true" />
</summary>
diff --git a/src/locales/de.json b/src/locales/de.json
index 7ba164c9f8..38422f3b53 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -309,6 +309,11 @@
"server.noAi.ownerLine": "{name} wollte in {team} einen Bot nutzen, aber es ist noch keine KI verbunden. Verbinde eine, damit Bots antworten können.",
"server.teammates.notPassed": "Nicht an {name} weitergegeben",
"server.mcp.reconnect.one": "Der MCP-Server {name} hat sich nicht verbunden, daher waren seine Tools diesmal nicht verfügbar. Bei deiner nächsten Nachricht verbindet er sich wieder.",
+ "server.mcp.problem.signIn": "{name} braucht deine Anmeldung, bevor seine Tools funktionieren. Öffne Apps → MCP-Server und melde dich dort an.",
+ "server.mcp.problem.refused": "{name} hat seine Anmeldung oder seinen Schlüssel abgelehnt. Öffne Apps → MCP-Server, um dich neu anzumelden oder den Schlüssel zu ändern.",
+ "server.mcp.problem.notFound": "{name} wurde unter seiner Adresse nicht gefunden. Prüfe die Adresse unter Apps → MCP-Server.",
+ "server.mcp.problem.timeout": "{name} hat nicht rechtzeitig geantwortet. Versuch es gleich noch einmal. Passiert das öfter, teste ihn unter Apps → MCP-Server.",
+ "server.mcp.problem.cantConnect": "Keine Verbindung zu {name}. Teste ihn unter Apps → MCP-Server, um zu sehen, warum.",
"server.mcp.reconnect.many": "Die MCP-Server {names} haben sich nicht verbunden, daher waren ihre Tools diesmal nicht verfügbar. Bei deiner nächsten Nachricht verbinden sie sich wieder.",
"server.bots.nameClash": "{person} ist hier auch eine Person, daher erreicht „@{name}“ {person} und nicht diesen Bot. Benenne den Bot um, damit man beide auseinanderhält.",
"star.title": "Gefällt dir {app}?",
diff --git a/src/locales/en.json b/src/locales/en.json
index 73d7a60e89..df0e4cfd02 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -444,6 +444,11 @@
"server.noAi.ownerLine": "{name} tried to use a bot in {team}, but no AI is connected yet. Connect one so bots can answer.",
"server.teammates.notPassed": "Not passed to {name}",
"server.mcp.reconnect.one": "The MCP server {name} didn't connect, so its tools weren't available this time. It connects again on your next message.",
+ "server.mcp.problem.signIn": "{name} needs you to sign in before its tools work. Open Apps → MCP servers and sign in to it.",
+ "server.mcp.problem.refused": "{name} refused its sign-in or key. Open Apps → MCP servers to sign in again or update its key.",
+ "server.mcp.problem.notFound": "{name} wasn't found at its address. Check the address in Apps → MCP servers.",
+ "server.mcp.problem.timeout": "{name} didn't answer in time. Try again in a moment, and if it keeps happening, test it in Apps → MCP servers.",
+ "server.mcp.problem.cantConnect": "Couldn't connect to {name}. Test it in Apps → MCP servers to see why.",
"server.mcp.reconnect.many": "The MCP servers {names} didn't connect, so their tools weren't available this time. They connect again on your next message.",
"server.bots.nameClash": "{person} is also a person here, so \"@{name}\" reaches {person}, not this bot. Rename the bot to keep them apart.",
"star.title": "Enjoying {app}?",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 0ebf321194..eaae453b01 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -427,6 +427,11 @@
"server.noAi.ownerLine": "{name} tentou usar um bot em {team}, mas ainda não há nenhuma IA conectada. Conecte uma para os bots poderem responder.",
"server.teammates.notPassed": "Resposta não repassada para {name}",
"server.mcp.reconnect.one": "O servidor MCP {name} não se conectou, então as ferramentas dele não estavam disponíveis desta vez. Ele se conecta novamente na sua próxima mensagem.",
+ "server.mcp.problem.signIn": "{name} precisa que você entre antes de as ferramentas dele funcionarem. Abra Apps → Servidores MCP e entre nele.",
+ "server.mcp.problem.refused": "{name} recusou o login ou a chave. Abra Apps → Servidores MCP para entrar de novo ou atualizar a chave.",
+ "server.mcp.problem.notFound": "{name} não foi encontrado no endereço dele. Confira o endereço em Apps → Servidores MCP.",
+ "server.mcp.problem.timeout": "{name} não respondeu a tempo. Tente de novo daqui a pouco e, se continuar acontecendo, teste-o em Apps → Servidores MCP.",
+ "server.mcp.problem.cantConnect": "Não foi possível conectar a {name}. Teste-o em Apps → Servidores MCP para ver o motivo.",
"server.mcp.reconnect.many": "Os servidores MCP {names} não se conectaram, então as ferramentas deles não estavam disponíveis desta vez. Eles se conectam novamente na sua próxima mensagem.",
"server.bots.nameClash": "{person} também é o nome de uma pessoa aqui, então \"@{name}\" envia a mensagem para {person}, não para este bot. Renomeie o bot para diferenciar os dois.",
"star.title": "Está gostando do app {app}?",
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 202856078f..d40cff1aa4 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -133,7 +133,7 @@ export interface Message extends Pick<import("../../shared/wire").WireMessage, "
goalRun?: GroupGoalRunCardData;
call?: import("../../shared/wire").LiveCallRecord;
channelMode?: "chat" | "goal";
- tool?: { name: string; ok?: boolean; spoken?: string; setup?: boolean; claudeUpdate?: boolean; place?: PlaceRow; limitResetsAt?: number; partial?: boolean; summary?: string; input?: string; output?: string ; itemId?: string; outputPath?: string; fullResult?: boolean; clipped?: boolean; nameCode?: string; nameParams?: Record<string, string | number>; summaryCode?: string; summaryParams?: Record<string, string | number>; rescue?: import("../../shared/first-reply-rescue").FirstReplyRescue; step?: import("../../shared/turn-progress").LiveStep; whose?: { person: string; app: string }; label?: string };
+ tool?: { name: string; ok?: boolean; spoken?: string; setup?: boolean; claudeUpdate?: boolean; place?: PlaceRow; limitResetsAt?: number; partial?: boolean; summary?: string; input?: string; output?: string ; itemId?: string; outputPath?: string; fullResult?: boolean; clipped?: boolean; nameCode?: string; nameParams?: Record<string, string | number>; summaryCode?: string; summaryParams?: Record<string, string | number>; rescue?: import("../../shared/first-reply-rescue").FirstReplyRescue; step?: import("../../shared/turn-progress").LiveStep; whose?: { person: string; app: string }; label?: string; problem?: string };
steered?: boolean;
via?: "api" | "call";
callId?: string;