Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(connectors): list the connected-apps service's own tools when discovery fails (#6992)
Milind Soni4d225552f36e
diff --git a/server/connector-discovery-fallback.ts b/server/connector-discovery-fallback.tsnew file mode 100644index 0000000000..66b7dd96ee--- /dev/null+++ b/server/connector-discovery-fallback.ts@@ -0,0 +1,70 @@+// An engine reads the connector bridge's tools/list once, when its session starts. When the connected-apps service does+// not answer then, an empty list would leave the bot only the few app tools defined here (Gmail and Calendar) for the+// whole session, with no way to reach any other connected app: it reads as "only Gmail and Calendar are connected".+// So the bridge lists the connected-apps service's own tools instead, under these short schemas. Each call is still sent+// to the service when it is made, and judged there and by the relay like any other.++const NOTE = " (The connected-apps service did not answer when this session started; if a call fails, try it again shortly.)";++/** The tools a session of the connected-apps service always offers, in the shape it takes them. */+export const DISCOVERY_FALLBACK_TOOLS: ReadonlyArray<Record<string, unknown>> = [+ {+ name: "COMPOSIO_SEARCH_TOOLS",+ description: "Find the connected-app tools for a task: Google Drive, Sheets, Docs, Slack, Notion and every other app the person connected. Returns each tool's slug and how to call it." + NOTE,+ inputSchema: {+ type: "object",+ properties: {+ queries: {+ type: "array",+ description: "One entry per task.",+ items: {+ type: "object",+ properties: {+ use_case: { type: "string", description: "The task in plain words, e.g. \"read rows from a Google Sheet\"." },+ known_fields: { type: "string", description: "Anything already known that the task needs, e.g. a spreadsheet id." },+ },+ required: ["use_case"],+ },+ },+ },+ required: ["queries"],+ },+ },+ {+ name: "COMPOSIO_GET_TOOL_SCHEMAS",+ description: "Read the full arguments of connected-app tools by their slugs, as COMPOSIO_SEARCH_TOOLS named them." + NOTE,+ inputSchema: {+ type: "object",+ properties: { tool_slugs: { type: "array", items: { type: "string" }, description: "Tool slugs, e.g. GOOGLESHEETS_BATCH_GET." } },+ required: ["tool_slugs"],+ },+ },+ {+ name: "COMPOSIO_MULTI_EXECUTE_TOOL",+ description: "Run one or more connected-app tools by slug with their arguments." + NOTE,+ inputSchema: {+ type: "object",+ properties: {+ tools: {+ type: "array",+ items: {+ type: "object",+ properties: { tool_slug: { type: "string" }, arguments: { type: "object" } },+ required: ["tool_slug", "arguments"],+ },+ },+ sync_response_to_workbench: { type: "boolean", description: "false unless the response is very large." },+ },+ required: ["tools"],+ },+ },+ {+ name: "COMPOSIO_MANAGE_CONNECTIONS",+ description: "Ask the person to connect an app that is not connected yet." + NOTE,+ inputSchema: {+ type: "object",+ properties: { toolkits: { type: "array", items: { type: "string" }, description: "App slugs, e.g. googlesheets." } },+ required: ["toolkits"],+ },+ },+];diff --git a/server/connector-proxy.test.ts b/server/connector-proxy.test.tsindex 4338c3f0c1..57b85d5eb1 100644--- a/server/connector-proxy.test.ts+++ b/server/connector-proxy.test.ts@@ -11,6 +11,8 @@ import { schemaBytes, TOOL_SCHEMA_PROFILE_ENV } from "./tool-schema-profile.ts";import { TOOL_LIMIT_ENV } from "./tool-count-limit.ts";const ENTRY = join(dirname(fileURLToPath(import.meta.url)), "connector-proxy.ts");+/** What the bridge lists when the connected-apps service does not answer discovery. */+const SERVICE_TOOLS = ["COMPOSIO_SEARCH_TOOLS", "COMPOSIO_GET_TOOL_SCHEMAS", "COMPOSIO_MULTI_EXECUTE_TOOL", "COMPOSIO_MANAGE_CONNECTIONS"];let child: ChildProcessWithoutNullStreams | null = null;let server: Server | null = null;@@ -549,7 +551,7 @@ describe("connector MCP bridge", () => {return nextJson(lines);};expect((await ask(1, "initialize")).result.serverInfo.name).toBe("openmausbot-connectors");- expect(await ask(2, "tools/list")).toEqual({ jsonrpc: "2.0", id: 2, result: { tools: [] } });+ expect((await ask(2, "tools/list")).result.tools.map((tool: { name: string }) => tool.name)).toEqual(SERVICE_TOOLS);expect(listings).toBe(2);const failedCall = await ask(3, "tools/call", { name: "GMAIL_FETCH_EMAILS", arguments: {} });expect(failedCall.result.isError).toBe(true);@@ -566,10 +568,73 @@ describe("connector MCP bridge", () => {});const lines = start({ OMB_CONNECTOR_UPSTREAM_URL: upstream });child!.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 5, method: "tools/list" })}\n`);- expect(await nextJson(lines)).toEqual({ jsonrpc: "2.0", id: 5, result: { tools: [] } });+ const reply = await nextJson(lines);+ expect(reply.id).toBe(5);+ expect(reply.result.tools.map((tool: { name: string }) => tool.name)).toEqual(SERVICE_TOOLS);expect(listings).toBe(2);});+ it("still lists the service's own tools beside the Gmail and Calendar app tools when discovery fails, and sends their calls on", async () => {+ let offline = true;+ const calls: string[] = [];+ const upstream = await listen((request, response) => {+ let body = "";+ request.on("data", (chunk) => { body += chunk; });+ request.on("end", () => {+ const rpc = JSON.parse(body);+ if (offline) {+ response.writeHead(503, { "content-type": "application/json" });+ return response.end(JSON.stringify({ error: "connected apps are busy" }));+ }+ calls.push(rpc.params?.name);+ response.writeHead(200, { "content-type": "application/json" });+ response.end(JSON.stringify({ jsonrpc: "2.0", id: rpc.id, result: { content: [{ type: "text", text: "GOOGLESHEETS_BATCH_GET" }] } }));+ });+ });+ const lines = start({+ OMB_CONNECTOR_UPSTREAM_URL: upstream,+ OMB_CONNECTOR_APP_TOOLS: JSON.stringify(["gmail.search_emails", "googlecalendar.list_events"]),+ });+ const ask = async (id: number, method: string, params = {}) => {+ child!.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);+ return nextJson(lines);+ };+ const listed = (await ask(1, "tools/list")).result.tools.map((tool: { name: string }) => tool.name);+ expect(listed).toEqual([...SERVICE_TOOLS, "gmail_search_emails", "googlecalendar_list_events"]);+ offline = false;+ const found = await ask(2, "tools/call", { name: "COMPOSIO_SEARCH_TOOLS", arguments: { queries: [{ use_case: "read a Google Sheet" }] } });+ expect(found.result.content[0].text).toBe("GOOGLESHEETS_BATCH_GET");+ expect(calls).toEqual(["COMPOSIO_SEARCH_TOOLS"]);+ });++ it.each([+ ["an HTTP refusal", 403, { error: "connected apps are not enabled for this bot" }],+ ["a refusal answered as a result", 200, { jsonrpc: "2.0", id: 8, result: { content: [{ type: "text", text: "Only the member's own turn may use this." }], isError: true } }],+ ])("lists nothing, once, after %s of the tool list", async (_case, status, body) => {+ let listings = 0;+ const upstream = await listen((request, response) => {+ request.resume();+ listings += 1;+ response.writeHead(status, { "content-type": "application/json" });+ response.end(JSON.stringify(body));+ });+ const lines = start({ OMB_CONNECTOR_UPSTREAM_URL: upstream });+ child!.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 8, method: "tools/list" })}\n`);+ expect(await nextJson(lines)).toEqual({ jsonrpc: "2.0", id: 8, result: { tools: [] } });+ expect(listings).toBe(1);+ });++ it("keeps a bot's grants on the service's own tools listed during a discovery outage", async () => {+ const upstream = await listen((request, response) => {+ request.resume();+ response.writeHead(500);+ response.end();+ });+ const lines = start({ OMB_CONNECTOR_UPSTREAM_URL: upstream, OMB_CONNECTOR_ALLOWED_TOOLS: "{}" });+ child!.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 7, method: "tools/list" })}\n`);+ expect((await nextJson(lines)).result.tools.map((tool: { name: string }) => tool.name)).toEqual(["COMPOSIO_MANAGE_CONNECTIONS"]);+ });+it("keeps locally defined app tools available during a discovery outage", async () => {const lines = start({ OMB_CONNECTOR_UPSTREAM_URL: "", OMB_CONNECTOR_APP_TOOLS: JSON.stringify(["gmail.search_emails"]) });child!.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 6, method: "tools/list" })}\n`);diff --git a/server/connector-proxy.ts b/server/connector-proxy.tsindex 93f0744855..f1cb3ca801 100644--- a/server/connector-proxy.ts+++ b/server/connector-proxy.ts@@ -12,6 +12,7 @@ import {withConnectionParameters,} from "./connector-advertisement.ts";import { APP_TOOL_NAMES_ENV, APP_TOOLS_ENV, appToolAnswer, appToolCall, appToolEntries, parseAppToolsEnv } from "./connector-app-tools.ts";+import { DISCOVERY_FALLBACK_TOOLS } from "./connector-discovery-fallback.ts";import { ARGUMENT_REFUSAL, argumentRefusalNote, fitArguments, fittedArgumentsNote, preservesNumericText } from "./connector-arguments.ts";import { annotateFailedCall } from "./connector-scope-hint.ts";import { withSignedOutHint } from "./connector-signed-out-hint.ts";@@ -134,7 +135,7 @@ async function relay(message: Json, timeoutMs = RELAY_TIMEOUT_MS): Promise<Json});const nextSession = response.headers.get("mcp-session-id");if (nextSession) upstreamSessionId = nextSession;- if (!response.ok) throw new Error(`connector service returned HTTP ${response.status}`);+ if (!response.ok) throw Object.assign(new Error(`connector service returned HTTP ${response.status}`), { status: response.status });return parseUpstream(await readBounded(response), message.id);}@@ -270,17 +271,32 @@ function fittedList(frame: Json): Json {return { ...frame, result: capToolListResult(fitToolListResult(frame.result, SCHEMA_PROFILE, log), TOOL_LIMIT, log) };}+/** A refusal that answers the same way every time: an HTTP 4xx other than 429, or a result that is not a list (the+ * harness's own refusal of this bot). A timeout, a dropped connection, a 5xx, a 429, a JSON-RPC error or a reply that+ * cannot be read is an outage. */+function refusedListing(failure: { status?: number } | Json | null): boolean {+ if (failure && "status" in failure && typeof failure.status === "number") return failure.status < 500 && failure.status !== 429;+ return Boolean(failure && "result" in failure && !("error" in failure));+}+async function listTools(message: Json): Promise<Json> {+ let refused = false;for (let attempt = 0; attempt < 2; attempt += 1) {if (attempt) await delay(TOOLS_LIST_RETRY_MS);try {const response = await relay(message, TOOLS_LIST_RELAY_TIMEOUT_MS);if (response && !response.error && Array.isArray((response.result as Json | undefined)?.tools)) return response;- } catch {+ refused = refusedListing(response);+ } catch (error) {+ refused = refusedListing(error as { status?: number });}+ if (refused) break;}- process.stderr.write("connector-proxy: Connected apps are temporarily unavailable; start a new session to retry discovery.\n");- return { jsonrpc: "2.0", id: message.id, result: { tools: [] } };+ process.stderr.write(refused+ ? "connector-proxy: Connected apps refused this bot's tool list.\n"+ : "connector-proxy: Connected apps are temporarily unavailable; start a new session to retry discovery.\n");+ // In an outage, with a service to send calls to, its own tools still go on the list: calls reach it once it answers again.+ return { jsonrpc: "2.0", id: message.id, result: { tools: UPSTREAM && !refused ? structuredClone(DISCOVERY_FALLBACK_TOOLS) : [] } };}async function handle(received: Json): Promise<void> {