Skip to content

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

fix(apps): a bot's connected apps answer by the same names on every engine (#3755)

Milind Sonidae71a150b10
diff --git a/docs/composio.md b/docs/composio.md
index 3d17d44fdd..f0c54ce23c 100644
--- a/docs/composio.md
+++ b/docs/composio.md
@@ -193,10 +193,12 @@ The workspace-level connections above say which accounts exist. A second, per-bo
A bot with no grant record at all keeps the legacy behavior: every tool on every connected app it can see. Assigning the first grant switches the bot to exact-tool mode — a service not on the list grants nothing, even when the workspace is connected to it.
-**Nothing changes until you assign.** Upgrading OpenMausBot does not alter any bot's access: existing bots keep the all-tools default until someone edits their grants. An emptied grant list is deliberate and means "no tools on any connected app."
+**Nothing changes until you assign.** Upgrading OpenMausBot does not alter any bot's access: existing bots keep the all-tools default until someone edits their grants. An emptied grant list is deliberate and means "no tools on any connected app." The one exception is an app a bot's **Apps** switch turns on (its read or write level) that its tool list leaves out: that app gets all of its tools, so a switch that shows an app on always lets the bot use it.
**Imported bots land with no grants.** Shareable packages and team imports never carry grants — an imported bot starts with connected apps off, and any grants it later gets are chosen by the importing workspace. Grants also never appear in exports; only the workspace's own private team backup keeps them.
**A Chief's new bots start with the Chief's apps.** A bot a Chief of Staff creates (`create_bot`, or a team setup) starts with a copy of the Chief's own connected apps, tools, read or write levels and MCP servers at that moment, never more, and the workspace's default access level. It has the Chief's owner and exactly the Chief's audience; on a Team Cloud, an app each person connects still works only in each person's own private chat, with their own connection. A bot a person creates keeps the defaults above.
+**Gmail and Google Calendar by name.** Besides Composio's search-and-run tools, a bot with Gmail or Google Calendar connected and granted gets plain tools for the common reads and writes, the same on every engine: `gmail.search_emails`, `gmail.read_email`, `gmail.read_email_thread`, `gmail.create_draft`, `gmail.send_email`, `googlecalendar.list_events` and `googlecalendar.list_calendars` (writes only where the bot may write). Claude Code finds them by those names (`select:gmail.search_emails`); other engines show them as `gmail_search_emails` behind their own prefix. Each one runs its Composio tool through the multi-execute tool, so its grant, read or write level and approval rules are that tool's. A routine written on one engine keeps working when its bot moves to another.
+
Grants are enforced on the real tool names at call time (including batches inside the MULTI_EXECUTE meta-tool), the tool list offered to the model is filtered to the granted set, and every allow/deny writes a decision-log row. Refusals do not enumerate what else is granted. Paired phones see each bot's grants read-only in its profile (What this bot does → App tools); grants are assigned on the computer, never from a phone.
diff --git a/scripts/control-omb.ts b/scripts/control-omb.ts
index 69535a9ab8..b3f6833fc1 100644
--- a/scripts/control-omb.ts
+++ b/scripts/control-omb.ts
@@ -165,7 +165,7 @@ export function verificationServerEnvironment(parentEnv: NodeJS.ProcessEnv, data
// The fake engines' knobs are the one thing a caller may script into the child.
for (const [key, value] of Object.entries(parentEnv)) {
// FAKE_CLAUDE_DUMP stays the launcher's: assertions read fixtureDumpPath.
- if ((key.startsWith("FAKE_CLAUDE_") || key.startsWith("FAKE_CODEX_TEXT_") || key.startsWith("FAKE_CODEX_COMMAND")) && key !== "FAKE_CLAUDE_DUMP" && value) childEnv[key] = value;
+ if ((key.startsWith("FAKE_CLAUDE_") || key.startsWith("FAKE_CODEX_TEXT_") || key.startsWith("FAKE_CODEX_COMMAND") || key === "FAKE_ACP_HANG_ON") && key !== "FAKE_CLAUDE_DUMP" && value) childEnv[key] = value;
}
// Enables POST /api/testing/org-library; the route does not exist without it.
if (parentEnv.OMB_TEST_ORG_LIBRARY_KEY) childEnv.OMB_TEST_ORG_LIBRARY_KEY = parentEnv.OMB_TEST_ORG_LIBRARY_KEY;
diff --git a/server/connected-app-tools.e2e.test.ts b/server/connected-app-tools.e2e.test.ts
new file mode 100644
index 0000000000..0c5b2f5d6c
--- /dev/null
+++ b/server/connected-app-tools.e2e.test.ts
@@ -0,0 +1,94 @@
+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { createInterface } from "node:readline";
+import { expect, it } from "vitest";
+
+import { launchVerificationServer } from "../scripts/control-omb.ts";
+import { startFakeConnectedApps } from "./testing/fake-connected-apps.ts";
+
+type Bridge = { command: string; args: string[]; env: Record<string, string> };
+
+/** Starts a mounted connected-apps bridge the way the engine would and asks it for its tools and one call. */
+async function ask(bridge: Bridge, call: { name: string; arguments: Record<string, unknown> }) {
+ const child: ChildProcessWithoutNullStreams = spawn(bridge.command, [...(bridge.command === process.execPath ? ["--experimental-strip-types", "--no-warnings"] : []), ...bridge.args], {
+ env: { ...process.env, ...bridge.env }, stdio: "pipe",
+ });
+ const lines = createInterface({ input: child.stdout })[Symbol.asyncIterator]();
+ const request = async (id: number, method: string, params?: unknown) => {
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, ...(params ? { params } : {}) })}\n`);
+ return JSON.parse((await lines.next()).value as string);
+ };
+ try {
+ await request(1, "initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "engine", version: "1" } });
+ const listed = await request(2, "tools/list");
+ if (!listed.result) throw new Error(`tools/list: ${JSON.stringify(listed).slice(0, 500)} via ${bridge.command} ${bridge.args.join(" ")}`);
+ const names: string[] = listed.result.tools.map((tool: { name: string }) => tool.name);
+ const answer = await request(3, "tools/call", call);
+ return { names, answer };
+ } finally {
+ child.kill("SIGKILL");
+ }
+}
+
+const acpBridge = (entry: { command: string; args: string[]; env: Array<{ name: string; value: string }> }): Bridge =>
+ ({ command: entry.command, args: entry.args, env: Object.fromEntries(entry.env.map(({ name, value }) => [name, value])) });
+
+it("a bot given Gmail by its app switch reaches gmail.search_emails by name on Claude and on an ACP engine alike", async () => {
+ const apps = await startFakeConnectedApps();
+ apps.emails.push({ messageId: "m-ada", threadId: "t-ada", messageTimestamp: new Date().toISOString(), subject: "Q3 numbers", sender: "Ada <[email protected]>", preview: { body: "Here they are" } });
+ const scratch = mkdtempSync(join(tmpdir(), "omb-app-tools-"));
+ const gate = join(scratch, "finish");
+ const fixture = await launchVerificationServer({
+ ...process.env, OMB_COMPOSIO_BROKER_URL: apps.url, OMB_COMPOSIO_BROKER_TOKEN: apps.token,
+ FAKE_CLAUDE_MODE: "slow", FAKE_CLAUDE_SLOW_FINISH_GATE: gate, FAKE_ACP_HANG_ON: "Find Ada's mail again",
+ }, undefined, undefined, undefined, undefined, undefined, ["cline"]);
+ const api = async (method: string, path: string, body?: unknown, expected = 200) => {
+ const response = await fetch(fixture.info.url + path, {
+ method, headers: { "content-type": "application/json", origin: fixture.info.url },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ const result = await response.json() as any;
+ expect(response.status, `${method} ${path}: ${JSON.stringify(result).slice(0, 400)}`).toBe(expected);
+ return result;
+ };
+ try {
+ const bot = (await api("POST", "/api/bots", { name: "Paul" }, 201)).bot;
+ // The record an Apps switch left before it also wrote the tool list: Gmail on by scope, no tool granted.
+ await api("PATCH", `/api/bots/${bot.id}`, { composio: true, connectorTools: {}, connectorScopes: { apps: { gmail: "read", googlecalendar: "read" } } });
+ const saved = JSON.parse(readFileSync(join(fixture.info.dataDir, "bots.json"), "utf8")).find((row: any) => row.id === bot.id);
+ expect(saved.connectorTools).toEqual({ gmail: { tools: "*" }, googlecalendar: { tools: "*" } });
+
+ const send = async (text: string, sendId: string) => api("POST", `/api/bots/${bot.id}/messages`, { threadId: bot.threadId, text, sendId }, 202);
+ await send("Find Ada's mail", "app-tools-e2e-send-0001");
+ let claudeDump: any;
+ await expect.poll(() => {
+ try { claudeDump = JSON.parse(readFileSync(fixture.fixtureDumpPath, "utf8")); } catch { return false; }
+ return Boolean(claudeDump.mcpConfig?.mcpServers?.composio);
+ }, { timeout: 20_000 }).toBe(true);
+ const onClaude = await ask(claudeDump.mcpConfig.mcpServers.composio, { name: "gmail.search_emails", arguments: { query: "from:[email protected]" } });
+ expect(onClaude.names).toEqual(expect.arrayContaining(["gmail.search_emails", "gmail.read_email", "gmail.read_email_thread", "googlecalendar.list_events"]));
+ expect(onClaude.names, "a read-only app offers no tool that writes").not.toContain("gmail.send_email");
+ expect(JSON.parse(onClaude.answer.result.content[0].text).messages[0]).toMatchObject({ messageId: "m-ada", subject: "Q3 numbers" });
+ expect(apps.calls.at(-1)).toMatchObject({ tool: "GMAIL_FETCH_EMAILS", arguments: { user_id: "me", query: "from:[email protected]" } });
+ writeFileSync(gate, "");
+ await expect.poll(async () => (await api("GET", `/api/threads/${bot.threadId}/messages`)).messages
+ .some((message: any) => message.role === "bot" && String(message.text).startsWith("reply to:")), { timeout: 20_000 }).toBe(true);
+
+ await api("PATCH", `/api/bots/${bot.id}`, { modelSelection: { instanceId: "cline", model: "cline-default" } });
+ await send("Find Ada's mail again", "app-tools-e2e-send-0002");
+ const mounts = `${join(fixture.info.dataDir, "cline-launch.json")}.mcp.json`;
+ await expect.poll(() => existsSync(mounts), { timeout: 20_000 }).toBe(true);
+ const composio = (JSON.parse(readFileSync(mounts, "utf8")) as any[]).find((entry) => entry.name === "composio");
+ const onAcp = await ask(acpBridge(composio), { name: "gmail_search_emails", arguments: { query: "from:[email protected]" } });
+ const plain = (names: string[]) => names.filter((name) => /^(gmail|googlecalendar)[._]/.test(name)).map((name) => name.replace(".", "_")).sort();
+ expect(plain(onAcp.names), "the same tools under the same names").toEqual(plain(onClaude.names));
+ expect(onAcp.names).toContain("gmail_search_emails");
+ expect(JSON.parse(onAcp.answer.result.content[0].text).messages[0]).toMatchObject({ messageId: "m-ada" });
+ } finally {
+ await fixture.close();
+ await apps.close();
+ rmSync(scratch, { recursive: true, force: true });
+ }
+}, 120_000);
diff --git a/server/connector-app-tools.test.ts b/server/connector-app-tools.test.ts
new file mode 100644
index 0000000000..ce3cd52922
--- /dev/null
+++ b/server/connector-app-tools.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from "vitest";
+
+import { APP_TOOLS, appToolAnswer, appToolCall, appToolEntries, appToolsFor } from "./connector-app-tools.ts";
+
+const CONNECTED = ["gmail", "googlecalendar", "github"];
+const READS = ["gmail.search_emails", "gmail.read_email", "gmail.read_email_thread", "googlecalendar.list_events", "googlecalendar.list_calendars"];
+
+describe("the connected-app tools a bot gets", () => {
+ it("are its connected apps' tools, and only the reads of an app it may only read", () => {
+ expect(appToolsFor({}, CONNECTED)).toEqual(APP_TOOLS.map((tool) => tool.name));
+ expect(appToolsFor({ connectorScopes: { apps: { gmail: "read", googlecalendar: "read" } }, connectorTools: { gmail: { tools: "*" }, googlecalendar: { tools: "*" } } }, CONNECTED)).toEqual(READS);
+ expect(appToolsFor({ connectorScopes: { apps: { gmail: "write" } }, connectorTools: { gmail: { tools: "*" } } }, CONNECTED))
+ .toEqual(["gmail.search_emails", "gmail.read_email", "gmail.read_email_thread", "gmail.create_draft", "gmail.send_email"]);
+ });
+
+ it("never offers an app that is not connected, not granted, or granted other tools only", () => {
+ expect(appToolsFor({}, ["github"])).toEqual([]);
+ expect(appToolsFor({ connectorTools: {} }, CONNECTED)).toEqual([]);
+ expect(appToolsFor({ connectorTools: { gmail: { tools: ["GMAIL_FETCH_EMAILS"] } } }, CONNECTED)).toEqual(["gmail.search_emails"]);
+ expect(appToolsFor({ connectorScopes: { apps: {} } }, CONNECTED)).toEqual([]);
+ });
+});
+
+describe("how an engine sees them", () => {
+ it("lists them under the dotted names for an engine that finds tools by their own name, and with an underscore elsewhere", () => {
+ expect(appToolEntries(["gmail.search_emails"], "dotted").map((entry) => entry.name)).toEqual(["gmail.search_emails"]);
+ expect(appToolEntries(READS, "plain").map((entry) => entry.name)).toEqual(["gmail_search_emails", "gmail_read_email", "gmail_read_email_thread", "googlecalendar_list_events", "googlecalendar_list_calendars"]);
+ });
+
+ it("keeps every schema one flat object, the shape every engine's converter keeps", () => {
+ const serialized = JSON.stringify(appToolEntries(APP_TOOLS.map((tool) => tool.name), "plain"));
+ expect(serialized).not.toMatch(/"(oneOf|anyOf|allOf|const|format)"/);
+ for (const entry of appToolEntries(APP_TOOLS.map((tool) => tool.name), "plain")) {
+ expect(entry.inputSchema).toMatchObject({ type: "object", additionalProperties: false });
+ expect(String(entry.description).length).toBeLessThan(500);
+ }
+ });
+});
+
+describe("a call to one", () => {
+ it("runs its Composio tool through the multi-execute tool, by either name, with the arguments it takes", () => {
+ const call = appToolCall("gmail.search_emails", { query: "from:[email protected]", max_results: "5" });
+ expect(call?.slug).toBe("GMAIL_FETCH_EMAILS");
+ expect(call?.frame(9)).toEqual({ jsonrpc: "2.0", id: 9, method: "tools/call", params: { name: "COMPOSIO_MULTI_EXECUTE_TOOL", arguments: { tools: [{
+ tool_slug: "GMAIL_FETCH_EMAILS", arguments: { user_id: "me", query: "from:[email protected]", max_results: 5, include_payload: false, verbose: false },
+ }] } } });
+ expect(appToolCall("GMAIL_READ_EMAIL_THREAD", { thread_id: "t1" })?.frame(1)).toMatchObject({ params: { arguments: { tools: [{ tool_slug: "GMAIL_FETCH_MESSAGE_BY_THREAD_ID", arguments: { user_id: "me", thread_id: "t1" } }] } } });
+ expect(appToolCall("gmail_send_email", { to: "[email protected], [email protected]", subject: "Hi", body: "Hello" })?.frame(1))
+ .toMatchObject({ params: { arguments: { tools: [{ tool_slug: "GMAIL_SEND_EMAIL", arguments: { recipient_email: "[email protected]", extra_recipients: ["[email protected]"], subject: "Hi", body: "Hello" } }] } } });
+ expect(appToolCall("COMPOSIO_SEARCH_TOOLS", {})).toBeNull();
+ });
+
+ it("answers with the tool's own data, and passes a refusal or failure through as it came", () => {
+ const ok = { jsonrpc: "2.0", id: 1, result: { content: [{ type: "text", text: JSON.stringify({ successful: true, data: { results: [{ tool_slug: "GMAIL_FETCH_EMAILS", response: { successful: true, data: { messages: [{ messageId: "m1" }] } } }] } }) }] } };
+ expect(appToolAnswer("GMAIL_FETCH_EMAILS", ok)).toEqual({ jsonrpc: "2.0", id: 1, result: { content: [{ type: "text", text: JSON.stringify({ messages: [{ messageId: "m1" }] }) }] } });
+ const refused = { jsonrpc: "2.0", id: 1, result: { isError: true, content: [{ type: "text", text: "\"GMAIL_SEND_EMAIL\" is not granted to this bot. This call was not performed." }] } };
+ expect(appToolAnswer("GMAIL_SEND_EMAIL", refused)).toBe(refused);
+ });
+});
diff --git a/server/connector-app-tools.ts b/server/connector-app-tools.ts
new file mode 100644
index 0000000000..e039d0425d
--- /dev/null
+++ b/server/connector-app-tools.ts
@@ -0,0 +1,200 @@
+// The connected-app actions bots reach for most, under plain names that are the same on every engine: gmail.search_emails,
+// gmail.read_email_thread, googlecalendar.list_events. Each runs one Composio tool through COMPOSIO_MULTI_EXECUTE_TOOL,
+// so the relay judges it exactly as that tool: its grant, the bot's read or write scope, approval cards.
+import { isReadOnlyAction, type ConnectorScopes } from "../shared/connector-scopes.ts";
+import type { ConnectorToolGrant } from "../shared/wire.ts";
+import { toolData } from "./connected-reads.ts";
+
+/** JSON list of the app tools a bridge offers, by their dotted names. */
+export const APP_TOOLS_ENV = "OMB_CONNECTOR_APP_TOOLS";
+/** "dotted": offer `gmail.search_emails` itself. Claude Code's tool search finds an MCP tool by its own name, and Claude
+ * Code turns the dot into `_` in the name it sends; other engines get `gmail_search_emails`, since some providers refuse a
+ * dot in a tool name, and they show the same name either way. */
+export const APP_TOOL_NAMES_ENV = "OMB_CONNECTOR_APP_TOOL_NAMES";
+const MULTI_EXECUTE = "COMPOSIO_MULTI_EXECUTE_TOOL";
+
+type Input = Record<string, unknown>;
+interface AppTool {
+ name: string;
+ slug: string;
+ description: string;
+ properties: Record<string, Record<string, unknown>>;
+ required?: string[];
+ args(input: Input): Record<string, unknown>;
+}
+
+const text = (value: unknown): string | undefined => (typeof value === "string" && value.trim() ? value.trim() : typeof value === "number" ? String(value) : undefined);
+const count = (value: unknown, fallback: number, max: number): number => {
+ const n = typeof value === "string" ? Number.parseInt(value, 10) : Number(value);
+ return Number.isFinite(n) && n >= 1 ? Math.min(Math.floor(n), max) : fallback;
+};
+const addresses = (value: unknown): string[] | undefined => {
+ const list = Array.isArray(value) ? value : typeof value === "string" ? value.split(/[,;]/) : [];
+ const out = list.map((item) => String(item).trim()).filter(Boolean);
+ return out.length ? out : undefined;
+};
+const when = (value: unknown): string | undefined => {
+ const raw = text(value);
+ if (!raw) return undefined;
+ const at = Date.parse(raw);
+ return Number.isFinite(at) ? new Date(at).toISOString() : raw;
+};
+
+export const APP_TOOLS: readonly AppTool[] = [
+ {
+ name: "gmail.search_emails",
+ slug: "GMAIL_FETCH_EMAILS",
+ description: "Search the person's Gmail. query takes Gmail search words (from:[email protected], subject:invoice, is:unread, newer_than:7d, after:2026/10/01, in:inbox); leave it out for the newest mail. Returns each message's id, thread id, sender, subject, date and a preview. Read one with gmail.read_email, or its whole conversation with gmail.read_email_thread.",
+ properties: {
+ query: { type: "string", description: "Gmail search, e.g. \"from:[email protected] newer_than:7d\"." },
+ max_results: { type: "integer", minimum: 1, maximum: 50, description: "How many messages, 1 to 50. Default 10." },
+ page_token: { type: "string", description: "The nextPageToken of an earlier search, for the next page." },
+ },
+ args: (input) => ({
+ user_id: "me", query: text(input.query ?? input.q) ?? "", max_results: count(input.max_results ?? input.limit, 10, 50),
+ include_payload: false, verbose: false, ...(text(input.page_token) ? { page_token: text(input.page_token) } : {}),
+ }),
+ },
+ {
+ name: "gmail.read_email",
+ slug: "GMAIL_FETCH_MESSAGE_BY_MESSAGE_ID",
+ description: "Read one Gmail message in full: headers, text and attachment names. message_id comes from gmail.search_emails.",
+ properties: { message_id: { type: "string", description: "The message id." } },
+ required: ["message_id"],
+ args: (input) => ({ user_id: "me", message_id: text(input.message_id ?? input.id) ?? "", format: "full" }),
+ },
+ {
+ name: "gmail.read_email_thread",
+ slug: "GMAIL_FETCH_MESSAGE_BY_THREAD_ID",
+ description: "Read a whole Gmail conversation, every message in it. thread_id comes from gmail.search_emails.",
+ properties: { thread_id: { type: "string", description: "The thread id." } },
+ required: ["thread_id"],
+ args: (input) => ({ user_id: "me", thread_id: text(input.thread_id ?? input.id) ?? "" }),
+ },
+ {
+ name: "gmail.create_draft",
+ slug: "GMAIL_CREATE_EMAIL_DRAFT",
+ description: "Save an email as a draft in the person's Gmail without sending it. Give thread_id to draft a reply in that conversation.",
+ properties: {
+ to: { type: "string", description: "The recipient's address; several separated by commas." },
+ subject: { type: "string" },
+ body: { type: "string", description: "The text of the email." },
+ thread_id: { type: "string", description: "For a reply: the conversation's thread id." },
+ },
+ required: ["to", "body"],
+ args: (input) => {
+ const [first, ...rest] = addresses(input.to ?? input.recipient_email) ?? [];
+ return {
+ user_id: "me", recipient_email: first ?? "", body: String(input.body ?? ""), subject: String(input.subject ?? ""),
+ ...(rest.length ? { extra_recipients: rest } : {}), ...(text(input.thread_id) ? { thread_id: text(input.thread_id) } : {}),
+ };
+ },
+ },
+ {
+ name: "gmail.send_email",
+ slug: "GMAIL_SEND_EMAIL",
+ description: "Send an email from the person's Gmail.",
+ properties: {
+ to: { type: "string", description: "The recipient's address; several separated by commas." },
+ subject: { type: "string" },
+ body: { type: "string", description: "The text of the email." },
+ cc: { type: "string", description: "Addresses to copy, separated by commas." },
+ },
+ required: ["to", "subject", "body"],
+ args: (input) => {
+ const [first, ...rest] = addresses(input.to ?? input.recipient_email) ?? [];
+ const cc = addresses(input.cc);
+ return {
+ user_id: "me", recipient_email: first ?? "", subject: String(input.subject ?? ""), body: String(input.body ?? ""),
+ ...(rest.length ? { extra_recipients: rest } : {}), ...(cc ? { cc } : {}),
+ };
+ },
+ },
+ {
+ name: "googlecalendar.list_events",
+ slug: "GOOGLECALENDAR_EVENTS_LIST",
+ description: "List the events on the person's Google Calendar between two times, earliest first. Times are ISO 8601, e.g. 2026-10-28T09:00:00+01:00.",
+ properties: {
+ time_min: { type: "string", description: "Start of the window. Default now." },
+ time_max: { type: "string", description: "End of the window." },
+ calendar_id: { type: "string", description: "A calendar id from googlecalendar.list_calendars. Default the primary calendar." },
+ max_results: { type: "integer", minimum: 1, maximum: 250, description: "Default 50." },
+ },
+ args: (input) => ({
+ calendarId: text(input.calendar_id ?? input.calendarId) ?? "primary", timeMin: when(input.time_min ?? input.timeMin) ?? new Date().toISOString(),
+ ...(when(input.time_max ?? input.timeMax) ? { timeMax: when(input.time_max ?? input.timeMax) } : {}),
+ singleEvents: true, orderBy: "startTime", maxResults: count(input.max_results, 50, 250),
+ }),
+ },
+ {
+ name: "googlecalendar.list_calendars",
+ slug: "GOOGLECALENDAR_LIST_CALENDARS",
+ description: "List the person's Google calendars, with each one's id.",
+ properties: {},
+ args: () => ({}),
+ },
+];
+
+/** The app tool names in a bridge's environment; anything else reads as none. */
+export function parseAppToolsEnv(raw: string | undefined): string[] {
+ if (!raw) return [];
+ try {
+ const value: unknown = JSON.parse(raw);
+ return Array.isArray(value) ? value.filter((name): name is string => typeof name === "string" && APP_TOOLS.some((tool) => tool.name === name)) : [];
+ } catch {
+ return [];
+ }
+}
+
+const BY_NAME = new Map(APP_TOOLS.flatMap((tool) => [[tool.name, tool], [plainName(tool.name), tool]] as const));
+
+function plainName(name: string): string {
+ return name.replace(".", "_");
+}
+
+const appOf = (tool: AppTool) => tool.name.slice(0, tool.name.indexOf("."));
+
+/** The app tools a bot gets: those of its connected apps whose tool its grants allow, and only reads where it may only read. */
+export function appToolsFor(bot: { connectorTools?: Record<string, ConnectorToolGrant>; connectorScopes?: ConnectorScopes }, connected: readonly string[]): string[] {
+ return APP_TOOLS.filter((tool) => {
+ const app = appOf(tool);
+ if (!connected.includes(app)) return false;
+ const grant = bot.connectorTools === undefined ? { tools: "*" as const } : Object.hasOwn(bot.connectorTools, app) ? bot.connectorTools[app] : undefined;
+ if (!grant || (grant.tools !== "*" && !grant.tools.includes(tool.slug))) return false;
+ if (!bot.connectorScopes) return true;
+ const scope = Object.hasOwn(bot.connectorScopes.apps, app) ? bot.connectorScopes.apps[app] : undefined;
+ return scope === "write" || (scope === "read" && isReadOnlyAction(tool.slug, app));
+ }).map((tool) => tool.name);
+}
+
+/** The tools/list entries for `names`, as the bridge offers them. */
+export function appToolEntries(names: readonly string[], style: "dotted" | "plain"): Array<Record<string, unknown>> {
+ return APP_TOOLS.filter((tool) => names.includes(tool.name)).map((tool) => ({
+ name: style === "dotted" ? tool.name : plainName(tool.name),
+ description: tool.description,
+ inputSchema: { type: "object", additionalProperties: false, properties: tool.properties, ...(tool.required ? { required: tool.required } : {}) },
+ annotations: { readOnlyHint: isReadOnlyAction(tool.slug, appOf(tool)) },
+ }));
+}
+
+/** The Composio call an app tool's call stands for, by either spelling of its name, or null for any other tool. */
+export function appToolCall(name: string, input: unknown): { slug: string; frame(id: unknown): Record<string, unknown> } | null {
+ const tool = BY_NAME.get(name.trim().toLowerCase());
+ if (!tool) return null;
+ const args = tool.args(input && typeof input === "object" && !Array.isArray(input) ? input as Input : {});
+ return {
+ slug: tool.slug,
+ frame: (id) => ({ jsonrpc: "2.0", id, method: "tools/call", params: { name: MULTI_EXECUTE, arguments: { tools: [{ tool_slug: tool.slug, arguments: args }] } } }),
+ };
+}
+
+/** The app tool's answer: the one tool's data, or the relay's frame as it came when that cannot be read (a refusal, an error). */
+export function appToolAnswer(slug: string, frame: Record<string, unknown>): Record<string, unknown> {
+ let data: unknown;
+ try {
+ data = toolData(slug, frame);
+ } catch {
+ return frame;
+ }
+ return { ...frame, result: { content: [{ type: "text", text: JSON.stringify(data) }] } };
+}
diff --git a/server/connector-proxy.test.ts b/server/connector-proxy.test.ts
index e5f4a798de..2fb50a7214 100644
--- a/server/connector-proxy.test.ts
+++ b/server/connector-proxy.test.ts
@@ -509,3 +509,45 @@ describe("connector MCP bridge", () => {
}
});
});
+describe("connected-app tools by name", () => {
+ const upstreamFor = (calls: any[]) => listen((request, response) => {
+ let body = "";
+ request.on("data", (chunk) => { body += chunk; });
+ request.on("end", () => {
+ const frame = JSON.parse(body);
+ calls.push(frame);
+ response.writeHead(200, { "content-type": "application/json" });
+ if (frame.method === "tools/list") {
+ response.end(JSON.stringify({ jsonrpc: "2.0", id: frame.id, result: { tools: [{ name: "COMPOSIO_MULTI_EXECUTE_TOOL", description: "Run app tools", inputSchema: { type: "object" } }] } }));
+ return;
+ }
+ const slug = frame.params?.arguments?.tools?.[0]?.tool_slug;
+ const text = JSON.stringify({ successful: true, data: { results: [{ tool_slug: slug, response: { successful: true, data: { messages: [{ messageId: "m1", subject: "Q3" }] } } }] } });
+ response.end(JSON.stringify({ jsonrpc: "2.0", id: frame.id, result: { content: [{ type: "text", text }] } }));
+ });
+ });
+
+ it("lists the app tools after the upstream's, under the spelling the engine asked for", async () => {
+ for (const [style, names] of [["dotted", ["gmail.search_emails", "gmail.read_email_thread"]], ["", ["gmail_search_emails", "gmail_read_email_thread"]]] as const) {
+ const upstream = await upstreamFor([]);
+ const lines = start({ OMB_CONNECTOR_UPSTREAM_URL: upstream, OMB_CONNECTOR_APP_TOOLS: JSON.stringify(["gmail.search_emails", "gmail.read_email_thread", "not.a_tool"]), ...(style ? { OMB_CONNECTOR_APP_TOOL_NAMES: style } : {}) });
+ child!.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" })}\n`);
+ const listed = await nextJson(lines);
+ expect(listed.result.tools.map((tool: { name: string }) => tool.name)).toEqual(["COMPOSIO_MULTI_EXECUTE_TOOL", ...names]);
+ expect(listed.result.tools[1].annotations).toEqual({ readOnlyHint: true });
+ child!.kill("SIGKILL");
+ await new Promise<void>((resolve) => server!.close(() => resolve()));
+ server = null;
+ }
+ });
+
+ it("runs a call by either name as its Composio tool through the multi-execute tool, and answers with that tool's data", async () => {
+ const calls: any[] = [];
+ const upstream = await upstreamFor(calls);
+ const lines = start({ OMB_CONNECTOR_UPSTREAM_URL: upstream, OMB_CONNECTOR_APP_TOOLS: JSON.stringify(["gmail.search_emails"]) });
+ child!.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "gmail_search_emails", arguments: { query: "from:ada" } } })}\n`);
+ const reply = await nextJson(lines);
+ expect(calls.at(-1).params).toEqual({ name: "COMPOSIO_MULTI_EXECUTE_TOOL", arguments: { tools: [{ tool_slug: "GMAIL_FETCH_EMAILS", arguments: { user_id: "me", query: "from:ada", max_results: 10, include_payload: false, verbose: false } }] } });
+ expect(reply).toEqual({ jsonrpc: "2.0", id: 4, result: { content: [{ type: "text", text: JSON.stringify({ messages: [{ messageId: "m1", subject: "Q3" }] }) }] } });
+ });
+});
diff --git a/server/connector-proxy.ts b/server/connector-proxy.ts
index 00cfb3294c..986efc54e7 100644
--- a/server/connector-proxy.ts
+++ b/server/connector-proxy.ts
@@ -11,6 +11,7 @@ import {
parseConnectorServiceSlugsEnv,
withAuthConfigParameter,
} from "./connector-advertisement.ts";
+import { APP_TOOL_NAMES_ENV, APP_TOOLS_ENV, appToolAnswer, appToolCall, appToolEntries, parseAppToolsEnv } from "./connector-app-tools.ts";
import { withSignedOutHint } from "./connector-signed-out-hint.ts";
import { AUTH_CONFIG_ID } from "../shared/connector-availability.ts";
import { fitToolListResult } from "./mcp-tool-schema.ts";
@@ -28,6 +29,8 @@ const ALLOWED_TOOLS = parseConnectorAllowedToolsEnv(process.env[CONNECTOR_ALLOWE
const SERVICE_SLUGS = parseConnectorServiceSlugsEnv(process.env[CONNECTOR_SERVICE_SLUGS_ENV]);
const SCHEMA_PROFILE = toolSchemaProfileFromEnv(process.env);
const TOOL_LIMIT = toolLimitFromEnv(process.env);
+const APP_TOOLS = parseAppToolsEnv(process.env[APP_TOOLS_ENV]);
+const APP_TOOL_NAMES = process.env[APP_TOOL_NAMES_ENV] === "dotted" ? "dotted" : "plain";
const MAX_RESPONSE_BYTES = 20 * 1024 * 1024;
const INITIALIZE_RELAY_TIMEOUT_MS = 1_000;
const RELAY_TIMEOUT_MS = 10 * 60_000;
@@ -208,6 +211,15 @@ async function showConnectorCards(items: ConnectorRequest[]): Promise<string> {
return typeof body.authConfigNote === "string" && body.authConfigNote ? ` ${body.authConfigNote}` : "";
}
+/** The upstream list with the app tools after it, unless it already has one by that name. */
+function withAppTools(frame: Json): Json {
+ const result = frame.result as { tools?: unknown } | undefined;
+ if (!APP_TOOLS.length || !result || !Array.isArray(result.tools)) return frame;
+ const listed = new Set(result.tools.map((tool) => (tool as { name?: unknown })?.name));
+ const added = appToolEntries(APP_TOOLS, APP_TOOL_NAMES).filter((tool) => !listed.has(tool.name));
+ return { ...frame, result: { ...result, tools: [...result.tools, ...added] } };
+}
+
function fittedList(frame: Json): Json {
if ((!SCHEMA_PROFILE && TOOL_LIMIT === undefined) || !("result" in frame)) return frame;
const log = (line: string) => process.stderr.write(`connector-proxy: ${line}\n`);
@@ -259,6 +271,13 @@ async function handle(message: Json): Promise<void> {
send(textResult(id, "OpenMausBot is handling connection completion and will continue the task automatically."));
return;
}
+ const app = appToolCall(name, params.arguments);
+ if (app) {
+ const call = app.frame(id);
+ const response = await relay(call);
+ if (response && id !== undefined) send(appToolAnswer(app.slug, withSignedOutHint(call, response, SERVICE_SLUGS)));
+ return;
+ }
}
try {
// The engine lists tools once per session, so one failed listing would leave the whole session without them.
@@ -266,7 +285,7 @@ async function handle(message: Json): Promise<void> {
? await relay(message).catch(() => delay(TOOLS_LIST_RETRY_MS).then(() => relay(message)))
: await relay(message);
if (response && id !== undefined) {
- send(method === "tools/list" ? fittedList(withAuthConfigParameter(ALLOWED_TOOLS ? filterToolsListFrame(response, ALLOWED_TOOLS, SERVICE_SLUGS) : response))
+ send(method === "tools/list" ? fittedList(withAppTools(withAuthConfigParameter(ALLOWED_TOOLS ? filterToolsListFrame(response, ALLOWED_TOOLS, SERVICE_SLUGS) : response)))
: method === "tools/call" ? withSignedOutHint(message, response, SERVICE_SLUGS) : response);
}
} catch (error) {
diff --git a/server/contracts.ts b/server/contracts.ts
index 74b2e8750b..526eef4a7e 100644
--- a/server/contracts.ts
+++ b/server/contracts.ts
@@ -222,6 +222,9 @@ export interface ProviderAdapter {
computerMcp?: boolean;
/** The driver mounts integrations.composio. */
composioMcp?: boolean;
+ /** The engine's tool search finds an MCP tool by the name its server gives it, dots and all (Claude Code's
+ * `select:`), so the connected-app tools are offered as gmail.search_emails rather than gmail_search_emails. */
+ mcpToolsFoundByName?: boolean;
/** True when the driver can mount the first-party physical-phone MCP. */
phoneMcp?: boolean;
/** The driver can mount the built-in browser MCP. */
diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts
index 2b6e56e9ee..aaa0d16e36 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -2057,7 +2057,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
agentsMcp: true,
customMcp: true,
computerMcp: true,
- composioMcp: true,
+ composioMcp: true, mcpToolsFoundByName: true,
phoneMcp: true,
browserMcp: true,
dataMcp: true, highlevelMcp: true, deviceMcp: true,
diff --git a/server/host/team-connections-host.ts b/server/host/team-connections-host.ts
index f6706a06dc..836c75dfa5 100644
--- a/server/host/team-connections-host.ts
+++ b/server/host/team-connections-host.ts
@@ -3,6 +3,7 @@
// and their own message started it.
// Security: nothing else ever gets a member's connection: not a group chat, the bot's main chat, another member's chat,
// an admin writing in theirs, a routine or a webhook. The relay checks it again on every call. Off a team nothing changes.
+import { createHash } from "node:crypto";
import { join } from "node:path";
import { audienceMember, type Audience } from "../audience.ts";
@@ -15,8 +16,10 @@ import { type McpOAuthManager, withMcpSignIn, withoutPendingSignIn } from "../mc
import { isRemoteMcpServer, parseStoredMcpServer } from "../mcp-registry.ts";
import { OWN_APPS_SERVER } from "../../shared/own-apps.ts";
import { appLabel, ConnectionScopes, PeopleConnections, personAppOf, SCOPES_FILE, type BrokerAccess } from "../team-connections.ts";
+import { APP_TOOL_NAMES_ENV, APP_TOOLS_ENV, appToolsFor } from "../connector-app-tools.ts";
+import type { ConnectorScopes } from "../../shared/connector-scopes.ts";
-type Bot = { id: string; name: string; connectorTools?: Parameters<typeof Composio.mcpIntegration>[1]["connectorTools"] };
+type Bot = { id: string; name: string; connectorTools?: Parameters<typeof Composio.mcpIntegration>[1]["connectorTools"]; connectorScopes?: ConnectorScopes };
type Integration = { command: string; args: string[]; env: Record<string, string> };
export interface TeamConnectionsHostDeps {
@@ -58,6 +61,21 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {
isOwnerLive: deps.isSessionLive,
});
const personApps = () => (team ? scopes.person("app") : []);
+ /** The apps connected for an installation, the team's or a member's own, read at most once a minute. */
+ const connectedApps = new Map<string, { at: number; apps: Promise<string[]> }>();
+ const appsConnected = (as?: BrokerAccess): Promise<string[]> => {
+ const key = as ? createHash("sha256").update(as.url).update("\u0000").update(as.token).digest("hex") : "";
+ const cached = connectedApps.get(key);
+ if (cached && Date.now() - cached.at < 60_000) return cached.apps;
+ const apps = deps.composio.connectedServices(deps.cfg(), as)
+ .then((services) => Object.entries(services).filter(([, state]) => state.connected).map(([slug]) => slug), () => [] as string[]);
+ connectedApps.set(key, { at: Date.now(), apps });
+ return apps;
+ };
+ const withAppTools = async (bridge: Integration, bot: Bot, names: "dotted" | "plain", as?: BrokerAccess): Promise<Integration> => {
+ const tools = appToolsFor(bot, await appsConnected(as));
+ return tools.length ? { ...bridge, env: { ...bridge.env, [APP_TOOLS_ENV]: JSON.stringify(tools), [APP_TOOL_NAMES_ENV]: names } } : bridge;
+ };
const personMcp = () => (team ? scopes.person("mcp") : []);
const link = () => (team && deps.adminOrigin ? `${deps.adminOrigin}/cloud/team/${encodeURIComponent(team.id)}` : null);
const without = <T,>(servers: Record<string, T>, names: readonly string[]) =>
@@ -111,18 +129,19 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {
link,
turnPerson,
- /** The connected-apps bridges of a turn: the team's, and in a member's own turn their own beside it. */
- async appsIntegrations(bot: Bot, threadId: string, generation: string): Promise<{ composio?: Integration; composioOwn?: Integration }> {
+ /** The connected-apps bridges of a turn: the team's, and in a member's own turn their own beside it. `names`: how the
+ * engine spells the app tools' names. */
+ async appsIntegrations(bot: Bot, threadId: string, generation: string, names: "dotted" | "plain" = "plain"): Promise<{ composio?: Integration; composioOwn?: Integration }> {
const cfg = deps.cfg();
const out: { composio?: Integration; composioOwn?: Integration } = {};
const base = { harnessUrl: deps.harnessUrl, botId: bot.id, threadId, connectorTools: bot.connectorTools };
const shared = await deps.composio.mcpIntegration(cfg, { ...base, commsToken: deps.mint({ botId: bot.id, threadId, generation }) });
- if (shared) out.composio = shared;
+ if (shared) out.composio = await withAppTools(shared, bot, names);
const person = personApps().length ? turnPerson(threadId, generation) : null;
const access = person ? people.appsAccess(person) : null;
if (person && access) {
const own = await deps.composio.mcpIntegration(cfg, { ...base, as: access, commsToken: deps.mint({ botId: bot.id, threadId, generation, connectorsFor: person }) });
- if (own) out.composioOwn = own;
+ if (own) out.composioOwn = await withAppTools(own, bot, names, access);
}
return out;
},
diff --git a/server/index.ts b/server/index.ts
index ef1d7ff4cf..823c00efd6 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -8125,7 +8125,7 @@ async function startTurn(
integrations.phone = phoneIntegration(bot.id, threadId, dispatchClaimId);
}
if (bot.composio !== false && composio.configured(cfg) && instance.adapter.capabilities.composioMcp === true) {
- Object.assign(integrations, await teamConnections.appsIntegrations(bot, threadId, dispatchClaimId));
+ Object.assign(integrations, await teamConnections.appsIntegrations(bot, threadId, dispatchClaimId, instance.adapter.capabilities.mcpToolsFoundByName ? "dotted" : "plain"));
}
// User MCP servers' tools are never pre-allowed: every call rides the normal permission flow.
if (instance.adapter.capabilities.customMcp === true && !proactive.fence.confines(threadId)) {
@@ -10055,7 +10055,7 @@ async function runClaimedGroupMemberTurn(
}
try {
if (bot.composio !== false && composio.configured(cfg) && instance.adapter.capabilities.composioMcp === true) {
- Object.assign(integrations, await teamConnections.appsIntegrations(bot, threadId, internalGeneration));
+ Object.assign(integrations, await teamConnections.appsIntegrations(bot, threadId, internalGeneration, instance.adapter.capabilities.mcpToolsFoundByName ? "dotted" : "plain"));
}
} catch (error) {
const message = `connected apps are unavailable — ${error instanceof Error ? error.message : String(error)}`;
diff --git a/server/store.test.ts b/server/store.test.ts
index 5960268315..7abe961be7 100644
--- a/server/store.test.ts
+++ b/server/store.test.ts
@@ -43,6 +43,21 @@ describe("Store", () => {
expect(new Store(selection).bot(bot.id)).not.toHaveProperty("toolScope");
});
+ it("gives an app the bot's Apps switch turned on its tools, on load and whenever the switch changes", () => {
+ const store = new Store(selection);
+ const bot = store.createBot({ name: "Mail reader" });
+ const file = join(DATA_DIR, "bots.json");
+ const rows = JSON.parse(readFileSync(file, "utf8")) as BotRecord[];
+ Object.assign(rows.find((row) => row.id === bot.id)!, { composio: true, connectorTools: {}, connectorScopes: { apps: { gmail: "read", googlecalendar: "write" } } });
+ writeFileSync(file, JSON.stringify(rows));
+ const loaded = new Store(selection);
+ expect(loaded.bot(bot.id)?.connectorTools).toEqual({ gmail: { tools: "*" }, googlecalendar: { tools: "*" } });
+ expect((JSON.parse(readFileSync(file, "utf8")) as BotRecord[]).find((row) => row.id === bot.id)?.connectorTools, "saved").toEqual({ gmail: { tools: "*" }, googlecalendar: { tools: "*" } });
+ loaded.patchBot(bot.id, { connectorTools: { gmail: { tools: ["GMAIL_FETCH_EMAILS"] } } });
+ loaded.patchBot(bot.id, { connectorScopes: { apps: { gmail: "read", github: "write" } } });
+ expect(loaded.bot(bot.id)?.connectorTools, "a list already chosen for an app stays").toEqual({ gmail: { tools: ["GMAIL_FETCH_EMAILS"] }, github: { tools: "*" } });
+ });
+
it.each([undefined, { allow: ["native:read"] }, { deny: ["native:bash"] }])("does not activate a wider tool selection when saving %j fails", (toolScope) => {
const store = new Store(selection);
const bot = store.createBot();
diff --git a/server/store.ts b/server/store.ts
index 0a862b9c2f..022a0dd2d3 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -3,7 +3,7 @@ import { join } from "node:path";
import { writeFileAtomic, writeFileAtomicIfChanged } from "./atomic.ts";
import { commitRegistryChange, keptRevocation, saveRegistryFor } from "./registry-save.ts";
-import { parseToolScope, toolScopeWidens } from "../shared/tool-scope.ts";
+import { parseToolScope, toolScopeWidens } from "../shared/tool-scope.ts"; import { grantScopedApps } from "../shared/connector-scopes.ts";
import { reorderStable } from "../shared/bot-order.ts";
import { botOwner, chiefConflict, chiefScope, ownerEmail } from "../shared/bot-owner.ts";
import { ensureSections, readSections, changeEmptySection } from "./section-context.ts";
@@ -351,7 +351,7 @@ export class Store {
for (const b of this.bots) {
if (b.busy || (b.activity !== undefined && b.activity !== "idle")) botsMigrated = true;
b.busy = false;
- b.activity = "idle";
+ b.activity = "idle"; if (grantScopedApps(b)) botsMigrated = true;
if (typeof b.soul !== "string") {
b.soul = "";
botsMigrated = true;
@@ -1546,7 +1546,7 @@ export class Store {
const toAsk = patch.modelSelection ? (bot.tasks ?? []).filter((task) => task.modelSelection === undefined &&
this.switchNeedsAsk(id, task.threadId, bot.modelSelection, patch.modelSelection!)) : [];
// Revocations take effect in memory even when the disk write fails.
- Object.assign(bot, patch);
+ Object.assign(bot, patch); if (patch.connectorScopes !== undefined) grantScopedApps(bot);
for (const task of toAsk) Object.assign(task, structuredClone(ASK_NOW));
const task = this.activeTask(id);
if (task) {
diff --git a/server/system-prompt.test.ts b/server/system-prompt.test.ts
index 3188301a1f..05d18bc566 100644
--- a/server/system-prompt.test.ts
+++ b/server/system-prompt.test.ts
@@ -308,8 +308,14 @@ describe("shared sentences", () => {
});
describe("composioSystemPrompt", () => {
- it("keeps the generic all-tools sentence for legacy bots", () => {
- expect(composioSystemPrompt(undefined)).toBe(COMPOSIO_PROMPT);
+ it("keeps the generic all-tools sentence for legacy bots, with the app tools every engine offers by name", () => {
+ expect(composioSystemPrompt(undefined)).toBe(`${COMPOSIO_PROMPT} Gmail and Google Calendar, when connected, have tools of their own: call gmail.search_emails, gmail.read_email and gmail.read_email_thread, and googlecalendar.list_events and googlecalendar.list_calendars directly (your engine may show them behind its own prefix, with _ for the dot), and use the composio tools for everything else.`);
+ });
+
+ it("names the app tools of only the apps a bot was granted", () => {
+ expect(composioSystemPrompt({ gmail: { tools: "*" } })).toContain("Gmail, when connected, has tools of its own: call gmail.search_emails, gmail.read_email and gmail.read_email_thread directly");
+ expect(composioSystemPrompt({ github: { tools: "*" } })).not.toContain("gmail.");
+ expect(composioSystemPrompt({})).not.toContain("gmail.");
});
it("offers only a connection card when no tools are granted", () => {
diff --git a/server/system-prompt.ts b/server/system-prompt.ts
index 008add74fb..7c9bf33bf4 100644
--- a/server/system-prompt.ts
+++ b/server/system-prompt.ts
@@ -170,14 +170,27 @@ function syncedFoldersPrompt(synced: ReadonlyArray<{ computerName: string; pcPat
export const COMPOSIO_PROMPT =
" The user's connected apps (Gmail, Calendar, Slack, Notion, and the rest) are reachable through the composio tools — find the right one with COMPOSIO_SEARCH_TOOLS, read its arguments with COMPOSIO_GET_TOOL_SCHEMAS, then run it with COMPOSIO_MULTI_EXECUTE_TOOL. Reach for them before telling the user you have no access to a service.";
+/** The app tools a bot with these apps can call by name, on every engine. */
+const APP_TOOLS_PROMPT: Record<string, { label: string; tools: string }> = {
+ gmail: { label: "Gmail", tools: "gmail.search_emails, gmail.read_email and gmail.read_email_thread" },
+ googlecalendar: { label: "Google Calendar", tools: "googlecalendar.list_events and googlecalendar.list_calendars" },
+};
+
+function appToolsPrompt(apps: readonly string[]): string {
+ const named = apps.filter((app) => Object.hasOwn(APP_TOOLS_PROMPT, app)).map((app) => APP_TOOLS_PROMPT[app]!);
+ if (!named.length) return "";
+ const one = named.length === 1;
+ return ` ${named.map((app) => app.label).join(" and ")}, when connected, ${one ? "has tools of its" : "have tools of their"} own: call ${named.map((app) => app.tools).join(", and ")} directly (your engine may show them behind its own prefix, with _ for the dot), and use the composio tools for everything else.`;
+}
+
export function composioSystemPrompt(grants: Record<string, ConnectorToolGrant> | undefined): string {
- if (grants === undefined) return COMPOSIO_PROMPT;
+ if (grants === undefined) return COMPOSIO_PROMPT + appToolsPrompt(Object.keys(APP_TOOLS_PROMPT));
const services = Object.keys(grants);
if (services.length === 0) {
return " No connected apps are assigned to this bot. If a task needs one, or an app's sign-in has expired, call COMPOSIO_MANAGE_CONNECTIONS to show the user a card that connects it, and ask them to allow that app for this bot in OpenMausBot.";
}
const named = services.map(connectorServiceLabel).join(", ");
- return ` The user's connected apps assigned to this bot (${named}) are reachable through the composio tools — find the right one with COMPOSIO_SEARCH_TOOLS, read its arguments with COMPOSIO_GET_TOOL_SCHEMAS, then run it with COMPOSIO_MULTI_EXECUTE_TOOL. Only the tools this bot was granted will run; when a needed tool is refused, tell the user and ask them to grant it in OpenMausBot. Reach for the granted services before telling the user you have no access.`;
+ return ` The user's connected apps assigned to this bot (${named}) are reachable through the composio tools — find the right one with COMPOSIO_SEARCH_TOOLS, read its arguments with COMPOSIO_GET_TOOL_SCHEMAS, then run it with COMPOSIO_MULTI_EXECUTE_TOOL. Only the tools this bot was granted will run; when a needed tool is refused, tell the user and ask them to grant it in OpenMausBot. Reach for the granted services before telling the user you have no access.${appToolsPrompt(services)}`;
}
function connectorServiceLabel(slug: string): string {
diff --git a/shared/connector-scopes.test.ts b/shared/connector-scopes.test.ts
index bce8897112..ca150d796d 100644
--- a/shared/connector-scopes.test.ts
+++ b/shared/connector-scopes.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
import {
connectorAccessDecision,
describeConnectorScopes,
+ grantScopedApps,
isReadOnlyAction,
normalizeConnectorScopes,
toolkitOf,
@@ -95,3 +96,24 @@ describe("describeConnectorScopes", () => {
expect(text).toContain("slack (read and write)");
});
});
+
+describe("grantScopedApps", () => {
+ it("gives every tool to an app the scopes turn on and the tool list leaves out, and nothing else", () => {
+ const bot: Parameters<typeof grantScopedApps>[0] = { connectorTools: {}, connectorScopes: { apps: { gmail: "read" } } };
+ expect(grantScopedApps(bot)).toBe(true);
+ expect(bot.connectorTools).toEqual({ gmail: { tools: "*" } });
+ expect(grantScopedApps(bot), "once").toBe(false);
+ const listed = { connectorTools: { gmail: { tools: ["GMAIL_FETCH_EMAILS"] } }, connectorScopes: { apps: { gmail: "write" as const } } };
+ expect(grantScopedApps(listed)).toBe(false);
+ expect(listed.connectorTools).toEqual({ gmail: { tools: ["GMAIL_FETCH_EMAILS"] } });
+ });
+
+ it("leaves a bot with no tool list or no scopes alone: every app, or what its list says", () => {
+ const legacy = { connectorScopes: { apps: { gmail: "read" as const } } };
+ expect(grantScopedApps(legacy)).toBe(false);
+ expect(legacy).not.toHaveProperty("connectorTools");
+ const off = { connectorTools: {} };
+ expect(grantScopedApps(off)).toBe(false);
+ expect(off.connectorTools).toEqual({});
+ });
+});
diff --git a/shared/connector-scopes.ts b/shared/connector-scopes.ts
index 0f6a5a7291..8d70629f64 100644
--- a/shared/connector-scopes.ts
+++ b/shared/connector-scopes.ts
@@ -71,6 +71,17 @@ export function connectorAccessDecision(scopes: ConnectorScopes | undefined, cal
return { ok: true };
}
+/** A bot whose scopes switch an app on gets that app's tools: every one, unless its tool list already names some. A tool
+ * list that leaves out an app its scopes turn on would give that app no tool on any engine. True when `bot` changed. */
+export function grantScopedApps(bot: { connectorScopes?: ConnectorScopes; connectorTools?: Record<string, { tools: "*" | string[] }> }): boolean {
+ const tools = bot.connectorTools, scopes = bot.connectorScopes;
+ if (!scopes || !tools || typeof tools !== "object" || Array.isArray(tools)) return false;
+ const missing = Object.keys(scopes.apps).filter((slug) => !Object.hasOwn(tools, slug));
+ if (!missing.length) return false;
+ bot.connectorTools = { ...tools, ...Object.fromEntries(missing.map((slug) => [slug, { tools: "*" as const }])) };
+ return true;
+}
+
/** One sentence for the bot's prompt, so it does not spend a turn finding
* out. Empty when the bot is unscoped. */
export function describeConnectorScopes(scopes: ConnectorScopes | undefined): string {