Skip to content

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

Team calls: an unverifiable app inventory refuses opaque code instead of allowing it

milind-sonifcf87045df89
diff --git a/server/composio-inventory-schema.ts b/server/composio-inventory-schema.ts
new file mode 100644
index 0000000000..677ca4ce13
--- /dev/null
+++ b/server/composio-inventory-schema.ts
@@ -0,0 +1,44 @@
+import { z } from "zod";
+
+export const ACCOUNT_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
+const TOOLKIT_SLUG = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
+
+const connectedAccountResponseSchema = z.object({
+ id: z.string().optional(),
+ alias: z.string().nullable().optional(),
+ status: z.string().optional(),
+ updated_at: z.string().optional(),
+ toolkit: z.object({ slug: z.string().optional() }).optional(),
+});
+export type ConnectedAccountResponse = z.infer<typeof connectedAccountResponseSchema>;
+
+export const connectedAccountsPageSchema = z.object({
+ items: z.array(connectedAccountResponseSchema),
+ next_cursor: z.string().nullable().optional(),
+});
+
+const toolkitItemSchema = z.object({
+ slug: z.string().optional(),
+ is_no_auth: z.boolean().optional(),
+ connected_account: z.object({ id: z.string().optional(), status: z.string().optional() }).nullable().optional(),
+});
+export type ToolkitItem = z.infer<typeof toolkitItemSchema>;
+export const toolkitPageSchema = z.object({
+ items: z.array(toolkitItemSchema).optional(),
+ next_cursor: z.string().nullable().optional(),
+});
+
+export const inventoryAccountSchema = z.object({
+ id: z.string().regex(ACCOUNT_ID),
+ toolkit: z.object({ slug: z.string().regex(TOOLKIT_SLUG) }),
+});
+
+export const toolkitInventoryPageSchema = toolkitPageSchema.extend({
+ items: z.array(toolkitItemSchema.extend({
+ slug: z.string().regex(TOOLKIT_SLUG),
+ connected_account: z.object({
+ id: z.string().regex(ACCOUNT_ID),
+ status: z.string().optional(),
+ }).nullable().optional(),
+ }).refine((item) => item.is_no_auth === true || item.connected_account != null)),
+});
diff --git a/server/composio-inventory.test.ts b/server/composio-inventory.test.ts
new file mode 100644
index 0000000000..a23616488b
--- /dev/null
+++ b/server/composio-inventory.test.ts
@@ -0,0 +1,137 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import * as composio from "./composio.ts";
+import type { AppConfig } from "./config.ts";
+import { createTeamConnectionsHost } from "./host/team-connections-host.ts";
+
+const directories: string[] = [];
+let backend = 0;
+const capability = { threadId: "room", generation: "g" };
+const opaqueCalls = [{ slug: "COMPOSIO_PROXY_EXECUTE" }];
+
+function guard(cfg: AppConfig = {}) {
+ const dataDir = mkdtempSync(join(tmpdir(), "omb-inventory-"));
+ directories.push(dataDir);
+ const host = createTeamConnectionsHost({
+ team: { id: "fixture", name: "Fixture" }, dataDir, cfg: () => cfg,
+ adminOrigin: null, harnessUrl: "http://127.0.0.1:1", audienceOf: () => "room:fixture", requester: () => null,
+ mint: () => "fixture", mcpOAuth: {} as never, botMcp: () => ({}), isOwnerLive: () => true,
+ brokerUrl: () => null, composio,
+ });
+ host.scopes.set("app", "gmail", "person");
+ return host;
+}
+
+afterEach(() => {
+ composio.setManagedBrokerAccess(null);
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true });
+});
+
+describe("broker inventory completeness", () => {
+ it.each(["unavailable", "incomplete", "malformed"])("keeps display and bridge slugs but refuses opaque calls after an %s refresh", async (failure) => {
+ composio.setManagedBrokerAccess({ url: `https://broker.test/${++backend}`, token: "a".repeat(64) });
+ let broken = false;
+ vi.stubGlobal("fetch", async () => {
+ if (broken && failure === "unavailable") throw new Error("synthetic inventory timeout");
+ if (broken && failure === "malformed") return Response.json({});
+ return Response.json({ services: { slack: { connected: true } }, complete: !(broken && failure === "incomplete") });
+ });
+ const context = { harnessUrl: "http://127.0.0.1:1", commsToken: "fixture", botId: "bot", threadId: "room", connectorTools: { slack: { tools: "*" as const } } };
+ const host = guard();
+ const initialBridge = await composio.mcpIntegration({}, context);
+ await expect(composio.connectedServiceSlugs({})).resolves.toEqual(["slack"]);
+ await expect(host.callRefusal(capability, opaqueCalls)).resolves.toBeNull();
+ broken = true;
+ // A fresh display cache cannot prove that a person's app is absent now.
+ await expect(host.callRefusal(capability, opaqueCalls)).resolves.toEqual(expect.stringMatching(/inventory could not be verified/));
+ const now = vi.spyOn(Date, "now").mockReturnValue(Date.now() + 61_000);
+ try {
+ await expect(composio.connectedServiceSlugs({})).resolves.toEqual(["slack"]);
+ expect(await composio.mcpIntegration({}, context)).toEqual(initialBridge);
+ await expect(host.callRefusal(capability, opaqueCalls)).resolves.toEqual(expect.stringMatching(/inventory could not be verified/));
+ broken = false;
+ await expect(host.callRefusal(capability, opaqueCalls)).resolves.toBeNull();
+ } finally {
+ now.mockRestore();
+ }
+ });
+
+ it("reads a broker that sends no complete field as complete, and an explicit false as unverified", async () => {
+ composio.setManagedBrokerAccess({ url: `https://broker.test/${++backend}`, token: "a".repeat(64) });
+ let body: Record<string, unknown> = { configured: true, services: {} };
+ vi.stubGlobal("fetch", async () => Response.json(body));
+ const host = guard();
+
+ await expect(composio.connectedServicesInventory({})).resolves.toEqual({ services: {}, complete: true });
+ await expect(host.callRefusal(capability, opaqueCalls)).resolves.toBeNull();
+
+ body = { configured: true, services: {}, complete: false };
+ await expect(composio.connectedServicesInventory({})).resolves.toEqual({ services: {}, complete: false });
+ await expect(composio.verifiedConnectedServiceSlugs({})).rejects.toThrow(/inventory.*incomplete/i);
+ await expect(host.callRefusal(capability, opaqueCalls)).resolves.toEqual(expect.stringMatching(/inventory could not be verified/));
+
+ body = { configured: true, services: {}, complete: true };
+ await expect(composio.connectedServicesInventory({})).resolves.toEqual({ services: {}, complete: true });
+ await expect(host.callRefusal(capability, opaqueCalls)).resolves.toBeNull();
+ await expect(composio.connectedServiceSlugs({})).resolves.toEqual([]);
+ });
+});
+
+describe.each(["connected_accounts", "toolkits"])("self-hosted %s inventory", (walker) => {
+ it.each(["repeated cursor", "cursor cycle", "page cap", "missing items", "invalid items", "missing item identity",
+ "missing account id", "invalid account id", "missing slug", "empty slug", "invalid slug",
+ ...(walker === "toolkits" ? ["missing selected account", "missing selected id", "invalid selected id"] : [])])(
+ "refuses opaque calls on %s and recovers on the same backend", async (failure) => {
+ const cfg: AppConfig = { composio: { apiKey: `ak_inventory_${++backend}`, userId: "fixture", sessionId: "trs_inventory" } };
+ vi.stubEnv("OMB_COMPOSIO_API", "http://127.0.0.1:9876/api/v3.1");
+ let broken = true;
+ vi.stubGlobal("fetch", async (input: string | URL | Request) => {
+ const url = new URL(String(input));
+ if (url.pathname.endsWith("/auth_configs")) return Response.json({ items: [] });
+ if (url.pathname.endsWith("/tool_router/session/trs_inventory")) return Response.json({
+ session_id: "trs_inventory", mcp: { type: "http", url: "http://127.0.0.1:9876/mcp" },
+ config: { user_id: "fixture", multi_account: { enable: true } },
+ });
+ if (url.pathname.endsWith("/connected_accounts") || url.pathname.endsWith("/toolkits")) {
+ if (broken && url.pathname.endsWith(`/${walker}`)) {
+ const malformed: Record<string, unknown> = walker === "connected_accounts" ? {
+ "missing item identity": {}, "missing account id": { toolkit: { slug: "gmail" } },
+ "invalid account id": { id: "bad id", toolkit: { slug: "gmail" } },
+ "missing slug": { id: "ca_gmail", toolkit: {} },
+ "empty slug": { id: "ca_gmail", toolkit: { slug: "" } },
+ "invalid slug": { id: "ca_gmail", toolkit: { slug: " " } },
+ } : {
+ "missing item identity": {}, "missing slug": { is_no_auth: true },
+ "empty slug": { slug: "", is_no_auth: true }, "invalid slug": { slug: " ", is_no_auth: true },
+ "missing selected account": { slug: "gmail" },
+ "missing selected id": { slug: "gmail", connected_account: {} },
+ "invalid selected id": { slug: "gmail", connected_account: { id: "bad id" } },
+ "missing account id": { slug: "gmail", connected_account: null },
+ "invalid account id": { slug: "gmail", is_no_auth: true, connected_account: { id: "bad id" } },
+ };
+ if (Object.hasOwn(malformed, failure)) return Response.json({ items: [malformed[failure]] });
+ const cursor = url.searchParams.get("cursor");
+ if (failure === "missing items") return Response.json({});
+ if (failure === "invalid items") return Response.json({ items: {} });
+ const next = failure === "page cap" ? `${Number(cursor ?? 0) + 1}`
+ : failure === "cursor cycle" && cursor === "a" ? "b" : "a";
+ return Response.json({ items: [], next_cursor: next });
+ }
+ return Response.json({ items: [] });
+ }
+ throw new Error(`Unexpected inventory request: ${url}`);
+ });
+ const host = guard(cfg);
+ await expect(host.callRefusal(capability, opaqueCalls)).resolves.toEqual(expect.stringMatching(/inventory could not be verified/));
+ await expect(composio.verifiedConnectedServiceSlugs(cfg)).rejects.toThrow();
+ broken = false;
+ await expect(host.callRefusal(capability, opaqueCalls)).resolves.toBeNull();
+ await expect(composio.connectedServiceSlugs(cfg)).resolves.toEqual([]);
+ },
+ );
+});
diff --git a/server/composio.test.ts b/server/composio.test.ts
index ab6533b7a5..f5c3eddbab 100644
--- a/server/composio.test.ts
+++ b/server/composio.test.ts
@@ -7,6 +7,7 @@ import {
applyManagedBrokerMessage,
authorizeService,
connectedServiceSlugs,
+ verifiedConnectedServiceSlugs,
connectedServices,
connectedServicesInventory,
connectionMode,
@@ -74,7 +75,7 @@ let brokerMcpTools: Array<{ name: string; description?: string }> | null = null;
let brokerToolsListFail = false;
// What /broker/v1/connectors/connected serves; null falls back to github
// only, the state the existing validation tests were written against.
-let brokerConnectedServicesBody: { services: Record<string, { connected: boolean; status: string }> } | null = null;
+let brokerConnectedServicesBody: { complete?: boolean; services: Record<string, { connected: boolean; status: string }> } | null = null;
let brokerConnectedServicesFail = false;
// What /broker/v1/catalog serves; null falls back to github only.
let brokerCatalogBody: { items: Array<{ slug: string; name: string }> } | null = null;
@@ -342,8 +343,10 @@ beforeAll(async () => {
items: [
{ slug: "github", connected_account: { id: "ca_github", status: "ACTIVE" } },
{ slug: "gmail", is_no_auth: true },
- { slug: "slack" },
- { slug: "unconnected", connected_account: null },
+ ...(url.searchParams.has("toolkits") ? [
+ { slug: "slack" },
+ { slug: "unconnected", connected_account: null },
+ ] : []),
],
next_cursor: url.searchParams.has("toolkits") ? undefined : "toolkits-page-2",
};
@@ -980,6 +983,63 @@ describe.sequential("Composio Sessions", () => {
await expect(connectedServiceSlugs({})).resolves.toEqual([]);
});
+ it("rejects an unreachable connection inventory instead of reporting no service slugs", async () => {
+ await expect(verifiedConnectedServiceSlugs({})).rejects.toThrow(/unavailable/);
+ });
+
+ it("does not cache a failed inventory and retries discovery on the same backend", async () => {
+ setManagedBrokerAccess({ url: origin + "/broker", token: "9".repeat(64) });
+ const broken = vi.spyOn(globalThis, "fetch").mockRejectedValueOnce(new Error("synthetic inventory timeout"));
+ try {
+ await expect(verifiedConnectedServiceSlugs({})).rejects.toThrow(/synthetic inventory timeout/);
+ await expect(connectedServiceSlugs({})).resolves.toEqual(["github"]);
+ } finally {
+ broken.mockRestore();
+ setManagedBrokerAccess(null);
+ }
+ });
+
+ it("rejects incomplete account discovery without caching its partial service slugs", async () => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(Date.now() + 61_000);
+ const cfg: AppConfig = { composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" } };
+ connectedAccountsUnavailable = true;
+ try {
+ await expect(verifiedConnectedServiceSlugs(cfg)).rejects.toThrow(/inventory.*incomplete/i);
+ connectedAccountsUnavailable = false;
+ await expect(connectedServiceSlugs(cfg)).resolves.toContain("toolkit_41");
+ } finally {
+ connectedAccountsUnavailable = false;
+ vi.useRealTimers();
+ }
+ });
+
+ it("rejects a broker response without an inventory instead of caching an empty one", async () => {
+ setManagedBrokerAccess({ url: origin + "/broker", token: "b".repeat(64) });
+ const broken = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(Response.json({}));
+ try {
+ await expect(verifiedConnectedServiceSlugs({})).rejects.toThrow(/services/);
+ } finally {
+ broken.mockRestore();
+ setManagedBrokerAccess(null);
+ }
+ });
+
+ it("reads a broker that sends no complete field as complete, and an explicit false as incomplete", async () => {
+ setManagedBrokerAccess({ url: origin + "/broker", token: "7".repeat(64) });
+ try {
+ brokerConnectedServicesBody = { services: { gmail: { connected: true, status: "ACTIVE" } } };
+ await expect(connectedServicesInventory({})).resolves.toMatchObject({ complete: true });
+ await expect(verifiedConnectedServiceSlugs({})).resolves.toEqual(["gmail"]);
+ brokerConnectedServicesBody = { complete: false, services: { gmail: { connected: true, status: "ACTIVE" } } };
+ await expect(connectedServicesInventory({})).resolves.toMatchObject({ complete: false });
+ await expect(verifiedConnectedServiceSlugs({})).rejects.toThrow(/inventory.*incomplete/i);
+ } finally {
+ brokerConnectedServicesBody = null;
+ setManagedBrokerAccess(null);
+ }
+ });
+
it("keeps the last service slugs when a later read fails, so the bridge's tools stay as they were", async () => {
const access = { url: origin + "/broker", token: "e".repeat(64) };
brokerConnectedServicesBody = { services: { bland_ai: { connected: true, status: "ACTIVE" } } };
@@ -1387,6 +1447,24 @@ describe("connector tool inventory", () => {
const initializeCalls = () =>
calls.filter((call) => call.path.endsWith("/v1/mcp") && call.body?.method === "initialize");
+ it("groups tools using the cached service inventory after a failed refresh", async () => {
+ setManagedBrokerAccess({ url: origin + "/broker", token: "8".repeat(64) });
+ brokerConnectedServicesBody = { services: { bland_ai: { connected: true, status: "ACTIVE" } } };
+ brokerMcpTools = [{ name: "BLAND_AI_MAKE_CALL" }];
+ await expect(connectedServiceSlugs({})).resolves.toEqual(["bland_ai"]);
+ const now = vi.spyOn(Date, "now").mockReturnValue(Date.now() + 61_000);
+ const broken = vi.spyOn(globalThis, "fetch").mockRejectedValueOnce(new Error("synthetic inventory timeout"));
+ try {
+ await expect(listConnectorTools({})).resolves.toEqual({ bland_ai: [{ name: "BLAND_AI_MAKE_CALL" }] });
+ } finally {
+ broken.mockRestore();
+ now.mockRestore();
+ brokerMcpTools = null;
+ brokerConnectedServicesBody = null;
+ setManagedBrokerAccess(null);
+ }
+ });
+
it("groups an underscored service under its own slug using the connected services", async () => {
setManagedBrokerAccess({ url: origin + "/broker", token: "c".repeat(64) });
brokerConnectedServicesBody = {
diff --git a/server/composio.ts b/server/composio.ts
index 91e76034dc..a70d8d4278 100644
--- a/server/composio.ts
+++ b/server/composio.ts
@@ -1,6 +1,7 @@
import type { AppConfig } from "./config.ts";
import { createHash, randomUUID } from "node:crypto";
import { z } from "zod";
+import { ACCOUNT_ID, connectedAccountsPageSchema, inventoryAccountSchema, toolkitInventoryPageSchema, toolkitPageSchema, type ConnectedAccountResponse, type ToolkitItem } from "./composio-inventory-schema.ts";
import { SPAWNED_PROXIES } from "./proxy-paths.ts";
import { managedConnectorUnavailableReason, managedCustomAuthReason } from "../shared/connector-availability.ts";
import {
@@ -55,44 +56,18 @@ interface AccountLinkRequest {
alias?: string;
}
-const connectedAccountResponseSchema = z.object({
- id: z.string().optional(),
- alias: z.string().nullable().optional(),
- status: z.string().optional(),
- updated_at: z.string().optional(),
- toolkit: z.object({ slug: z.string().optional() }).optional(),
-});
-type ConnectedAccountResponse = z.infer<typeof connectedAccountResponseSchema>;
-
-const connectedAccountsPageSchema = z.object({
- items: z.array(connectedAccountResponseSchema),
- next_cursor: z.string().nullable().optional(),
-});
-
-const toolkitItemSchema = z.object({
- slug: z.string().optional(),
- is_no_auth: z.boolean().optional(),
- connected_account: z.object({ id: z.string().optional(), status: z.string().optional() }).nullable().optional(),
-});
-type ToolkitItem = z.infer<typeof toolkitItemSchema>;
-const toolkitPageSchema = z.object({
- items: z.array(toolkitItemSchema).optional(),
- next_cursor: z.string().nullable().optional(),
-});
-
const connectorServiceSchema = z.object({
connected: z.boolean(),
pending: z.boolean().optional(),
status: z.string().optional(),
accounts: z.array(z.object({ id: z.string(), alias: z.string().optional(), status: z.string() })).optional(),
});
-const connectorServicesResponseSchema = z.object({ services: z.record(z.string(), connectorServiceSchema).optional() });
+const connectorServicesResponseSchema = z.object({ services: z.record(z.string(), connectorServiceSchema).optional(), complete: z.boolean().optional() });
const removalResponseSchema = z.object({ removed: z.number() });
const authUrlResponseSchema = z.object({ url: z.string().optional() });
const linkResponseSchema = z.object({ redirect_url: z.string().optional() });
const MAX_CONNECTED_ACCOUNT_PAGES = 100;
-const ACCOUNT_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
const printableAliasSchema = z.string().min(1).max(64).refine((value) => {
for (const character of value) {
const codePoint = character.codePointAt(0);
@@ -362,7 +337,8 @@ async function listConnectedAccounts(
const body = connectedAccountsPageSchema.parse(await response.json());
accounts.push(...body.items);
const next = body.next_cursor || undefined;
- if (!next || seenCursors.has(next)) return accounts;
+ if (!next) return accounts;
+ if (seenCursors.has(next)) throw new Error("Composio account inventory contains a pagination cursor cycle");
seenCursors.add(next);
cursor = next;
}
@@ -372,10 +348,11 @@ async function listConnectedAccounts(
async function listSessionToolkits(
apiKey: string,
sessionId: string,
-): Promise<ToolkitItem[]> {
- const toolkits: ToolkitItem[] = [];
+): Promise<{ items: ToolkitItem[]; complete: boolean }> {
+ const items: ToolkitItem[] = [];
const seenCursors = new Set<string>();
let cursor: string | undefined;
+ let complete = true;
for (let page = 0; page < MAX_CONNECTED_ACCOUNT_PAGES; page += 1) {
// Unfiltered, this endpoint pages through the whole marketplace 50 at a time.
const params = new URLSearchParams({ limit: "50", is_connected: "true" });
@@ -385,10 +362,13 @@ async function listSessionToolkits(
{ headers: projectHeaders(apiKey), signal: AbortSignal.timeout(15_000) },
);
if (!response.ok) throw new Error(await responseError(response, `Composio toolkits: HTTP ${response.status}`));
- const body = toolkitPageSchema.parse(await response.json());
- toolkits.push(...(body.items ?? []));
+ const raw: unknown = await response.json();
+ const body = toolkitPageSchema.parse(raw);
+ items.push(...(body.items ?? []));
+ complete &&= toolkitInventoryPageSchema.safeParse(raw).success;
const next = body.next_cursor || undefined;
- if (!next || seenCursors.has(next)) return toolkits;
+ if (!next) return { items, complete };
+ if (seenCursors.has(next)) return { items, complete: false };
seenCursors.add(next);
cursor = next;
}
@@ -475,8 +455,8 @@ export async function connectedServicesInventory(cfg: AppConfig, as?: BrokerAcce
if (!apiKey) {
const response = await brokerRequest("/v1/connectors/connected", undefined, as);
if (!response.ok) await throwBrokerError(response, `Connected apps: HTTP ${response.status}`);
- const body = connectorServicesResponseSchema.parse(await response.json());
- const services = canonicalServiceRecord(body.services ?? {});
+ const body = connectorServicesResponseSchema.required({ services: true }).parse(await response.json());
+ const services = canonicalServiceRecord(body.services);
return {
services: Object.fromEntries(
Object.entries(services).map(([slug, state]) => [slug, {
@@ -486,7 +466,8 @@ export async function connectedServicesInventory(cfg: AppConfig, as?: BrokerAcce
accounts: state.accounts ?? [],
}]),
),
- complete: true,
+ // A broker that predates this field sends none, so only an explicit false means its account read came up short.
+ complete: body.complete !== false,
};
}
const session = await ensureProjectSession(cfg);
@@ -495,15 +476,21 @@ export async function connectedServicesInventory(cfg: AppConfig, as?: BrokerAcce
const [toolkits, accountResult] = await Promise.all([
listSessionToolkits(apiKey, session.session_id),
// Scoped project keys can grant Session reads without the raw connected-account list.
- listConnectedAccounts(apiKey, userId, []).then((accounts) => ({ accounts, complete: true as const }))
- .catch(() => ({ accounts: [] as ConnectedAccountResponse[], complete: false as const })),
+ listConnectedAccounts(apiKey, userId, []).then((accounts) => ({ accounts, complete: accounts.every((account) => inventoryAccountSchema.safeParse(account).success) }))
+ .catch(() => ({ accounts: [] as ConnectedAccountResponse[], complete: false })),
]);
return {
- services: allServiceStates(summarizeAccounts(accountResult.accounts, []), toolkits),
- complete: accountResult.complete,
+ services: allServiceStates(summarizeAccounts(accountResult.accounts, []), toolkits.items),
+ complete: accountResult.complete && toolkits.complete,
};
}
+export async function verifiedConnectedServiceSlugs(cfg: AppConfig, as?: BrokerAccess): Promise<readonly string[]> {
+ const { services, complete } = await connectedServicesInventory(cfg, as);
+ if (!complete) throw new Error("Connected-app inventory is incomplete; account discovery did not finish.");
+ return Object.keys(services);
+}
+
export async function connectedServices(cfg: AppConfig, as?: BrokerAccess): Promise<Record<string, ConnectorServiceState>> {
return (await connectedServicesInventory(cfg, as)).services;
}
@@ -625,8 +612,7 @@ function connectorToolListing(tool: unknown): ConnectorToolListing | null {
}
async function collectConnectorTools(cfg: AppConfig): Promise<Record<string, ConnectorToolListing[]>> {
- const connected = await connectedServices(cfg).catch(() => null);
- const candidates = connected ? Object.keys(connected) : [];
+ const candidates = await connectedServiceSlugs(cfg);
const initialize = await relayMcp(cfg, {
jsonrpc: "2.0",
id: "omb-grants-initialize",
diff --git a/server/host/team-connections-host.test.ts b/server/host/team-connections-host.test.ts
index 2ec8b65c06..8397e89193 100644
--- a/server/host/team-connections-host.test.ts
+++ b/server/host/team-connections-host.test.ts
@@ -47,7 +47,7 @@ function setup(options: { team?: boolean; requester?: Record<string, string>; se
mcpIntegration: vi.fn(async (_cfg: AppConfig, context: { commsToken: string; as?: unknown }) => ({ command: "node", args: ["bridge"], env: { TOKEN: context.commsToken, AS: context.as ? "own" : "team" } })),
connectedServices: vi.fn(async (_cfg: AppConfig, as?: { token: string }) => (as?.token === ADA_ACCESS.token || as?.token === CLEO_ACCESS.token
? { gmail: { connected: true, pending: false, status: "ACTIVE", accounts: [{ id: "ca_1", status: "ACTIVE", alias: "[email protected]" }] } } : {})),
- connectedServiceSlugs: vi.fn(async () => ["google_search_console"] as readonly string[]),
+ verifiedConnectedServiceSlugs: vi.fn(async () => ["google_search_console"] as readonly string[]),
authorizeService: vi.fn(),
removeService: vi.fn(),
};
@@ -244,10 +244,24 @@ describe("apps each person connects", () => {
const { host, composio } = setup();
host.scopes.set("app", "google_search_console", "person");
expect(await host.callRefusal({ threadId: "room-chat", generation: "g" }, [{ slug: "COMPOSIO_PROXY_EXECUTE" }])).toMatch(/Google Search Console is connected by each person/);
- composio.connectedServiceSlugs.mockResolvedValue([]);
+ composio.verifiedConnectedServiceSlugs.mockResolvedValue([]);
expect(await host.callRefusal({ threadId: "room-chat", generation: "g" }, [{ slug: "COMPOSIO_PROXY_EXECUTE" }])).toBeNull();
});
+ it("refuses opaque team calls when inventory discovery fails, then checks the recovered inventory", async () => {
+ const { host, composio } = setup();
+ host.scopes.set("app", "gmail", "person");
+ const cap = { threadId: "room-chat", generation: "g" };
+ const calls = [{ slug: "COMPOSIO_PROXY_EXECUTE" }];
+ composio.verifiedConnectedServiceSlugs.mockResolvedValue(["gmail"]);
+ expect(await host.callRefusal(cap, calls)).toMatch(/can't run here.*Gmail/);
+ composio.verifiedConnectedServiceSlugs.mockRejectedValueOnce(new Error("synthetic inventory timeout"));
+ expect(await host.callRefusal(cap, calls)).toMatch(/can't run here.*inventory could not be verified/);
+ expect(await host.callRefusal(cap, calls)).toMatch(/can't run here.*Gmail/);
+ composio.verifiedConnectedServiceSlugs.mockResolvedValue([]);
+ expect(await host.callRefusal(cap, calls)).toBeNull();
+ });
+
it("answers a connection card for a person's app with the one plain line, never a card", () => {
const { host } = setup({ requester: { "main-chat": "" } });
host.scopes.set("app", "gmail", "person");
diff --git a/server/host/team-connections-host.ts b/server/host/team-connections-host.ts
index ca4a675b8f..925aa03397 100644
--- a/server/host/team-connections-host.ts
+++ b/server/host/team-connections-host.ts
@@ -50,7 +50,7 @@ export interface TeamConnectionsHostDeps {
onSettled?(name: string, phase: McpSignInPhase, owner: string): void;
/** The connected-apps service a member's own installation is made on; null: none here. */
brokerUrl(): string | null;
- composio: Pick<typeof Composio, "configured" | "mcpIntegration" | "connectedServices" | "connectedServiceSlugs" | "authorizeService" | "removeService">;
+ composio: Pick<typeof Composio, "configured" | "mcpIntegration" | "connectedServices" | "verifiedConnectedServiceSlugs" | "authorizeService" | "removeService">;
}
const list = (names: readonly string[]) => names.length <= 1 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
@@ -158,6 +158,7 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {
+ `Reply with this one line and nothing more about it: "${name} is connected for the whole team by ${who ? who : "the team's owner or an admin"}: ask ${who ? (who.includes(" and ") ? "one of them" : "them") : "one of them"} to connect it."`;
},
opaque: (names: string[]) => `Code that calls apps can't run here while ${list(names)} ${names.length === 1 ? "is" : "are"} connected by each person. Call the app's tools directly.`,
+ opaqueUnverified: "Code that calls apps can't run here because the team's connected-app inventory could not be verified, and it may hold apps connected by each person. Nothing was run. Call the app's tools directly, or try again when the inventory is back.",
};
/** What a `person` app the team's bridge was asked for says: in a turn that acts for someone, where theirs is; else no. */
@@ -251,7 +252,12 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {
for (const call of calls) {
if (call.slug === "COMPOSIO_PROXY_EXECUTE") {
if (own) continue;
- const held = await deps.composio.connectedServiceSlugs(deps.cfg()).catch(() => [] as readonly string[]);
+ let held: readonly string[];
+ try {
+ held = await deps.composio.verifiedConnectedServiceSlugs(deps.cfg());
+ } catch {
+ return lines.opaqueUnverified;
+ }
const kept = apps.filter((slug) => held.includes(slug));
if (kept.length) return lines.opaque(kept.map(appLabel));
continue;