mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 02:30:43 +01:00
feat(connections): sync and group accounts managed by aggregators (#15254)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Connections give agents governed access to external tools. > - Aggregator gateways can expose accounts that users already connected upstream. > - The Apps catalog did not show those accounts or their current provider status. > - Separate cards and setup tasks also made account ownership unclear. > - This pull request discovers upstream accounts and groups them under one app card. > - Users can find connected apps while each provider keeps control of its accounts. ## Linked Issues or Issue Description **Subsystem affected** Connections across the database, shared contracts, server, and board UI. **Problem or motivation** Users cannot see which apps are connected through a saved aggregator gateway. Native and upstream accounts need one app card. Discovery must preserve company, user, gateway, and credential boundaries. **Proposed solution** Sync account metadata from Composio, Arcade, and supported Executor gateways. Keep upstream account management in each provider. Use source chips and search to browse the catalog. Preserve native setup and the gateway's existing access policy. **Alternatives considered** Creating a local executable connection for each upstream account would duplicate authorization state. Using an agent task for routine Composio setup would add an unnecessary step. The board now calls the saved gateway directly for that setup. **Roadmap alignment** This extends the shipped Connected Apps and MCP Tool Gateway features in ROADMAP.md. The duplicate search found no open PR for managed account discovery. Related work: Refs #13755, Refs #13941, Refs #14725, Refs #13855. Open PR #12906 covers adjacent toolkit routing work. ## What Changed - Add provider-neutral discovery, sync, and refresh APIs. Preserve the Composio API paths. - Cache observations by company, saved gateway, viewing user, and credential version. Retain stale observations after failed or incomplete scans. - Add optional Arcade account sync credentials in the vault. Discover Executor accounts through its supported inventory interface. - Group native and upstream accounts in one app card. Imported account menus open their provider. Gateway menus own refresh and sync setup. - Add Paperclip, Composio, Arcade, Installed, and All chips. Show 50 catalog entries per page. Keep connected accounts above discovery. Keep explicit provider searches scoped. - Simplify Composio app setup and refresh its connected app list on the gateway Permissions page. - Add a compact agent access card and task creation defaults for connection setup. Preserve explicit blocks and approval policies. - Add two replay-safe migrations, service and UI tests, Storybook journeys, and acceptance stories. ## Verification - Passed the repository typecheck, full build, token gates, and migration ordering check. - Passed the focused provider adapter, connection interaction, and catalog tests after rebasing onto master. - Passed all nine database sync and migration replay tests using a disposable database on the test-drive PostgreSQL cluster. Removed that database after the run. - Verified Arcade cursor pagination against its official Go SDK and passed all eight adapter tests, including short and incomplete pages. - Passed all 45 interaction tests after making the exact requested tools and their Allowed/Ask first permissions visible before granting access. Verified the compact card in Storybook. - Passed the complete UI suite on the final code: 683 files and 7,432 tests, including the corrected Composio destination assertions. Passed 130 focused tests for the UUID, management-link, and health-status corrections. - Passed 22 Composio setup/sync tests, 23 connection-intent service tests, and the connection migration test in separate disposable databases. Database startup alone was substituted; the suites exercised their real SQL and services. - Passed all 10 OpenAPI route checks and the full-stack connection-intent browser test, including scoped consent, agent continuation, and task completion. - The local full runner encountered embedded PostgreSQL startup failures on this loaded macOS host. The earlier in-flight run also held the pre-fix Arcade transform; a fresh run of the final provider suite passes. The final-head CI is queued during GitHub’s active Actions incident: https://www.githubstatus.com/. The previous run also lost several runners simultaneously; its real catalog assertion failures are fixed and the fresh complete UI suite passes. - Tested the real test-drive server in the embedded browser with a live Composio gateway. Detected Airtable and Circleback. Verified refresh progress, account rows, source chips, search scope, and 50-entry pagination. - Arcade and Executor coverage uses provider fixtures. Live credentials were unavailable. - Storybook builds successfully and includes grouped native/provider accounts, stale and unavailable discovery, optional Arcade setup, and mobile states. The acceptance document records the simulated and live coverage separately. - Greptile reviewed final commit `217b024c27b5933e773ce9419c4e92b1032042c6` at 5/5. All six review threads are resolved, security scans pass, and the PR has no merge conflicts. The outstanding remote checks are `ci / Select trusted runner` and `review`, queued by GitHub. They need to complete before merge. ## Risks - Provider response changes can break inventory discovery. Failed scans retain observations and show stale status. - Composio scans only the supported catalog and can take time. Large inventories run in the background with progress and a bounded lease. - Arcade requires a project API key and user ID when the gateway cannot supply them. This key is used only for discovery. - Executor discovery depends on the server's exposed inventory tools. Unsupported servers report unavailable discovery. - Cached account rows do not grant access or create executable connections. Gateway policies still govern tool use. Account deletion and per-app authorization remain upstream. - The migrations add tables and one nullable column. Replay preserves existing rows and company-scoped foreign keys. ## Model Used OpenAI Codex, based on GPT-6. The session does not expose a more specific serving model ID or context limit. Used reasoning, repository tools, code execution, and browser verification. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [ ] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
55e0c895ef
commit
b43073d11f
92 files changed
+7821
-225
No files matched your search
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { AggregatorDiscoveryUnavailableError, discoverArcadeApps, discoverExecutorApps, EXECUTOR_INVENTORY_CODE, inventoryPayload } from "../services/aggregator-app-discovery.js";
|
||||
import { aggregatorManagementUrl } from "@paperclipai/shared/aggregator-apps";
|
||||
|
||||
const account = (id: string, user = "u1") => ({ id, user_id: user, provider_id: "notion-provider", connection_status: "active", provider_user_info: { email: "Work", access_token: "do-not-store" } });
|
||||
const tool = { qualified_name: "Notion.ListPages", toolkit: { name: "Notion" }, requirements: { met: true, authorization: { provider_id: "notion-provider", token_status: "completed" } } };
|
||||
|
||||
describe("aggregator inventory adapters", () => {
|
||||
it("paginates Arcade, scopes the user and exposed tools, preserves distinct accounts, and strips credentials", async () => {
|
||||
const request = vi.fn(async (path: string) => path.startsWith("/v1/tools") ? { items: [tool, { ...tool, toolkit: { name: "Private" }, qualified_name: "Private.Read" }] }
|
||||
: path.includes("offset=100") ? { items: [account("last"), account("foreign", "u2")], total_count: 102, offset: 0 }
|
||||
: { items: Array.from({ length: 100 }, (_, index) => account(String(index))), total_count: 102, offset: 100 });
|
||||
const apps = await discoverArcadeApps({ request, userId: "u1", gatewayTools: ["Notion_ListPages"] });
|
||||
expect(apps).toHaveLength(1);
|
||||
expect(apps[0].accounts).toHaveLength(101);
|
||||
expect(apps[0].accounts[0]).toMatchObject({ appSlug: "notion", status: "ACTIVE", alias: "Work" });
|
||||
expect(JSON.stringify(apps)).not.toContain("do-not-store");
|
||||
expect(request.mock.calls[0][0]).toContain("user[id]=u1");
|
||||
});
|
||||
it("uses Arcade's next offset after a short page and rejects truncated final pages", async () => {
|
||||
const request = vi.fn(async (path: string) => path.startsWith("/v1/tools") ? { items: [tool], total_count: 1, offset: 0 }
|
||||
: path.includes("offset=1") ? { items: [account("second")], total_count: 2, offset: 0 }
|
||||
: { items: [account("first")], total_count: 2, offset: 1 });
|
||||
expect((await discoverArcadeApps({ request, userId: "u1", gatewayTools: ["Notion.ListPages"] }))[0].accounts).toHaveLength(2);
|
||||
expect(request.mock.calls.some(([path]) => path.includes("offset=1"))).toBe(true);
|
||||
await expect(discoverArcadeApps({ userId: "u1", gatewayTools: ["Notion.ListPages"], request: async path => path.startsWith("/v1/tools")
|
||||
? { items: [tool], total_count: 1, offset: 0 } : { items: [account("one")], total_count: 2, offset: 0 } })).rejects.toThrow("Incomplete");
|
||||
});
|
||||
it("rejects an Arcade partial page rather than returning an authoritative empty inventory", async () => {
|
||||
for (const items of [[], [account("one")]]) await expect(discoverArcadeApps({ userId: "u1", gatewayTools: ["Notion.ListPages"], request: async path => path.startsWith("/v1/tools") ? { items: [tool] } : { items, total: 10 } })).rejects.toThrow("Incomplete");
|
||||
});
|
||||
it("does not claim Arcade authorization from account existence alone", async () => {
|
||||
const apps = await discoverArcadeApps({ userId: "u1", gatewayTools: ["Notion.ListPages"], request: async path => ({ items: path.startsWith("/v1/tools") ? [{ ...tool, requirements: { ...tool.requirements, met: false } }] : [account("1")] }) });
|
||||
expect(apps[0].accounts[0].status).toBe("UNVERIFIED");
|
||||
});
|
||||
it("enumerates Executor pages and uses owner/integration/account identity with honest health", async () => {
|
||||
const call = vi.fn(async (_name, args) => ({ result: { structuredContent: { items: [{ integration: args.offset ? "custom-notion-helper" : "notion", integrationName: "Custom helper", connection: "Work", owner: args.offset ? "user" : "org", identityLabel: "Work", lastHealth: args.offset ? null : { status: "healthy", checkedAt: 1000 }, secret: "never" }], hasMore: !args.offset, nextOffset: args.offset ? null : 50 } } }));
|
||||
const apps = await discoverExecutorApps({ call, toolNames: ["integrations"], managementUrl: "https://executor.example/team/integrations" });
|
||||
expect(apps[0].accounts[0]).toMatchObject({ appSlug: "notion", status: "ACTIVE", healthCheckedAt: "1970-01-01T00:00:01.000Z" });
|
||||
expect(apps[1].accounts[0]).toMatchObject({ appSlug: "executor:custom-notion-helper", status: "UNVERIFIED" });
|
||||
expect(JSON.stringify(apps)).not.toContain("never");
|
||||
expect(call).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("uses fixed read-only code and preserves an upstream workspace management link", async () => {
|
||||
const call = vi.fn(async () => ({ structuredContent: { status: "completed", result: { connections: [{ integration: "notion", name: "Work", owner: "user", lastHealth: { status: "expired" } }], integrations: [{ slug: "notion" }], managementUrls: { notion: "https://self-host.example/my-org/integrations/notion?addAccount=1" } } } }));
|
||||
const apps = await discoverExecutorApps({ call, toolNames: ["execute"] });
|
||||
expect(call).toHaveBeenCalledWith("execute", { code: EXECUTOR_INVENTORY_CODE });
|
||||
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
|
||||
expect(await new AsyncFunction("tools", EXECUTOR_INVENTORY_CODE)({})).toEqual({ discoveryUnavailable: true });
|
||||
expect(apps[0].accounts[0]).toMatchObject({ status: "EXPIRED", managementUrl: "https://self-host.example/my-org/integrations/notion" });
|
||||
});
|
||||
it("rejects unsupported, failed, malformed and truncated Executor inventories", async () => {
|
||||
await expect(discoverExecutorApps({ toolNames: [], call: vi.fn() })).rejects.toThrow("unavailable");
|
||||
await expect(discoverExecutorApps({ toolNames: ["execute"], call: async () => ({ structuredContent: { result: { incompatible: true } } }) })).rejects.toBeInstanceOf(AggregatorDiscoveryUnavailableError);
|
||||
await expect(discoverExecutorApps({ toolNames: ["execute"], call: async () => ({ isError: true }) })).rejects.toThrow("failed");
|
||||
await expect(discoverExecutorApps({ toolNames: ["integrations"], call: async () => ({ items: [], hasMore: true, nextOffset: 0 }) })).rejects.toThrow("Incomplete");
|
||||
expect(() => inventoryPayload({ content: [{ type: "text", text: "No accounts" }] })).toThrow();
|
||||
});
|
||||
it("validates browser destinations without leaking credentials", () => {
|
||||
expect(aggregatorManagementUrl("composio")).toBe("https://dashboard.composio.dev/~/org/connect/apps");
|
||||
for (const url of ["javascript:alert(1)", "https://user:password@executor.example/", "https://executor.example/?api_key=secret"]) expect(aggregatorManagementUrl("executor", url)).toBeNull();
|
||||
expect(aggregatorManagementUrl("arcade", "https://other.example")).toBeNull();
|
||||
expect(aggregatorManagementUrl("executor", "https://executor.example/team/accounts")).toBe("https://executor.example/team/accounts");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,160 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { companies, companyMemberships, connectionGrants, createDb, toolApplications, toolCatalogEntries, toolConnections, toolConnectionAppSnapshots } from "@paperclipai/db";
|
||||
import { toolAccessService } from "../services/tool-access.js";
|
||||
import { secretService } from "../services/secrets.js";
|
||||
import { toolAccessRoutes } from "../routes/tool-access.js";
|
||||
import { errorHandler } from "../middleware/error-handler.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
|
||||
// Optional reuse of the explicitly disposable browser-test cluster on hosts with limited PostgreSQL startup resources.
|
||||
const acceptanceDatabaseUrl = process.env.PAPERCLIP_AGGREGATOR_TEST_DATABASE_URL;
|
||||
if (acceptanceDatabaseUrl && !["127.0.0.1", "localhost"].includes(new URL(acceptanceDatabaseUrl).hostname)) throw new Error("The acceptance database must be local and disposable");
|
||||
const support = acceptanceDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport();
|
||||
if (!support.supported) console.warn(`Managed-account database tests unavailable: ${support.reason}`);
|
||||
(support.supported ? describe : describe.skip)("provider-neutral account sync", () => {
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let cleanup: (() => Promise<void>) | undefined;
|
||||
beforeAll(async () => {
|
||||
if (acceptanceDatabaseUrl) { db = createDb(acceptanceDatabaseUrl); return; }
|
||||
const database = await startEmbeddedPostgresTestDatabase("paperclip-aggregator-sync-"); db = createDb(database.connectionString); cleanup = database.cleanup;
|
||||
}, 90_000);
|
||||
afterAll(async () => { await cleanup?.(); });
|
||||
async function fixture(provider: "arcade" | "executor" = "executor") {
|
||||
const [company] = await db.insert(companies).values({ name: "Aggregator sync test", issuePrefix: randomUUID().slice(0, 6).toUpperCase() }).returning();
|
||||
const userId = randomUUID();
|
||||
await db.insert(companyMemberships).values({ companyId: company.id, principalType: "user", principalId: userId, membershipRole: "admin", status: "active" });
|
||||
const [application] = await db.insert(toolApplications).values({ companyId: company.id, applicationKey: randomUUID(), name: provider, type: "mcp_http", metadata: { sourceTemplateKey: provider } }).returning();
|
||||
const [connection] = await db.insert(toolConnections).values({ companyId: company.id, applicationId: application.id, uid: randomUUID(), name: `${provider} gateway`, transport: "mcp_remote", authKind: "none", credentialPolicy: "shared", status: "active", enabled: true, config: { sourceTemplateKey: provider, url: provider === "arcade" ? "https://api.arcade.dev/mcp/test" : "https://executor.example/mcp", managementUrl: "https://executor.example/team/integrations" } }).returning();
|
||||
await db.insert(connectionGrants).values({ companyId: company.id, connectionId: connection.id, kind: "organization", status: "active", isDefault: true });
|
||||
const names = provider === "executor" ? ["integrations"] : ["Notion.ListPages"];
|
||||
await db.insert(toolCatalogEntries).values(names.map(toolName => ({ companyId: company.id, connectionId: connection.id, name: toolName, toolName, versionHash: "v1", status: "active", riskLevel: "read" as const })));
|
||||
let accounts = [{ integration: "notion", owner: "user", connection: "Work", lastHealth: { status: "healthy", checkedAt: Date.now() } }];
|
||||
let fail = false;
|
||||
let partial = false;
|
||||
const calls: { url: string; method: string; name?: string; authorization?: string }[] = [];
|
||||
const access = toolAccessService(db, { remoteHttpRequest: async (url, init) => {
|
||||
const rpc = init.body ? JSON.parse(String(init.body)) : undefined;
|
||||
calls.push({ url: String(url), method: init.method ?? "GET", name: rpc?.params?.name, authorization: new Headers(init.headers).get("Authorization") ?? undefined });
|
||||
if (rpc?.method === "tools/list") return Response.json({ jsonrpc: "2.0", id: rpc.id, result: { tools: names.map(name => ({ name, inputSchema: { type: "object" } })) } });
|
||||
if (fail) return new Response("upstream error with private token", { status: 401 });
|
||||
if (!rpc) return Response.json({ items: String(url).includes("/v1/tools") ? [{ qualified_name: names[0], toolkit: { name: "Notion" }, requirements: { met: true, authorization: { provider_id: "notion", token_status: "completed" } } }] : [{ id: "arcade-work", provider_id: "notion", user_id: "arcade-user", connection_status: "active", provider_user_info: { email: "Work" } }] });
|
||||
return Response.json({ jsonrpc: "2.0", id: rpc.id, result: { structuredContent: { items: accounts, hasMore: partial, nextOffset: partial ? 0 : null } } });
|
||||
} });
|
||||
return { company, connection, actor: { actorType: "user" as const, actorId: userId }, access, calls, disconnect: () => { accounts = []; }, fail: () => { fail = true; }, partial: () => { partial = true; } };
|
||||
}
|
||||
async function sync(f: Awaited<ReturnType<typeof fixture>>) {
|
||||
await f.access.syncAggregatorApps(f.connection.id, true, f.actor);
|
||||
let result = await f.access.listAggregatorApps(f.connection.id, f.actor);
|
||||
await vi.waitFor(async () => { result = await f.access.listAggregatorApps(f.connection.id, f.actor); expect(result.sync.status).not.toBe("syncing"); }, { timeout: 5000 });
|
||||
return result;
|
||||
}
|
||||
it("replays the account migrations without losing observations or weakening company boundaries", async () => {
|
||||
const f = await fixture();
|
||||
await sync(f);
|
||||
const before = await db.select().from(toolConnectionAppSnapshots).where(eq(toolConnectionAppSnapshots.connectionId, f.connection.id));
|
||||
for (const name of ["0295_public_captain_cross", "0296_stiff_thaddeus_ross"]) {
|
||||
const migration = await readFile(new URL(`../../../packages/db/src/migrations/${name}.sql`, import.meta.url), "utf8");
|
||||
for (const statement of migration.split("--> statement-breakpoint")) await db.execute(sql.raw(statement));
|
||||
}
|
||||
expect(await db.select().from(toolConnectionAppSnapshots).where(eq(toolConnectionAppSnapshots.connectionId, f.connection.id))).toEqual(before);
|
||||
const other = await fixture();
|
||||
await expect(db.insert(toolConnectionAppSnapshots).values({ companyId: other.company.id, connectionId: f.connection.id,
|
||||
userId: other.actor.actorId, credentialKey: "different", toolkit: "notion", status: "connected", accounts: [] })).rejects.toThrow();
|
||||
});
|
||||
it("imports and reconciles Executor accounts without new executable connections or access grants", async () => {
|
||||
const f = await fixture();
|
||||
const grants = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, f.connection.id));
|
||||
expect((await sync(f)).apps[0]).toMatchObject({ provider: "executor", appSlug: "notion", status: "connected" });
|
||||
expect(await db.select().from(toolConnections).where(eq(toolConnections.companyId, f.company.id))).toHaveLength(1);
|
||||
expect(await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, f.connection.id))).toEqual(grants);
|
||||
f.disconnect();
|
||||
expect((await sync(f)).apps.flatMap(app => app.accounts)).toHaveLength(0);
|
||||
});
|
||||
it.each(["fail", "partial"] as const)("retains stale observations after %s and isolates users, gateways and credential changes", async failure => {
|
||||
const f = await fixture(); await sync(f); f[failure]();
|
||||
const result = await sync(f);
|
||||
expect(result.sync.status).toBe("error");
|
||||
expect(result.apps[0].accounts).toHaveLength(1);
|
||||
expect(result.apps[0].errorAt).toBeTruthy();
|
||||
expect(JSON.stringify(result)).not.toContain("private token");
|
||||
expect((await f.access.listAggregatorApps(f.connection.id, { actorType: "user", actorId: randomUUID() })).apps).toHaveLength(0);
|
||||
const other = await fixture(); expect((await other.access.listAggregatorApps(other.connection.id, other.actor)).apps).toHaveLength(0);
|
||||
await db.update(toolConnections).set({ config: { ...f.connection.config, url: "https://executor.example/rotated" } }).where(eq(toolConnections.id, f.connection.id));
|
||||
expect((await f.access.listAggregatorApps(f.connection.id, f.actor)).apps).toHaveLength(0);
|
||||
});
|
||||
it("reports unsupported Executor inventory without trying arbitrary tools", async () => {
|
||||
const f = await fixture(); await sync(f); f.calls.length = 0; await db.update(toolCatalogEntries).set({ status: "inactive" }).where(eq(toolCatalogEntries.connectionId, f.connection.id));
|
||||
expect((await f.access.syncAggregatorApps(f.connection.id, true, f.actor)).discovery.availability).toBe("unsupported");
|
||||
expect(f.calls).toHaveLength(0);
|
||||
expect((await f.access.listAggregatorApps(f.connection.id, f.actor)).apps[0].freshness).toBe("stale");
|
||||
});
|
||||
it("reuses an existing Arcade API key and secret-backed user header without extra sync setup", async () => {
|
||||
const f = await fixture("arcade");
|
||||
const key = await secretService(db).create(f.company.id, { name: "Arcade project", provider: "local_encrypted", value: "existing-key" }, { userId: f.actor.actorId });
|
||||
const user = await secretService(db).create(f.company.id, { name: "Arcade user", provider: "local_encrypted", value: "arcade-user" }, { userId: f.actor.actorId });
|
||||
await db.update(toolConnections).set({ authKind: "api_key", credentialRefs: [
|
||||
{ name: "authorization", secretId: key.id, placement: "header", key: "Authorization", prefix: "Bearer " },
|
||||
{ name: "headers.Arcade-User-ID", secretId: user.id, placement: "header", key: "Arcade-User-ID", prefix: "" },
|
||||
], credentialSecretRefs: [
|
||||
{ secretId: key.id, configPath: "credentials.authorization", versionSelector: "latest" },
|
||||
{ secretId: user.id, configPath: "headers.Arcade-User-ID", versionSelector: "latest" },
|
||||
] }).where(eq(toolConnections.id, f.connection.id));
|
||||
for (const [secretId, configPath] of [[key.id, "credentials.authorization"], [user.id, "headers.Arcade-User-ID"]]) await secretService(db).createBinding({ companyId: f.company.id, secretId, targetType: "tool_connection", targetId: f.connection.id, configPath });
|
||||
expect((await f.access.listAggregatorApps(f.connection.id, f.actor)).discovery.availability).toBe("available");
|
||||
expect((await sync(f)).apps[0]).toMatchObject({ provider: "arcade", appSlug: "notion" });
|
||||
expect(f.calls.filter(call => call.method === "GET").every(call => call.authorization === "Bearer existing-key")).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps optional Arcade discovery credentials in the vault, uses them only for discovery, and invalidates rotation", async () => {
|
||||
const f = await fixture("arcade");
|
||||
expect((await f.access.listAggregatorApps(f.connection.id, f.actor)).discovery.availability).toBe("setup_required");
|
||||
await f.access.configureArcadeDiscovery(f.connection.id, { apiKey: "project-discovery-key", userId: "arcade-user" }, f.actor);
|
||||
const result = await sync(f);
|
||||
expect(result.apps[0]).toMatchObject({ provider: "arcade", appSlug: "notion" });
|
||||
const [saved] = await db.select().from(toolConnections).where(eq(toolConnections.id, f.connection.id));
|
||||
expect(JSON.stringify(saved)).not.toContain("project-discovery-key");
|
||||
expect(saved.credentialSecretRefs).toHaveLength(0);
|
||||
expect(f.calls.filter(call => call.method === "POST").every(call => call.authorization !== "Bearer project-discovery-key")).toBe(true);
|
||||
expect(f.calls.filter(call => call.method === "GET").every(call => call.authorization === "Bearer project-discovery-key")).toBe(true);
|
||||
const metadata = (saved.config.aggregatorDiscovery as Record<string, { secretId: string }>)[f.actor.actorId];
|
||||
await secretService(db).rotateCurrentUserSecretValue(f.company.id, f.actor.actorId, metadata.secretId, { value: "rotated-discovery-key" }, { userId: f.actor.actorId });
|
||||
expect((await f.access.listAggregatorApps(f.connection.id, f.actor)).apps).toHaveLength(0);
|
||||
expect(await db.select().from(toolConnectionAppSnapshots).where(eq(toolConnectionAppSnapshots.connectionId, f.connection.id))).toHaveLength(1);
|
||||
expect((await sync(f)).apps[0].accounts).toHaveLength(1);
|
||||
expect(f.calls.filter(call => call.method === "GET").at(-1)?.authorization).toBe("Bearer rotated-discovery-key");
|
||||
});
|
||||
it("rejects optional sync configuration by ordinary members and agents", async () => {
|
||||
const f = await fixture("arcade");
|
||||
const memberId = randomUUID();
|
||||
await db.insert(companyMemberships).values({ companyId: f.company.id, principalType: "user", principalId: memberId, membershipRole: "member", status: "active" });
|
||||
const app = express(); app.use(express.json());
|
||||
app.use((req, _res, next) => { req.actor = req.headers["x-test-agent"] ? { type: "agent", agentId: randomUUID(), companyId: f.company.id } : { type: "board", userId: memberId, source: "session", isInstanceAdmin: false, companyIds: [f.company.id] }; next(); });
|
||||
app.use("/api", toolAccessRoutes(db)); app.use(errorHandler);
|
||||
for (const agent of [false, true]) {
|
||||
const response = await request(app).put(`/api/tool-connections/${f.connection.id}/aggregator/discovery`).set("x-test-agent", agent ? "yes" : "").send({ apiKey: "not-saved", userId: "arcade-user" });
|
||||
expect(response.status).toBe(403);
|
||||
}
|
||||
const [saved] = await db.select().from(toolConnections).where(eq(toolConnections.id, f.connection.id));
|
||||
expect(saved.config.aggregatorDiscovery).toBeUndefined();
|
||||
});
|
||||
|
||||
it("enforces company membership and connection-manager access on all generic endpoints", async () => {
|
||||
const f = await fixture("arcade");
|
||||
const app = express(); app.use(express.json());
|
||||
let viewingUser = randomUUID();
|
||||
app.use((req, _res, next) => { req.actor = { type: "board", userId: viewingUser, source: "session", isInstanceAdmin: false, companyIds: viewingUser === f.actor.actorId ? [f.company.id] : [] }; next(); });
|
||||
app.use("/api", toolAccessRoutes(db)); app.use(errorHandler);
|
||||
for (const path of ["/aggregator/apps", "/aggregator/apps/sync", "/aggregator/apps/refresh", "/aggregator/discovery"]) {
|
||||
const endpoint = `/api/tool-connections/${f.connection.id}${path}`;
|
||||
const response = path.endsWith("discovery") ? await request(app).put(endpoint).send({ apiKey: "no", userId: "no" }) : path.endsWith("apps") ? await request(app).get(endpoint) : await request(app).post(endpoint).send({});
|
||||
expect([403, 404]).toContain(response.status);
|
||||
}
|
||||
viewingUser = f.actor.actorId;
|
||||
await request(app).get(`/api/tool-connections/${f.connection.id}/aggregator/apps`).expect(200).expect("Cache-Control", "private, no-store");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,337 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, companies, companyMemberships, connectionGrants, createDb, issues, toolApplications, toolCatalogEntries, toolConnections, toolConnectionAppSnapshots } from "@paperclipai/db";
|
||||
import { composioAppSetupSchema } from "@paperclipai/shared";
|
||||
import { composioAppAccounts, composioAppSetupResult } from "../services/composio-app-setup.js";
|
||||
import { toolAccessService } from "../services/tool-access.js";
|
||||
import { toolAccessPolicyService } from "../services/tool-access-policy.js";
|
||||
import { toolAccessRoutes } from "../routes/tool-access.js";
|
||||
import { errorHandler } from "../middleware/error-handler.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
|
||||
describe("Composio app authorization evidence", () => {
|
||||
it("completes app setup without an agent selection", () => {
|
||||
expect(composioAppSetupSchema.parse({ action: "complete" })).toEqual({ action: "complete" });
|
||||
expect(composioAppSetupSchema.safeParse({ action: "complete", agentId: randomUUID() }).success).toBe(false);
|
||||
});
|
||||
it("keeps only the requested app's account identities and never treats missing or malformed evidence as an empty list", () => {
|
||||
const response = { results: { gmail: { accounts: [{ id: "gmail", status: "ACTIVE" }] }, circleback_mcp: { accounts: [{ id: "ca_1", alias: "Work", status: "active", is_default: true, access_token: "secret" }] } } };
|
||||
expect(composioAppAccounts(response, "circleback_mcp")).toEqual([{ id: "ca_1", alias: "Work", status: "ACTIVE", isDefault: true }]);
|
||||
expect(composioAppAccounts(response, "missing")).toBeUndefined();
|
||||
expect(composioAppAccounts({ circleback_mcp: { accounts: [] } }, "circleback_mcp")).toEqual([]);
|
||||
expect(composioAppAccounts({ circleback_mcp: { accounts: [{ status: "active" }] } }, "circleback_mcp")).toBeUndefined();
|
||||
expect(() => composioAppAccounts({ circleback_mcp: { error: "expired", accounts: [] } }, "circleback_mcp")).toThrow("could not check");
|
||||
});
|
||||
it("accepts a hosted link and only verifies the requested toolkit", () => {
|
||||
expect(composioAppSetupResult({ results: { circleback_mcp: { redirect_url: "https://connect.composio.dev/link/test" } } }, "circleback_mcp"))
|
||||
.toEqual({ status: "authorization_required", authorizationUrl: "https://connect.composio.dev/link/test" });
|
||||
expect(composioAppSetupResult({ results: { gmail: { status: "ACTIVE" }, circleback_mcp: { accounts: [{ status: "INITIATED" }] } } }, "circleback_mcp"))
|
||||
.toEqual({ status: "not_connected" });
|
||||
expect(composioAppSetupResult({ result: { content: [{ type: "text", text: JSON.stringify({ results: { circleback_mcp: { accounts: [{ status: "ACTIVE" }] } } }) }] } }, "circleback_mcp"))
|
||||
.toEqual({ status: "connected" });
|
||||
});
|
||||
it("rejects provider failures and untrusted handoff URLs", () => {
|
||||
expect(() => composioAppSetupResult({ isError: true }, "circleback_mcp")).toThrow("could not configure");
|
||||
expect(composioAppSetupResult({ redirect_url: "https://untrusted.example/link/test" }, "circleback_mcp")).toEqual({ status: "not_connected" });
|
||||
});
|
||||
it("recognizes the lowercase account status returned by the live Composio gateway", () => {
|
||||
const response = { result: { content: [{ type: "text", text: JSON.stringify({
|
||||
data: { results: { circleback_mcp: { toolkit: "circleback_mcp", status: "active", accounts: [{ status: "active", is_default: true }] } } },
|
||||
error: null, successful: true,
|
||||
}) }], isError: false } };
|
||||
expect(composioAppSetupResult(response, "circleback_mcp")).toEqual({ status: "connected" });
|
||||
expect(composioAppSetupResult(response, "gmail")).toEqual({ status: "not_connected" });
|
||||
});
|
||||
});
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
(support.supported ? describe : describe.skip)("direct Composio setup", () => {
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let cleanup: (() => Promise<void>) | undefined;
|
||||
beforeAll(async () => {
|
||||
const database = await startEmbeddedPostgresTestDatabase("paperclip-composio-setup-");
|
||||
db = createDb(database.connectionString);
|
||||
cleanup = database.cleanup;
|
||||
}, 20_000);
|
||||
afterAll(async () => { await cleanup?.(); });
|
||||
|
||||
async function fixture(syncToolkits: string[] = ["circleback_mcp", "notion", "hubspot"]) {
|
||||
const [company] = await db.insert(companies).values({ name: "Composio direct setup", issuePrefix: randomUUID().slice(0, 6).toUpperCase() }).returning();
|
||||
const userId = randomUUID();
|
||||
await db.insert(companyMemberships).values({ companyId: company.id, principalType: "user", principalId: userId, membershipRole: "admin", status: "active" });
|
||||
const [agent, otherAgent] = await db.insert(agents).values(["Default agent", "Other agent"].map(name => ({ companyId: company.id, name, role: "general" as const, status: "idle" as const, adapterType: "codex_local" }))).returning();
|
||||
const [app] = await db.insert(toolApplications).values({ companyId: company.id, applicationKey: randomUUID(), name: "Composio", type: "mcp_http", metadata: { sourceTemplateKey: "composio" } }).returning();
|
||||
const [connection] = await db.insert(toolConnections).values({ companyId: company.id, applicationId: app.id, uid: randomUUID(), name: "Composio account", transport: "mcp_remote", authKind: "none", credentialPolicy: "shared", status: "active", enabled: true, config: { sourceTemplateKey: "composio", url: "https://connect.composio.dev/mcp" } }).returning();
|
||||
await db.insert(connectionGrants).values({ companyId: company.id, connectionId: connection.id, kind: "organization", isDefault: true, status: "active" });
|
||||
const catalog = await db.insert(toolCatalogEntries).values([
|
||||
["COMPOSIO_SEARCH_TOOLS", "read"], ["COMPOSIO_GET_TOOL_SCHEMAS", "read"], ["COMPOSIO_MULTI_EXECUTE_TOOL", "destructive"], ["COMPOSIO_MANAGE_CONNECTIONS", "destructive"],
|
||||
].map(([toolName, riskLevel]) => ({ companyId: company.id, connectionId: connection.id, name: toolName, toolName, versionHash: "v1", status: "active" as const, riskLevel: riskLevel as "read" | "destructive" }))).returning();
|
||||
const accountId = randomUUID();
|
||||
let accounts = [{ id: accountId, alias: "Work", status: "initiated", is_default: true, access_token: "never-store-this-token" }];
|
||||
let onList = async () => {};
|
||||
let listResult: unknown = undefined;
|
||||
let failedToolkit: string | undefined;
|
||||
let mutationStatus = 200;
|
||||
let applyMutation = true;
|
||||
const operations: string[] = [];
|
||||
const batches: { name: string; action: string; account_id?: string; alias?: string }[][] = [];
|
||||
const access = toolAccessService(db, { composioAppToolkits: syncToolkits, remoteHttpRequest: async (_url, init) => {
|
||||
const request = JSON.parse(String(init.body));
|
||||
const toolkits = request.params.arguments.toolkits;
|
||||
expect(request.params.name).toBe("COMPOSIO_MANAGE_CONNECTIONS");
|
||||
batches.push(toolkits);
|
||||
const results: Record<string, unknown> = {};
|
||||
for (const toolkit of toolkits) {
|
||||
operations.push(toolkit.action);
|
||||
if (toolkit.action === "list") await onList();
|
||||
else if (mutationStatus !== 200) return new Response("unconfirmed", { status: mutationStatus });
|
||||
if (applyMutation && toolkit.name === "circleback_mcp") {
|
||||
if (toolkit.action === "rename") accounts = accounts.map(account => account.id === toolkit.account_id ? { ...account, alias: toolkit.alias } : account);
|
||||
if (toolkit.action === "remove") accounts = accounts.filter(account => account.id !== toolkit.account_id);
|
||||
}
|
||||
results[toolkit.name] = toolkit.name === failedToolkit ? { toolkit: toolkit.name, accounts: [{ status: "ACTIVE" }] }
|
||||
: toolkit.action === "add" ? { redirect_url: "https://connect.composio.dev/link/test" }
|
||||
: listResult ?? { toolkit: toolkit.name, accounts: toolkit.name === "circleback_mcp" ? accounts : [] };
|
||||
}
|
||||
return Response.json({ jsonrpc: "2.0", id: request.id, result: { structuredContent: { data: { results } } } });
|
||||
} });
|
||||
return { company, agent, otherAgent, connection, catalog, access, operations, batches, accountId, actor: { actorType: "user" as const, actorId: userId },
|
||||
activate: () => { accounts = accounts.map(account => ({ ...account, status: "active" })); },
|
||||
disconnect: () => { accounts = []; },
|
||||
setListResult: (result: unknown) => { listResult = result; },
|
||||
failToolkit: (toolkit: string) => { failedToolkit = toolkit; },
|
||||
setMutationStatus: (status: number) => { mutationStatus = status; },
|
||||
refuseMutation: () => { applyMutation = false; },
|
||||
onList: (callback: () => Promise<void>) => { onList = callback; } };
|
||||
|
||||
}
|
||||
|
||||
async function configureAccess(f: Awaited<ReturnType<typeof fixture>>, agentId?: string) {
|
||||
await f.access.putConnectionInstalls(f.connection.id, { installs: agentId
|
||||
? [{ targetType: "agent", targetId: agentId }] : [{ targetType: "company", targetId: f.company.id }] }, f.actor);
|
||||
await f.access.finishGalleryAppConnection(f.company.id, f.connection.id, {
|
||||
enabledCatalogEntryIds: f.catalog.map(tool => tool.id),
|
||||
askFirstCatalogEntryIds: f.catalog.filter(tool => ["COMPOSIO_MULTI_EXECUTE_TOOL", "COMPOSIO_MANAGE_CONNECTIONS"].includes(tool.toolName)).map(tool => tool.id),
|
||||
access: agentId ? { agentIds: [agentId] } : "all_agents",
|
||||
}, f.actor);
|
||||
}
|
||||
|
||||
it("generates and verifies app sign-in without a task or new access grants, preserving company-wide gateway defaults", async () => {
|
||||
const f = await fixture();
|
||||
await configureAccess(f);
|
||||
const grants = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, f.connection.id));
|
||||
const installs = await f.access.listConnectionInstalls(f.connection.id, f.company.id);
|
||||
const before = (await f.access.getEffectiveProfilesForAgent(f.company.id, f.agent.id)).allowedTools;
|
||||
expect(await f.access.setupComposioApp(f.connection.id, "circleback_mcp", { action: "start" }, f.actor)).toMatchObject({ status: "authorization_required" });
|
||||
expect(f.operations).toEqual(["list", "add"]);
|
||||
expect(await db.select().from(issues).where(eq(issues.companyId, f.company.id))).toHaveLength(0);
|
||||
await expect(f.access.setupComposioApp(f.connection.id, "circleback_mcp", { action: "complete" }, f.actor)).rejects.toThrow("Finish connecting");
|
||||
expect((await f.access.getEffectiveProfilesForAgent(f.company.id, f.agent.id)).allowedTools).toEqual(before);
|
||||
f.activate();
|
||||
await f.access.setupComposioApp(f.connection.id, "circleback_mcp", { action: "complete" }, f.actor);
|
||||
expect((await f.access.getEffectiveProfilesForAgent(f.company.id, f.agent.id)).allowedTools).toEqual(before);
|
||||
expect((await f.access.getEffectiveProfilesForAgent(f.company.id, f.otherAgent.id)).allowedTools.map(t => t.toolName).sort()).toEqual(f.catalog.map(t => t.toolName).sort());
|
||||
expect(await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, f.connection.id))).toEqual(grants);
|
||||
expect(await f.access.listConnectionInstalls(f.connection.id, f.company.id)).toEqual(installs);
|
||||
const tool = f.catalog.find(t => t.toolName === "COMPOSIO_MULTI_EXECUTE_TOOL")!;
|
||||
const decision = await toolAccessPolicyService(db).decide({ companyId: f.company.id, actor: { actorType: "agent", actorId: f.agent.id, agentId: f.agent.id }, request: { connectionId: f.connection.id, catalogEntryId: tool.id, toolName: tool.toolName, arguments: {} } });
|
||||
expect(decision.decision).toBe("require_approval");
|
||||
expect(f.operations.filter(action => action === "add")).toHaveLength(1);
|
||||
});
|
||||
it("does not create another link for an active account and rejects unknown toolkits", async () => {
|
||||
const f = await fixture();
|
||||
f.activate();
|
||||
expect(await f.access.setupComposioApp(f.connection.id, "circleback_mcp", { action: "start" }, f.actor)).toEqual({ status: "connected" });
|
||||
expect(f.operations).toEqual(["list"]);
|
||||
await expect(f.access.setupComposioApp(f.connection.id, "invented", { action: "start" }, f.actor)).rejects.toThrow("not in the catalog");
|
||||
});
|
||||
it("keeps meta-tool execution behind approval even if its catalog risk is read", async () => {
|
||||
const f = await fixture();
|
||||
const tool = f.catalog.find(t => t.toolName === "COMPOSIO_MULTI_EXECUTE_TOOL")!;
|
||||
await db.update(toolCatalogEntries).set({ riskLevel: "read" }).where(eq(toolCatalogEntries.id, tool.id));
|
||||
await configureAccess(f);
|
||||
f.activate();
|
||||
await f.access.setupComposioApp(f.connection.id, "circleback_mcp", { action: "complete" }, f.actor);
|
||||
const decision = await toolAccessPolicyService(db).decide({ companyId: f.company.id, actor: { actorType: "agent", actorId: f.agent.id, agentId: f.agent.id }, request: { connectionId: f.connection.id, catalogEntryId: tool.id, toolName: tool.toolName, arguments: {} } });
|
||||
expect(decision.decision).toBe("require_approval");
|
||||
});
|
||||
it("does not complete app setup if the gateway is disabled while checking Composio", async () => {
|
||||
const f = await fixture();
|
||||
f.activate();
|
||||
f.onList(async () => { await db.update(toolConnections).set({ enabled: false }).where(eq(toolConnections.id, f.connection.id)); });
|
||||
await expect(f.access.setupComposioApp(f.connection.id, "circleback_mcp", { action: "complete" }, f.actor)).rejects.toThrow("no longer active");
|
||||
expect((await f.access.getEffectiveProfilesForAgent(f.company.id, f.agent.id)).allowedTools).toHaveLength(0);
|
||||
});
|
||||
it("preserves a saved gateway's restricted access when another app is connected", async () => {
|
||||
const f = await fixture();
|
||||
await configureAccess(f, f.agent.id);
|
||||
const before = (await f.access.getEffectiveProfilesForAgent(f.company.id, f.agent.id)).allowedTools;
|
||||
f.activate();
|
||||
await f.access.setupComposioApp(f.connection.id, "circleback_mcp", { action: "complete" }, f.actor);
|
||||
expect((await f.access.getEffectiveProfilesForAgent(f.company.id, f.agent.id)).allowedTools).toEqual(before);
|
||||
expect((await f.access.getEffectiveProfilesForAgent(f.company.id, f.otherAgent.id)).allowedTools).toHaveLength(0);
|
||||
});
|
||||
it("rejects agents, non-managers, and other companies before calling Composio", async () => {
|
||||
const f = await fixture();
|
||||
const userId = randomUUID();
|
||||
await db.insert(companyMemberships).values({ companyId: f.company.id, principalType: "user", principalId: userId, membershipRole: "member", status: "active" });
|
||||
let providerCalls = 0;
|
||||
const member: Express.Request["actor"] = { type: "board", userId, source: "session", isInstanceAdmin: false, companyIds: [f.company.id], memberships: [{ companyId: f.company.id, membershipRole: "member", status: "active" }] };
|
||||
const actors: [Express.Request["actor"], number][] = [
|
||||
[member, 403],
|
||||
[{ ...member, companyIds: [randomUUID()], memberships: [] }, 404],
|
||||
[{ type: "agent", agentId: f.agent.id, companyId: f.company.id, source: "agent_key" }, 403],
|
||||
];
|
||||
for (const [actor, status] of actors) {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => { req.actor = actor; next(); });
|
||||
app.use("/api", toolAccessRoutes(db, { remoteHttpRequest: async () => { providerCalls++; throw new Error("Must not reach provider"); } }));
|
||||
app.use(errorHandler);
|
||||
await request(app).post(`/api/tool-connections/${f.connection.id}/composio/apps/circleback_mcp/setup`).send({ action: "start" }).expect(status);
|
||||
await request(app).get(`/api/tool-connections/${f.connection.id}/composio/apps`).expect(status);
|
||||
await request(app).post(`/api/tool-connections/${f.connection.id}/composio/apps/sync`).send({ force: true }).expect(status);
|
||||
await request(app).post(`/api/tool-connections/${f.connection.id}/composio/apps/refresh`).send({ toolkits: ["circleback_mcp"] }).expect(status);
|
||||
await request(app).post(`/api/tool-connections/${f.connection.id}/composio/apps/circleback_mcp/accounts`).send({ action: "remove", accountId: f.accountId }).expect(status);
|
||||
}
|
||||
expect(providerCalls).toBe(0);
|
||||
});
|
||||
it("persists safe observations per user and gateway, and refreshes known apps without creating accounts", async () => {
|
||||
const f = await fixture();
|
||||
f.activate();
|
||||
const result = await f.access.refreshComposioApps(f.connection.id, ["circleback_mcp", "hubspot"], f.actor);
|
||||
expect(result.apps.find(app => app.toolkit === "circleback_mcp")).toMatchObject({ connectionId: f.connection.id, status: "connected", accounts: [{ id: f.accountId, alias: "Work", status: "ACTIVE" }] });
|
||||
expect(JSON.stringify(await db.select().from(toolConnectionAppSnapshots).where(eq(toolConnectionAppSnapshots.connectionId, f.connection.id)))).not.toContain("never-store-this-token");
|
||||
expect((await f.access.listComposioApps(f.connection.id, { ...f.actor, actorId: randomUUID() })).apps).toEqual([]);
|
||||
f.operations.length = 0;
|
||||
f.disconnect();
|
||||
const refreshed = await f.access.refreshComposioApps(f.connection.id, [], f.actor);
|
||||
expect(f.operations).toEqual(["list"]);
|
||||
expect(refreshed.apps.find(app => app.toolkit === "circleback_mcp")).toMatchObject({ status: "not_connected", accounts: [] });
|
||||
expect((await f.access.getEffectiveProfilesForAgent(f.company.id, f.agent.id)).allowedTools).toEqual([]);
|
||||
});
|
||||
it("rechecks apps from earlier direct setup and hides observations after a gateway identity changes", async () => {
|
||||
const f = await fixture();
|
||||
f.activate();
|
||||
await f.access.setupComposioApp(f.connection.id, "circleback_mcp", { action: "start" }, f.actor);
|
||||
await db.delete(toolConnectionAppSnapshots).where(eq(toolConnectionAppSnapshots.connectionId, f.connection.id));
|
||||
expect((await f.access.refreshComposioApps(f.connection.id, [], f.actor)).apps).toHaveLength(1);
|
||||
await db.update(toolConnections).set({ config: { ...f.connection.config, url: "https://connect.composio.dev/other-mcp" } }).where(eq(toolConnections.id, f.connection.id));
|
||||
expect((await f.access.listComposioApps(f.connection.id, f.actor)).apps).toEqual([]);
|
||||
});
|
||||
async function finishSync(f: Awaited<ReturnType<typeof fixture>>) {
|
||||
await vi.waitFor(async () => expect((await f.access.listComposioApps(f.connection.id, f.actor)).sync.status).not.toBe("syncing"), { timeout: 10_000 });
|
||||
return f.access.listComposioApps(f.connection.id, f.actor);
|
||||
}
|
||||
|
||||
it("discovers already connected apps across the catalog without a visible-page filter or access changes", async () => {
|
||||
const f = await fixture(); f.activate();
|
||||
const grants = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, f.connection.id));
|
||||
await f.access.syncComposioApps(f.connection.id, false, f.actor);
|
||||
const result = await finishSync(f);
|
||||
expect(result.sync).toMatchObject({ status: "ready", checked: 3, total: 3, failed: 0, coverage: "supported_catalog" });
|
||||
expect(result.apps.find(app => app.toolkit === "circleback_mcp")).toMatchObject({ status: "connected", errorAt: null });
|
||||
expect(f.batches.flat().map(tool => tool.name)).toEqual(["circleback_mcp", "notion", "hubspot"]);
|
||||
expect(f.operations.every(action => action === "list")).toBe(true);
|
||||
expect(await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, f.connection.id))).toEqual(grants);
|
||||
expect(await db.select().from(issues).where(eq(issues.companyId, f.company.id))).toHaveLength(0);
|
||||
await f.access.syncComposioApps(f.connection.id, false, f.actor);
|
||||
expect(f.operations).toHaveLength(3); // Fresh inventory does not start another scan.
|
||||
f.disconnect();
|
||||
await f.access.syncComposioApps(f.connection.id, true, f.actor);
|
||||
expect((await finishSync(f)).apps.find(app => app.toolkit === "circleback_mcp")).toMatchObject({ status: "not_connected", accounts: [] });
|
||||
});
|
||||
|
||||
it("shares a lease between concurrent syncs and bounds provider batches", async () => {
|
||||
const { COMPOSIO_APP_TOOLKITS } = await import("@paperclipai/shared/aggregator-app-catalog");
|
||||
const names = ["circleback_mcp", ...COMPOSIO_APP_TOOLKITS.filter(name => name !== "circleback_mcp").slice(0, 35)];
|
||||
const f = await fixture(names); f.activate();
|
||||
let release!: () => void;
|
||||
const held = new Promise<void>(resolve => { release = resolve; });
|
||||
f.onList(() => held);
|
||||
await Promise.all([f.access.syncComposioApps(f.connection.id, true, f.actor), f.access.syncComposioApps(f.connection.id, true, f.actor)]);
|
||||
expect(f.batches).toHaveLength(1);
|
||||
release();
|
||||
const result = await finishSync(f);
|
||||
expect(result.sync).toMatchObject({ status: "ready", total: 36, checked: 36 });
|
||||
expect(f.batches.map(batch => batch.length)).toEqual([32, 4]);
|
||||
expect(new Set(f.batches.flat().map(tool => tool.name)).size).toBe(36);
|
||||
});
|
||||
|
||||
it("keeps failed account observations unverified and restores them after a successful sync", async () => {
|
||||
const f = await fixture(); f.activate();
|
||||
await f.access.syncComposioApps(f.connection.id, true, f.actor); await finishSync(f);
|
||||
f.setListResult({ accounts: [{ status: "ACTIVE" }] });
|
||||
await f.access.syncComposioApps(f.connection.id, true, f.actor);
|
||||
const failed = await finishSync(f);
|
||||
expect(failed.sync.status).toBe("error");
|
||||
expect(failed.apps.find(app => app.toolkit === "circleback_mcp")).toMatchObject({ status: "connected", accounts: [{ id: f.accountId }] });
|
||||
expect(failed.apps.find(app => app.toolkit === "circleback_mcp")?.errorAt).toBeTruthy();
|
||||
f.setListResult(undefined);
|
||||
await f.access.syncComposioApps(f.connection.id, true, f.actor);
|
||||
expect((await finishSync(f)).apps.find(app => app.toolkit === "circleback_mcp")?.errorAt).toBeNull();
|
||||
});
|
||||
|
||||
it("reports an incomplete sync when a toolkit without prior accounts fails", async () => {
|
||||
const f = await fixture(); f.activate(); f.failToolkit("hubspot");
|
||||
await f.access.syncComposioApps(f.connection.id, true, f.actor);
|
||||
const result = await finishSync(f);
|
||||
expect(result.sync).toMatchObject({ status: "error", checked: 3, total: 3, failed: 1 });
|
||||
expect(result.sync.error).toBeTruthy();
|
||||
expect(result.apps.find(app => app.toolkit === "circleback_mcp")?.accounts[0].id).toBe(f.accountId);
|
||||
expect(result.apps.find(app => app.toolkit === "hubspot")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects observations when credentials change while a provider request is in flight", async () => {
|
||||
const f = await fixture(); f.activate();
|
||||
f.onList(async () => { await db.update(toolConnections).set({ config: { ...f.connection.config, url: "https://connect.composio.dev/replaced" } }).where(eq(toolConnections.id, f.connection.id)); });
|
||||
await f.access.syncComposioApps(f.connection.id, true, f.actor);
|
||||
await vi.waitFor(() => expect(f.operations.length).toBeGreaterThan(0));
|
||||
await vi.waitFor(async () => expect((await f.access.listComposioApps(f.connection.id, f.actor)).sync.status).toBe("idle"));
|
||||
expect((await f.access.listComposioApps(f.connection.id, f.actor)).apps).toEqual([]);
|
||||
});
|
||||
|
||||
it("renames and removes only a verified account in the selected toolkit, and confirms both changes", async () => {
|
||||
const f = await fixture(); f.activate();
|
||||
const grants = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, f.connection.id));
|
||||
await expect(f.access.manageComposioAppAccount(f.connection.id, "hubspot", { action: "remove", accountId: f.accountId }, f.actor)).rejects.toThrow("no longer available");
|
||||
expect(f.operations).toEqual(["list"]);
|
||||
const renamed = await f.access.manageComposioAppAccount(f.connection.id, "circleback_mcp", { action: "rename", accountId: f.accountId, alias: "Meetings" }, f.actor);
|
||||
expect(renamed.apps.find(app => app.toolkit === "circleback_mcp")?.accounts[0].alias).toBe("Meetings");
|
||||
expect(f.batches.some(batch => batch.some(op => op.action === "rename" && op.account_id === f.accountId && op.alias === "Meetings"))).toBe(true);
|
||||
const removed = await f.access.manageComposioAppAccount(f.connection.id, "circleback_mcp", { action: "remove", accountId: f.accountId }, f.actor);
|
||||
expect(removed.apps.find(app => app.toolkit === "circleback_mcp")).toMatchObject({ status: "not_connected", accounts: [] });
|
||||
expect((await db.select().from(toolConnections).where(eq(toolConnections.id, f.connection.id)))[0]).toMatchObject({ status: "active", enabled: true });
|
||||
expect(await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, f.connection.id))).toEqual(grants);
|
||||
});
|
||||
it("adds another account without a task or an agent grant, even when an account is already active", async () => {
|
||||
const f = await fixture(); f.activate();
|
||||
const result = await f.access.manageComposioAppAccount(f.connection.id, "circleback_mcp", { action: "add" }, f.actor);
|
||||
expect(result.authorizationUrl).toBe("https://connect.composio.dev/link/test");
|
||||
expect(f.operations).toEqual(["add"]);
|
||||
expect(await db.select().from(issues).where(eq(issues.companyId, f.company.id))).toHaveLength(0);
|
||||
expect((await f.access.getEffectiveProfilesForAgent(f.company.id, f.agent.id)).allowedTools).toEqual([]);
|
||||
});
|
||||
it("retains previous observations when a list result is incomplete or fails", async () => {
|
||||
const f = await fixture(); f.activate();
|
||||
await f.access.refreshComposioApps(f.connection.id, ["circleback_mcp"], f.actor);
|
||||
f.setListResult({ toolkit: "circleback_mcp", accounts: [{ status: "ACTIVE" }] });
|
||||
await expect(f.access.refreshComposioApps(f.connection.id, ["circleback_mcp"], f.actor)).rejects.toThrow("complete account list");
|
||||
expect((await f.access.listComposioApps(f.connection.id, f.actor)).apps[0].accounts[0].id).toBe(f.accountId);
|
||||
f.setListResult({ toolkit: "circleback_mcp", error: "expired", accounts: [] });
|
||||
await expect(f.access.refreshComposioApps(f.connection.id, ["circleback_mcp"], f.actor)).rejects.toThrow("could not check");
|
||||
expect((await f.access.listComposioApps(f.connection.id, f.actor)).apps[0].status).toBe("connected");
|
||||
});
|
||||
it("never retries an uncertain mutation or reports an unconfirmed rename as success", async () => {
|
||||
const f = await fixture(); f.activate();
|
||||
f.setMutationStatus(400);
|
||||
await expect(f.access.manageComposioAppAccount(f.connection.id, "circleback_mcp", { action: "remove", accountId: f.accountId }, f.actor)).rejects.toThrow("has not confirmed");
|
||||
expect(f.operations.filter(op => op === "remove")).toHaveLength(1);
|
||||
f.setMutationStatus(200); f.refuseMutation();
|
||||
await expect(f.access.manageComposioAppAccount(f.connection.id, "circleback_mcp", { action: "rename", accountId: f.accountId, alias: "Meetings" }, f.actor)).rejects.toThrow("has not confirmed");
|
||||
expect((await f.access.listComposioApps(f.connection.id, f.actor)).apps[0].accounts[0].alias).toBe("Work");
|
||||
});
|
||||
});
|
||||
@@ -24,6 +24,8 @@ import {
|
||||
toolConnections,
|
||||
toolProfileBindings,
|
||||
toolProfiles,
|
||||
toolPolicies,
|
||||
toolProfileEntries,
|
||||
userSecretDefinitions,
|
||||
} from "@paperclipai/db";
|
||||
import type { RuntimeToolsTokenClaims } from "../runtime-tools-token.js";
|
||||
@@ -32,6 +34,8 @@ import { connectionIntentDeliveryService } from "../services/connection-intent-d
|
||||
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
|
||||
import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js";
|
||||
import { materializeNativeInteractionResponses } from "../services/native-runtime/native-interaction-bridge.js";
|
||||
import { toolAccessService } from "../services/tool-access.js";
|
||||
import { toolAccessPolicyService } from "../services/tool-access-policy.js";
|
||||
import { connectionIntentService } from "../services/connection-intents.js";
|
||||
import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
@@ -869,4 +873,105 @@ describeEmbeddedPostgres("connectionIntentService", () => {
|
||||
});
|
||||
|
||||
|
||||
async function accessFixture() {
|
||||
const [company] = await db.insert(companies).values({ name: "Grant fixture", issuePrefix: `G${randomUUID().slice(0, 7)}` }).returning();
|
||||
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Default agent", role: "general", adapterType: "process" }).returning();
|
||||
const [otherAgent] = await db.insert(agents).values({ companyId: company.id, name: "Other agent", role: "general", adapterType: "process" }).returning();
|
||||
await db.insert(companyMemberships).values({ companyId: company.id, principalType: "user", principalId: "grant-user", membershipRole: "owner", status: "active" });
|
||||
const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Connect Circleback", status: "in_progress", assigneeAgentId: agent.id }).returning();
|
||||
const [run] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id, status: "running", responsibleUserId: "grant-user", contextSnapshot: { issueId: issue.id } }).returning();
|
||||
const [application] = await db.insert(toolApplications).values({ companyId: company.id, applicationKey: randomUUID(), name: "Composio", type: "mcp_http", metadata: { sourceTemplateKey: "composio" } }).returning();
|
||||
const [connection] = await db.insert(toolConnections).values({ companyId: company.id, applicationId: application.id, uid: randomUUID(), name: "Saved Composio", transport: "mcp_remote", authKind: "none", credentialPolicy: "shared", enabled: true, status: "active", healthStatus: "ok", config: { sourceTemplateKey: "composio" } }).returning();
|
||||
await db.insert(connectionGrants).values({ companyId: company.id, connectionId: connection.id, kind: "organization", status: "active" });
|
||||
await db.insert(toolConnectionInstalls).values({ companyId: company.id, connectionId: connection.id, targetType: "company", targetId: company.id });
|
||||
const catalog = await db.insert(toolCatalogEntries).values([
|
||||
{ toolName: "COMPOSIO_SEARCH_TOOLS", riskLevel: "read" as const },
|
||||
{ toolName: "COMPOSIO_MANAGE_CONNECTIONS", riskLevel: "destructive" as const },
|
||||
{ toolName: "COMPOSIO_REMOTE_BASH_TOOL", riskLevel: "destructive" as const },
|
||||
].map(tool => ({ ...tool, companyId: company.id, connectionId: connection.id, name: tool.toolName, versionHash: "v1", entryKind: "tool" as const, status: "active" as const }))).returning();
|
||||
return { company, agent, otherAgent, issue, connection, catalog, service: connectionIntentService(db), claims: { ...claims, sub: agent.id, company_id: company.id, run_id: run.id, responsible_user_id: "grant-user" } };
|
||||
}
|
||||
|
||||
it("creates a scoped access card and atomically accepts repeated clicks without granting other agents", async () => {
|
||||
const f = await accessFixture();
|
||||
const request = await f.service.request(f.claims, "composio", { connectionId: f.connection.id, toolNames: ["COMPOSIO_SEARCH_TOOLS", "COMPOSIO_MANAGE_CONNECTIONS"] });
|
||||
expect((await f.service.search(f.claims, "composio")).results[0].state).toBe("needs_user_action");
|
||||
const loaded = await f.service.loadIntent(request.interactionId!);
|
||||
expect(loaded.interaction).toMatchObject({ title: "Grant Composio access to Default agent?", payload: { accessRequest: { connectionId: f.connection.id, tools: [ { toolName: "COMPOSIO_SEARCH_TOOLS", permission: "allowed" }, { toolName: "COMPOSIO_MANAGE_CONNECTIONS", permission: "ask_first" } ] } } });
|
||||
const repeated = await f.service.request(f.claims, "composio", { connectionId: f.connection.id, toolNames: ["COMPOSIO_MANAGE_CONNECTIONS", "COMPOSIO_SEARCH_TOOLS"] });
|
||||
expect(repeated.interactionId).toBe(request.interactionId);
|
||||
await expect(f.service.complete(request.interactionId!, f.connection.id, "grant-user")).rejects.toThrow("connection-management authority");
|
||||
await expect(f.service.complete(request.interactionId!, f.connection.id, "other-user", { canManageOrganizationGrant: true })).rejects.toThrow("addressed user");
|
||||
const results = await Promise.all([1, 2].map(() => f.service.complete(request.interactionId!, f.connection.id, "grant-user", { canManageOrganizationGrant: true })));
|
||||
expect(results.every(result => result.status === "accepted")).toBe(true);
|
||||
const effective = await toolAccessService(db).getEffectiveProfilesForAgent(f.company.id, f.agent.id);
|
||||
expect(effective.allowedTools.map(tool => tool.toolName).sort()).toEqual(["COMPOSIO_MANAGE_CONNECTIONS", "COMPOSIO_SEARCH_TOOLS"]);
|
||||
expect((await toolAccessService(db).getEffectiveProfilesForAgent(f.company.id, f.otherAgent.id)).allowedTools).toEqual([]);
|
||||
for (const [name, outcome] of [["COMPOSIO_SEARCH_TOOLS", "allow"], ["COMPOSIO_MANAGE_CONNECTIONS", "require_approval"], ["COMPOSIO_REMOTE_BASH_TOOL", "deny"]]) {
|
||||
const tool = f.catalog.find(tool => tool.toolName === name)!;
|
||||
const decision = await toolAccessPolicyService(db).decide({ companyId: f.company.id, actor: { actorType: "agent", actorId: f.agent.id, agentId: f.agent.id }, request: { connectionId: f.connection.id, catalogEntryId: tool.id, toolName: tool.toolName, arguments: {} } });
|
||||
expect(decision.decision).toBe(outcome);
|
||||
}
|
||||
expect(await db.select().from(toolProfileEntries).where(eq(toolProfileEntries.profileId, effective.profiles.find(profile => profile.profileKey.startsWith("connection-intent:"))!.id))).toHaveLength(2);
|
||||
const managedTool = f.catalog[1];
|
||||
await db.insert(toolPolicies).values({ companyId: f.company.id, name: "New block after approval", policyType: "block", selectors: { catalogEntryId: managedTool.id }, priority: 100 });
|
||||
const blocked = await toolAccessPolicyService(db).decide({ companyId: f.company.id, actor: { actorType: "agent", actorId: f.agent.id, agentId: f.agent.id }, request: { connectionId: f.connection.id, catalogEntryId: managedTool.id, toolName: managedTool.toolName, arguments: {} } });
|
||||
expect(blocked.decision).toBe("deny");
|
||||
|
||||
});
|
||||
|
||||
it("rejects changed tools and rolls back installs, grants, and acceptance", async () => {
|
||||
const f = await accessFixture();
|
||||
const request = await f.service.request(f.claims, "composio", { connectionId: f.connection.id });
|
||||
await db.update(toolCatalogEntries).set({ versionHash: "v2" }).where(eq(toolCatalogEntries.id, f.catalog[0].id));
|
||||
await expect(f.service.complete(request.interactionId!, f.connection.id, "grant-user", { canManageOrganizationGrant: true })).rejects.toThrow("tools changed");
|
||||
expect((await f.service.loadIntent(request.interactionId!)).interaction.status).toBe("pending");
|
||||
expect((await toolAccessService(db).listConnectionInstalls(f.connection.id, f.company.id)).some(install => install.targetType === "agent")).toBe(false);
|
||||
expect((await toolAccessService(db).getEffectiveProfilesForAgent(f.company.id, f.agent.id)).allowedTools).toEqual([]);
|
||||
const renewed = await f.service.request(f.claims, "composio", { connectionId: f.connection.id });
|
||||
expect(renewed.interactionId).not.toBe(request.interactionId);
|
||||
expect((await f.service.loadIntent(request.interactionId!)).interaction.status).toBe("expired");
|
||||
expect((await f.service.loadIntent(renewed.interactionId!)).interaction.payload.accessRequest?.tools[0].versionHash).toBe("v2");
|
||||
});
|
||||
|
||||
it("revokes task-granted tools when the agent profile is removed, including Ask-first tools", async () => {
|
||||
const f = await accessFixture();
|
||||
const request = await f.service.request(f.claims, "composio", { connectionId: f.connection.id });
|
||||
await f.service.complete(request.interactionId!, f.connection.id, "grant-user", { canManageOrganizationGrant: true });
|
||||
const access = toolAccessService(db);
|
||||
const effective = await access.getEffectiveProfilesForAgent(f.company.id, f.agent.id);
|
||||
const profile = effective.profiles.find(profile => profile.profileKey.startsWith("connection-intent:"))!;
|
||||
await access.deleteProfile(profile.id, {});
|
||||
expect((await access.getEffectiveProfilesForAgent(f.company.id, f.agent.id)).allowedTools).toEqual([]);
|
||||
for (const tool of f.catalog.slice(0, 2)) {
|
||||
const decision = await toolAccessPolicyService(db).decide({
|
||||
companyId: f.company.id, actor: { actorType: "agent", actorId: f.agent.id, agentId: f.agent.id },
|
||||
request: { connectionId: f.connection.id, catalogEntryId: tool.id, toolName: tool.toolName, arguments: {} },
|
||||
});
|
||||
expect(decision.decision).toBe("deny");
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves explicit blocks and rejects unrelated or invented requested tools", async () => {
|
||||
const f = await accessFixture();
|
||||
await expect(f.service.request(f.claims, "composio", { connectionId: randomUUID() })).rejects.toThrow("not eligible");
|
||||
await expect(f.service.request(f.claims, "composio", { connectionId: f.connection.id, toolNames: ["invented"] })).rejects.toThrow("active catalog");
|
||||
const request = await f.service.request(f.claims, "composio", { connectionId: f.connection.id });
|
||||
await db.insert(toolPolicies).values({ companyId: f.company.id, name: "Explicit block", policyType: "block", selectors: { catalogEntryId: f.catalog[1].id } });
|
||||
await expect(f.service.complete(request.interactionId!, f.connection.id, "grant-user", { canManageOrganizationGrant: true })).rejects.toThrow("existing policy blocks");
|
||||
await expect(f.service.request({ ...f.claims, company_id: randomUUID() }, "composio", { connectionId: f.connection.id })).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("declines access without changing permissions and expires requests after reassignment", async () => {
|
||||
const f = await accessFixture();
|
||||
const request = await f.service.request(f.claims, "composio", { connectionId: f.connection.id });
|
||||
await f.service.decline(request.interactionId!, "grant-user");
|
||||
expect((await toolAccessService(db).getEffectiveProfilesForAgent(f.company.id, f.agent.id)).allowedTools).toEqual([]);
|
||||
const other = await accessFixture();
|
||||
const pending = await other.service.request(other.claims, "composio", { connectionId: other.connection.id });
|
||||
await db.update(issues).set({ assigneeAgentId: other.otherAgent.id }).where(eq(issues.id, other.issue.id));
|
||||
await expect(other.service.complete(pending.interactionId!, other.connection.id, "grant-user", { canManageOrganizationGrant: true })).rejects.toThrow();
|
||||
expect((await toolAccessService(db).getEffectiveProfilesForAgent(other.company.id, other.agent.id)).allowedTools).toEqual([]);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -37,6 +37,8 @@ describe("runtime connection MCP contract", () => {
|
||||
type: "object",
|
||||
properties: {
|
||||
service: { type: "string" },
|
||||
connectionId: { type: "string", description: "Reuse this saved connection" },
|
||||
toolNames: { type: "array", items: { type: "string" }, minItems: 1, maxItems: 20, uniqueItems: true, description: "Exact indexed tools needed by this agent" },
|
||||
targetService: { type: "string", description: "App slug returned by search only when the user explicitly named this external provider" },
|
||||
selectionInteractionId: {
|
||||
type: "string",
|
||||
|
||||
@@ -109,7 +109,7 @@ export function runtimeConnectionIntentRoutes(db: Db) {
|
||||
}
|
||||
if (name === "connection_request") {
|
||||
const input = connectionRequestInputSchema.parse(params.arguments ?? {});
|
||||
const result = await service.request(claims, input.service, { selectionInteractionId: input.selectionInteractionId, targetService: input.targetService });
|
||||
const result = await service.request(claims, input.service, { selectionInteractionId: input.selectionInteractionId, targetService: input.targetService, connectionId: input.connectionId, toolNames: input.toolNames });
|
||||
res.json({ jsonrpc: "2.0", id, result: resultContent(result) });
|
||||
return;
|
||||
}
|
||||
@@ -133,7 +133,7 @@ export function runtimeConnectionIntentRoutes(db: Db) {
|
||||
});
|
||||
router.post("/runtime-tools/connections/request", async (req, res) => {
|
||||
const input = connectionRequestInputSchema.parse(req.body ?? {});
|
||||
res.json(await service.request(runtimeClaims(req), input.service, { selectionInteractionId: input.selectionInteractionId, targetService: input.targetService }));
|
||||
res.json(await service.request(runtimeClaims(req), input.service, { selectionInteractionId: input.selectionInteractionId, targetService: input.targetService, connectionId: input.connectionId, toolNames: input.toolNames }));
|
||||
});
|
||||
return router;
|
||||
}
|
||||
|
||||
@@ -303,6 +303,8 @@ import {
|
||||
replaceChatEndpointResourcesSchema,
|
||||
updateChatEndpointSchema,
|
||||
} from "@paperclipai/shared";
|
||||
import { aggregatorAppsSyncSchema, aggregatorAppsRefreshSchema, arcadeDiscoverySetupSchema } from "@paperclipai/shared/aggregator-apps";
|
||||
import { composioAppsSyncSchema, composioAppsRefreshSchema, composioAppSetupSchema, composioAppAccountSchema } from "@paperclipai/shared/composio-app-setup";
|
||||
import {
|
||||
COMPANY_IMPORT_TRANSFERS_API_PATH,
|
||||
companyImportTransferDeclarationSchema,
|
||||
@@ -1454,6 +1456,15 @@ const BOARD_ONLY_OPERATIONS = new Set([
|
||||
"POST /api/tool-connections/{connectionId}/railway/ssh",
|
||||
"POST /api/tool-connections/{connectionId}/catalog/refresh",
|
||||
"GET /api/tool-connections/{connectionId}/catalog",
|
||||
"GET /api/tool-connections/{connectionId}/aggregator/apps",
|
||||
"POST /api/tool-connections/{connectionId}/aggregator/apps/sync",
|
||||
"POST /api/tool-connections/{connectionId}/aggregator/apps/refresh",
|
||||
"PUT /api/tool-connections/{connectionId}/aggregator/discovery",
|
||||
"GET /api/tool-connections/{connectionId}/composio/apps",
|
||||
"POST /api/tool-connections/{connectionId}/composio/apps/sync",
|
||||
"POST /api/tool-connections/{connectionId}/composio/apps/refresh",
|
||||
"POST /api/tool-connections/{connectionId}/composio/apps/{toolkit}/setup",
|
||||
"POST /api/tool-connections/{connectionId}/composio/apps/{toolkit}/accounts",
|
||||
"GET /api/tool-connections/{connectionId}/activity",
|
||||
"GET /api/tool-connections/{connectionId}/test-agents",
|
||||
"GET /api/tool-connections/{connectionId}/test-agents/{agentId}/access",
|
||||
@@ -10774,6 +10785,38 @@ registerCurrentRoute({
|
||||
summary: "List tool connection activity",
|
||||
});
|
||||
|
||||
for (const provider of ["aggregator", "composio"] as const) {
|
||||
registerCurrentRoute({
|
||||
method: "get", path: `/api/tool-connections/{connectionId}/${provider}/apps`, tags: ["tool-access"],
|
||||
summary: "List upstream account observations for the current connection manager",
|
||||
});
|
||||
registerCurrentRoute({
|
||||
method: "post", path: `/api/tool-connections/{connectionId}/${provider}/apps/sync`, tags: ["tool-access"],
|
||||
summary: "Start upstream account discovery without changing tool access",
|
||||
body: provider === "aggregator" ? aggregatorAppsSyncSchema : composioAppsSyncSchema,
|
||||
});
|
||||
registerCurrentRoute({
|
||||
method: "post", path: `/api/tool-connections/{connectionId}/${provider}/apps/refresh`, tags: ["tool-access"],
|
||||
summary: "Refresh upstream account observations",
|
||||
body: provider === "aggregator" ? aggregatorAppsRefreshSchema : composioAppsRefreshSchema,
|
||||
});
|
||||
}
|
||||
registerCurrentRoute({
|
||||
method: "put", path: "/api/tool-connections/{connectionId}/aggregator/discovery", tags: ["tool-access"],
|
||||
summary: "Save manager-owned optional Arcade account discovery credentials",
|
||||
body: arcadeDiscoverySetupSchema,
|
||||
});
|
||||
registerCurrentRoute({
|
||||
method: "post", path: "/api/tool-connections/{connectionId}/composio/apps/{toolkit}/setup", tags: ["tool-access"],
|
||||
summary: "Start or verify Composio app authorization through a saved gateway",
|
||||
body: composioAppSetupSchema,
|
||||
});
|
||||
registerCurrentRoute({
|
||||
method: "post", path: "/api/tool-connections/{connectionId}/composio/apps/{toolkit}/accounts", tags: ["tool-access"],
|
||||
summary: "Manage a Composio account through a saved gateway",
|
||||
body: composioAppAccountSchema,
|
||||
});
|
||||
|
||||
registerCurrentRoute({
|
||||
method: "get",
|
||||
path: "/api/tool-connections/{connectionId}/test-agents",
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { composioAppSetupSchema, composioAppsRefreshSchema, composioAppsSyncSchema, composioAppAccountSchema } from "@paperclipai/shared";
|
||||
import { aggregatorAppsSyncSchema, aggregatorAppsRefreshSchema, arcadeDiscoverySetupSchema } from "@paperclipai/shared/aggregator-apps";
|
||||
import { Router, type Request, type Response } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { agents, companies, connectionGrants, issueThreadInteractions, toolConnectionInstalls } from "@paperclipai/db";
|
||||
@@ -2032,6 +2034,68 @@ function connectorEnrollmentPrincipal(req: Request): string {
|
||||
res.json({ access: accessSummary });
|
||||
});
|
||||
|
||||
async function composioAppManager(req: Request, res: Response) {
|
||||
assertBoard(req);
|
||||
const connection = await getAccessibleResource(req, res, svc.getConnection(req.params.connectionId as string), "Tool connection not found");
|
||||
if (!connection) return null;
|
||||
if (!await isToolConnectionManager(req, connection.companyId)) throw forbidden("Only a connection manager can configure apps and grant agent access");
|
||||
return connection;
|
||||
}
|
||||
|
||||
router.get("/tool-connections/:connectionId/aggregator/apps", async (req, res) => {
|
||||
const connection = await composioAppManager(req, res);
|
||||
if (!connection) return;
|
||||
res.set("Cache-Control", "private, no-store");
|
||||
res.json(await svc.listAggregatorApps(connection.id, { actorType: "user", actorId: req.actor.userId ?? "board" }));
|
||||
});
|
||||
router.post("/tool-connections/:connectionId/aggregator/apps/sync", validate(aggregatorAppsSyncSchema), async (req, res) => {
|
||||
const connection = await composioAppManager(req, res);
|
||||
if (!connection) return;
|
||||
res.json(await svc.syncAggregatorApps(connection.id, req.body.force, { actorType: "user", actorId: req.actor.userId ?? "board" }));
|
||||
});
|
||||
router.post("/tool-connections/:connectionId/aggregator/apps/refresh", validate(aggregatorAppsRefreshSchema), async (req, res) => {
|
||||
const connection = await composioAppManager(req, res);
|
||||
if (!connection) return;
|
||||
res.json(await svc.refreshAggregatorApps(connection.id, req.body.toolkits, { actorType: "user", actorId: req.actor.userId ?? "board" }));
|
||||
});
|
||||
router.put("/tool-connections/:connectionId/aggregator/discovery", validate(arcadeDiscoverySetupSchema), async (req, res) => {
|
||||
const connection = await composioAppManager(req, res);
|
||||
if (!connection) return;
|
||||
res.json(await svc.configureArcadeDiscovery(connection.id, req.body, { actorType: "user", actorId: req.actor.userId ?? "board" }));
|
||||
});
|
||||
|
||||
router.get("/tool-connections/:connectionId/composio/apps", async (req, res) => {
|
||||
const connection = await composioAppManager(req, res);
|
||||
if (!connection) return;
|
||||
res.json(await svc.listComposioApps(connection.id, { actorType: "user", actorId: req.actor.userId ?? "board" }));
|
||||
});
|
||||
|
||||
router.post("/tool-connections/:connectionId/composio/apps/sync", validate(composioAppsSyncSchema), async (req, res) => {
|
||||
const connection = await composioAppManager(req, res);
|
||||
if (!connection) return;
|
||||
res.json(await svc.syncComposioApps(connection.id, req.body.force, { actorType: "user", actorId: req.actor.userId ?? "board" }));
|
||||
});
|
||||
|
||||
router.post("/tool-connections/:connectionId/composio/apps/refresh", validate(composioAppsRefreshSchema), async (req, res) => {
|
||||
const connection = await composioAppManager(req, res);
|
||||
if (!connection) return;
|
||||
res.json(await svc.refreshComposioApps(connection.id, req.body.toolkits, { actorType: "user", actorId: req.actor.userId ?? "board" }));
|
||||
});
|
||||
|
||||
router.post("/tool-connections/:connectionId/composio/apps/:toolkit/accounts", validate(composioAppAccountSchema), async (req, res) => {
|
||||
const connection = await composioAppManager(req, res);
|
||||
if (!connection) return;
|
||||
res.json(await svc.manageComposioAppAccount(connection.id, req.params.toolkit as string, req.body, { actorType: "user", actorId: req.actor.userId ?? "board" }));
|
||||
});
|
||||
|
||||
router.post("/tool-connections/:connectionId/composio/apps/:toolkit/setup", validate(composioAppSetupSchema), async (req, res) => {
|
||||
const connection = await composioAppManager(req, res);
|
||||
if (!connection) return;
|
||||
const result = await svc.setupComposioApp(connection.id, req.params.toolkit as string, req.body,
|
||||
{ actorType: "user", actorId: req.actor.userId ?? "board" });
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
router.post("/tool-connections/:connectionId/test-calls", validate(toolConnectionTestCallSchema), async (req, res) => {
|
||||
assertBoard(req);
|
||||
if (!options.toolGateway) {
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import type { ComposioAppAccount } from "@paperclipai/shared";
|
||||
import { aggregatorManagementUrl } from "@paperclipai/shared/aggregator-apps";
|
||||
import { resolveAggregatorApp } from "@paperclipai/shared/aggregator-app-catalog";
|
||||
|
||||
export class AggregatorDiscoveryUnavailableError extends Error {}
|
||||
|
||||
export type DiscoveredApp = { toolkit: string; accounts: ComposioAppAccount[] };
|
||||
export type JsonRequest = (path: string) => Promise<unknown>;
|
||||
export type McpCall = (name: string, args: Record<string, unknown>) => Promise<unknown>;
|
||||
const record = (value: unknown): Record<string, unknown> => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
const string = (value: unknown): string | undefined => typeof value === "string" && value.trim() ? value.trim() : undefined;
|
||||
|
||||
/** Read only explicit structured/JSON result channels, never provider prose. */
|
||||
export function inventoryPayload(value: unknown, depth = 0): Record<string, unknown> {
|
||||
if (depth > 8) throw new Error("Malformed provider inventory");
|
||||
const root = record(value);
|
||||
if (root.error || root.isError) throw new Error("Provider account discovery failed");
|
||||
if (root.result !== undefined) return inventoryPayload(root.result, depth + 1);
|
||||
if (root.structuredContent !== undefined) return inventoryPayload(root.structuredContent, depth + 1);
|
||||
if (root.value !== undefined && !root.items && !root.connections) return inventoryPayload(root.value, depth + 1);
|
||||
if (Array.isArray(root.content)) {
|
||||
for (const block of root.content) {
|
||||
if (record(block).type !== "text") continue;
|
||||
try { return inventoryPayload(JSON.parse(String(record(block).text)), depth + 1); } catch { /* Try another JSON block. */ }
|
||||
}
|
||||
throw new Error("Provider did not return an account inventory");
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
async function pages(request: JsonRequest, path: string): Promise<Record<string, unknown>[]> {
|
||||
const result: Record<string, unknown>[] = [];
|
||||
let offset = 0;
|
||||
for (let pageIndex = 0; pageIndex < 100; pageIndex++) {
|
||||
const page = record(await request(`${path}${path.includes("?") ? "&" : "?"}limit=100&offset=${offset}`));
|
||||
if (!Array.isArray(page.items) || page.items.some(item => !item || typeof item !== "object")) throw new Error("Incomplete provider inventory");
|
||||
result.push(...page.items.map(record));
|
||||
const total = typeof page.total_count === "number" ? page.total_count : typeof page.total === "number" ? page.total : undefined;
|
||||
if (total !== undefined && (!Number.isSafeInteger(total) || total < 0)) throw new Error("Incomplete provider inventory");
|
||||
if (total !== undefined && result.length >= total) return result;
|
||||
// Arcade returns the next offset, which can advance after a short page.
|
||||
if (page.offset !== undefined) {
|
||||
if (page.offset === 0 && total === undefined) return result;
|
||||
if (!page.items.length || !Number.isSafeInteger(page.offset) || Number(page.offset) <= offset) throw new Error("Incomplete provider inventory");
|
||||
offset = Number(page.offset);
|
||||
} else {
|
||||
if (page.items.length < 100) {
|
||||
if (total !== undefined) throw new Error("Incomplete provider inventory");
|
||||
return result;
|
||||
}
|
||||
offset += 100;
|
||||
}
|
||||
}
|
||||
throw new Error("Provider inventory exceeded the discovery limit");
|
||||
}
|
||||
|
||||
export async function discoverArcadeApps(input: { request: JsonRequest; userId: string; gatewayTools: string[] }): Promise<DiscoveredApp[]> {
|
||||
const [accounts, tools] = await Promise.all([
|
||||
pages(input.request, `/v1/admin/user_connections?user[id]=${encodeURIComponent(input.userId)}`),
|
||||
pages(input.request, `/v1/tools?user_id=${encodeURIComponent(input.userId)}`),
|
||||
]);
|
||||
const exposed = new Set(input.gatewayTools);
|
||||
const grouped = new Map<string, Map<string, ComposioAppAccount>>();
|
||||
for (const tool of tools) {
|
||||
const toolName = string(tool.qualified_name) ?? string(tool.name);
|
||||
const names = [toolName, string(tool.fully_qualified_name), string(tool.name)].filter((name): name is string => Boolean(name));
|
||||
if (!toolName || !names.some(name => exposed.has(name) || exposed.has(name.replaceAll(".", "_")))) continue;
|
||||
const toolkit = string(record(tool.toolkit).name) ?? toolName.split(/[._]/)[0];
|
||||
const requirements = record(tool.requirements);
|
||||
const auth = record(requirements.authorization);
|
||||
const providerId = string(auth.provider_id);
|
||||
if (!providerId || !toolkit) continue;
|
||||
const app = resolveAggregatorApp("arcade", toolkit);
|
||||
for (const account of accounts) {
|
||||
// Admin credentials can enumerate other users; reject unscoped records.
|
||||
if (account.user_id !== input.userId || account.provider_id !== providerId) continue;
|
||||
const id = string(account.id) ?? string(account.connection_id);
|
||||
if (!id) throw new Error("Malformed Arcade account");
|
||||
const live = ["active", "connected"].includes(String(account.connection_status).toLowerCase());
|
||||
const status = live && requirements.met === true && auth.token_status === "completed" ? "ACTIVE"
|
||||
: auth.token_status === "pending" ? "INITIATED" : auth.token_status === "failed" ? "EXPIRED" : "UNVERIFIED";
|
||||
const info = record(account.provider_user_info);
|
||||
const existing = grouped.get(toolkit) ?? new Map<string, ComposioAppAccount>();
|
||||
if (existing.get(id)?.status !== "ACTIVE") existing.set(id, {
|
||||
id, alias: string(info.email) ?? string(info.name) ?? null, status, isDefault: false,
|
||||
appSlug: app.slug, appName: app.name, managementUrl: aggregatorManagementUrl("arcade"),
|
||||
});
|
||||
grouped.set(toolkit, existing);
|
||||
}
|
||||
}
|
||||
return [...grouped].map(([toolkit, accounts]) => ({ toolkit, accounts: [...accounts.values()] }));
|
||||
}
|
||||
|
||||
export const EXECUTOR_INVENTORY_CODE = "if (typeof tools === 'undefined' || typeof tools.executor?.coreTools?.connections?.list !== 'function' || typeof tools.executor?.coreTools?.integrations?.list !== 'function') return { discoveryUnavailable: true }; const connections = await tools.executor.coreTools.connections.list({}); const integrations = await tools.executor.coreTools.integrations.list({}); const managementUrls = {}; for (const integration of new Set(connections.connections.map(account => account.integration))) { try { const handoff = await tools.executor.coreTools.connections.createHandoff({ integration }); managementUrls[integration] = handoff.url; } catch {} } return { connections: connections.connections, integrations: integrations.integrations, managementUrls };";
|
||||
|
||||
export async function discoverExecutorApps(input: { call: McpCall; toolNames: string[]; managementUrl?: string | null }): Promise<DiscoveredApp[]> {
|
||||
const accounts: Record<string, unknown>[] = [];
|
||||
const metadata = new Map<string, Record<string, unknown>>();
|
||||
let managementUrls: Record<string, unknown> = {};
|
||||
if (input.toolNames.includes("integrations")) {
|
||||
let offset = 0;
|
||||
for (let pageIndex = 0; pageIndex < 200; pageIndex++) {
|
||||
const page = inventoryPayload(await input.call("integrations", { limit: 50, offset }));
|
||||
if (!Array.isArray(page.items) || typeof page.hasMore !== "boolean") throw new Error("Incomplete Executor inventory");
|
||||
accounts.push(...page.items.map(record));
|
||||
if (!page.hasMore) break;
|
||||
if (typeof page.nextOffset !== "number" || page.nextOffset <= offset || pageIndex === 199) throw new Error("Incomplete Executor inventory");
|
||||
offset = page.nextOffset;
|
||||
}
|
||||
} else if (input.toolNames.includes("execute")) {
|
||||
const payload = inventoryPayload(await input.call("execute", { code: EXECUTOR_INVENTORY_CODE }));
|
||||
if (!Array.isArray(payload.connections) || !Array.isArray(payload.integrations)) throw new AggregatorDiscoveryUnavailableError("Executor account discovery is unavailable on this server");
|
||||
accounts.push(...payload.connections.map(record));
|
||||
managementUrls = record(payload.managementUrls);
|
||||
for (const item of payload.integrations) { const row = record(item); if (string(row.slug)) metadata.set(String(row.slug), row); }
|
||||
} else throw new AggregatorDiscoveryUnavailableError("Executor account discovery is unavailable on this server");
|
||||
const grouped = new Map<string, ComposioAppAccount[]>();
|
||||
for (const account of accounts) {
|
||||
const toolkit = string(account.integration);
|
||||
const name = string(account.connection) ?? string(account.name);
|
||||
const owner = string(account.owner);
|
||||
if (!toolkit || !name || !owner) throw new Error("Malformed Executor account");
|
||||
const app = resolveAggregatorApp("executor", toolkit, string(account.integrationName) ?? string(metadata.get(toolkit)?.name));
|
||||
const health = record(account.lastHealth);
|
||||
const status = health.status === "healthy" || health.status === "ok" ? "ACTIVE"
|
||||
: health.status === "unhealthy" || health.status === "expired" || health.status === "dead" ? "EXPIRED" : "UNVERIFIED";
|
||||
let managementUrl = aggregatorManagementUrl("executor", input.managementUrl);
|
||||
if (!managementUrl && typeof managementUrls[toolkit] === "string") {
|
||||
managementUrl = aggregatorManagementUrl("executor", managementUrls[toolkit] as string);
|
||||
if (managementUrl) { const url = new URL(managementUrl); url.search = ""; url.hash = ""; managementUrl = url.toString(); }
|
||||
}
|
||||
const id = JSON.stringify([toolkit, owner, name]);
|
||||
const before = grouped.get(toolkit) ?? [];
|
||||
if (before.some(item => item.id === id)) throw new Error("Duplicate Executor account identity");
|
||||
before.push({ id, alias: string(account.identityLabel) ?? name, status, isDefault: false,
|
||||
appSlug: app.slug, appName: app.name, healthCheckedAt: typeof health.checkedAt === "number" && Number.isFinite(health.checkedAt) && Math.abs(health.checkedAt) <= 8.64e15 ? new Date(health.checkedAt).toISOString() : string(health.checkedAt) ?? null,
|
||||
managementUrl,
|
||||
});
|
||||
grouped.set(toolkit, before);
|
||||
}
|
||||
return [...grouped].map(([toolkit, accounts]) => ({ toolkit, accounts }));
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { ComposioAppAccount, ComposioAppSetupResult } from "@paperclipai/shared";
|
||||
import { extractRemoteMcpPending } from "./remote-mcp-pending.js";
|
||||
import { unprocessable } from "../errors.js";
|
||||
|
||||
function record(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
|
||||
}
|
||||
|
||||
function payloadsFrom(response: unknown) {
|
||||
const root = record(response);
|
||||
const result = record(root?.result) ?? root;
|
||||
const payloads = [result, record(result?.structuredContent)];
|
||||
if (Array.isArray(result?.content)) {
|
||||
for (const item of result.content) {
|
||||
const block = record(item);
|
||||
if (block?.type !== "text" || typeof block.text !== "string") continue;
|
||||
try { payloads.push(record(JSON.parse(block.text))); } catch { /* Plain text is not proof. */ }
|
||||
}
|
||||
}
|
||||
if (root?.error || result?.isError === true || payloads.some(p => p?.successful === false || p?.success === false || p?.error)) {
|
||||
throw unprocessable("Composio could not configure this app. Check the app in Composio and try again.");
|
||||
}
|
||||
return payloads;
|
||||
}
|
||||
|
||||
/** Retain only account identity and status, never raw provider results or credentials. */
|
||||
export function composioAppAccounts(response: unknown, toolkit: string): ComposioAppAccount[] | undefined {
|
||||
const accounts = new Map<string, ComposioAppAccount>();
|
||||
let observed = false;
|
||||
let incomplete = false;
|
||||
let visited = 0;
|
||||
function visit(value: unknown, matched: boolean, depth: number) {
|
||||
if (++visited > 20_000 || depth > 12) { incomplete = true; return; }
|
||||
if (Array.isArray(value)) { value.forEach(item => visit(item, matched, depth + 1)); return; }
|
||||
const entry = record(value);
|
||||
if (!entry) return;
|
||||
const named = entry.toolkit ?? entry.toolkit_name ?? entry.toolkit_slug;
|
||||
const selected = matched || named === toolkit || record(named)?.slug === toolkit;
|
||||
if (selected && (entry.error || entry.success === false || entry.successful === false)) {
|
||||
throw unprocessable("Composio could not check this app. Refresh its accounts before trying again.");
|
||||
}
|
||||
if (selected && Array.isArray(entry.accounts)) {
|
||||
observed = true;
|
||||
for (const item of entry.accounts) {
|
||||
const account = record(item);
|
||||
const id = account?.id ?? account?.account_id ?? account?.connected_account_id;
|
||||
if (typeof id !== "string" || !id || id.length > 200) { incomplete = true; continue; }
|
||||
accounts.set(id, { id, alias: typeof account?.alias === "string" ? account.alias.slice(0, 100) : null,
|
||||
status: typeof account?.status === "string" ? account.status.toUpperCase().slice(0, 40) : "UNKNOWN",
|
||||
isDefault: account?.is_default === true || account?.isDefault === true });
|
||||
}
|
||||
}
|
||||
for (const [key, child] of Object.entries(entry)) visit(child, selected || key === toolkit, depth + 1);
|
||||
}
|
||||
payloadsFrom(response).forEach(payload => visit(payload, false, 0));
|
||||
return observed && !incomplete ? [...accounts.values()] : undefined;
|
||||
}
|
||||
|
||||
/** Only the requested toolkit can establish success; other accounts are unrelated. */
|
||||
export function composioAppSetupResult(response: unknown, toolkit: string): ComposioAppSetupResult {
|
||||
const payloads = payloadsFrom(response);
|
||||
let connected = false;
|
||||
let visited = 0;
|
||||
const visit = (value: unknown, matched: boolean, depth: number) => {
|
||||
if (++visited > 20_000 || depth > 12) return;
|
||||
if (Array.isArray(value)) { value.forEach(item => visit(item, matched, depth + 1)); return; }
|
||||
const entry = record(value);
|
||||
if (!entry) return;
|
||||
const named = entry.toolkit ?? entry.toolkit_name ?? entry.toolkit_slug ?? entry.name;
|
||||
const selected = matched || named === toolkit || record(named)?.slug === toolkit;
|
||||
if (selected && (typeof entry.status === "string" && entry.status.toUpperCase() === "ACTIVE" || entry.connected === true)) connected = true;
|
||||
for (const [key, child] of Object.entries(entry)) visit(child, selected || key === toolkit, depth + 1);
|
||||
};
|
||||
payloads.forEach(payload => visit(payload, false, 0));
|
||||
if (connected) return { status: "connected" };
|
||||
const url = extractRemoteMcpPending(response, "composio", "COMPOSIO_MANAGE_CONNECTIONS")?.links[0]?.url;
|
||||
return url ? { status: "authorization_required", authorizationUrl: url } : { status: "not_connected" };
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { toolCatalogEntries, toolConnections, toolProfiles, toolProfileEntries, toolPolicies, toolProfileBindings } from "@paperclipai/db";
|
||||
import type { ConnectionIntentInteraction } from "@paperclipai/shared";
|
||||
import { conflict } from "../errors.js";
|
||||
import { toolAccessPolicyService } from "./tool-access-policy.js";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
|
||||
type AccessTools = NonNullable<ConnectionIntentInteraction["payload"]["accessRequest"]>["tools"];
|
||||
|
||||
/** Called inside the caller's transaction after identity and installation checks. */
|
||||
export async function grantConnectionAgentTools(db: Db, input: {
|
||||
connection: Pick<typeof toolConnections.$inferSelect, "id" | "companyId" | "applicationId">;
|
||||
agentId: string;
|
||||
userId: string;
|
||||
tools: AccessTools;
|
||||
interactionId?: string;
|
||||
context?: { issueId: string; projectId: string | null };
|
||||
}) {
|
||||
const { connection, agentId, userId, tools, interactionId, context } = input;
|
||||
const catalog = await db.select().from(toolCatalogEntries).where(and(
|
||||
eq(toolCatalogEntries.companyId, connection.companyId), eq(toolCatalogEntries.connectionId, connection.id),
|
||||
)).for("update");
|
||||
for (const requested of tools) {
|
||||
const tool = catalog.find(entry => entry.id === requested.catalogEntryId);
|
||||
if (!tool || tool.status !== "active" || tool.entryKind !== "tool" || tool.toolName !== requested.toolName
|
||||
|| tool.versionHash !== requested.versionHash || (requested.permission === "allowed" && tool.riskLevel !== "read")) {
|
||||
throw conflict("The requested tools changed. Ask the agent for a new access request.");
|
||||
}
|
||||
const decision = await toolAccessPolicyService(db).decide({
|
||||
companyId: connection.companyId,
|
||||
actor: { actorType: "agent", actorId: agentId, agentId: agentId },
|
||||
runContext: context ?? {},
|
||||
request: { connectionId: connection.id, catalogEntryId: tool.id, toolName: tool.toolName, arguments: {} },
|
||||
});
|
||||
if (decision.decision === "deny" && decision.reasonCode !== "deny_default") {
|
||||
throw conflict("An existing policy blocks this tool. Review the connection's permissions before granting access.");
|
||||
}
|
||||
}
|
||||
// An additive, agent-scoped profile leaves other connection permissions
|
||||
// and company-wide assignments intact. The caller supplies the exact reviewed tool set.
|
||||
const profileKey = `connection-intent:${connection.id}:${agentId}`;
|
||||
const [profile] = await db.insert(toolProfiles).values({
|
||||
companyId: connection.companyId, profileKey, name: profileKey, defaultAction: "deny",
|
||||
metadata: { source: "connection_intent", connectionId: connection.id, agentId: agentId },
|
||||
}).onConflictDoUpdate({ target: [toolProfiles.companyId, toolProfiles.profileKey], set: { status: "active", updatedAt: new Date() } }).returning();
|
||||
const entries = await db.select().from(toolProfileEntries).where(and(
|
||||
eq(toolProfileEntries.companyId, connection.companyId), eq(toolProfileEntries.profileId, profile.id),
|
||||
));
|
||||
for (const tool of tools) {
|
||||
if (!entries.some(entry => entry.catalogEntryId === tool.catalogEntryId && entry.effect === "include")) {
|
||||
await db.insert(toolProfileEntries).values({ companyId: connection.companyId, profileId: profile.id,
|
||||
selectorType: "catalog_entry", effect: "include", catalogEntryId: tool.catalogEntryId,
|
||||
connectionId: connection.id, applicationId: connection.applicationId });
|
||||
}
|
||||
if (tool.permission === "ask_first") {
|
||||
const name = `connection-intent:${agentId}:${tool.catalogEntryId}`;
|
||||
await db.insert(toolPolicies).values({ companyId: connection.companyId, name, policyType: "require_approval", priority: 0,
|
||||
selectors: { connectionId: connection.id, catalogEntryId: tool.catalogEntryId },
|
||||
conditions: { actor: { agentId: agentId } },
|
||||
config: { source: "connection_intent", connectionId: connection.id, agentId: agentId },
|
||||
createdByUserId: userId,
|
||||
}).onConflictDoUpdate({ target: [toolPolicies.companyId, toolPolicies.name], set: { enabled: true, updatedAt: new Date() } });
|
||||
}
|
||||
}
|
||||
await db.insert(toolProfileBindings).values({ companyId: connection.companyId, profileId: profile.id,
|
||||
targetType: "agent", targetId: agentId, priority: 100, createdByUserId: userId,
|
||||
metadata: { source: "connection_intent", connectionId: connection.id },
|
||||
}).onConflictDoNothing();
|
||||
await logActivity(db, { companyId: connection.companyId, actorType: "user", actorId: userId,
|
||||
action: "tool_connection.agent_access_granted", entityType: "tool_connection", entityId: connection.id,
|
||||
details: { ...(interactionId ? { interactionId } : {}), agentId, profileId: profile.id, tools: tools } });
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { emailChannelService } from "./email-channels.js";
|
||||
import { emailConnectionService } from "./email-connections.js";
|
||||
import { grantConnectionAgentTools } from "./connection-agent-access.js";
|
||||
import { agentService } from "./agents.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
import { aiConnectionService } from "./ai-connections.js";
|
||||
import { aiConnectionBindingSchema } from "@paperclipai/shared";
|
||||
@@ -12,6 +14,10 @@ import {
|
||||
companies,
|
||||
toolConnections,
|
||||
toolCatalogEntries,
|
||||
toolProfiles,
|
||||
toolProfileEntries,
|
||||
toolProfileBindings,
|
||||
toolPolicies,
|
||||
companyMemberships,
|
||||
heartbeatRuns,
|
||||
issueThreadInteractions,
|
||||
@@ -44,6 +50,7 @@ import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
|
||||
import type { RuntimeToolsTokenClaims } from "../runtime-tools-token.js";
|
||||
import { issueThreadInteractionService } from "./issue-thread-interactions.js";
|
||||
import { toolAccessService } from "./tool-access.js";
|
||||
import { toolAccessPolicyService } from "./tool-access-policy.js";
|
||||
import { captureRunIdentity } from "./run-identity.js";
|
||||
import { resolveManagedGitHubIdentitySelection } from "./git-credentials.js";
|
||||
|
||||
@@ -431,9 +438,9 @@ export function connectionIntentService(db: Db) {
|
||||
candidates.push({ score, nameScore, item: {
|
||||
service, name: app.name, description: app.description ?? null, logoUrl: app.branding.logoUrl ?? null,
|
||||
methods: app.methods, source: app.source,
|
||||
state: ready ? "ready" : denied ? "unavailable" : !app.available || !app.methods.length ? "unavailable"
|
||||
state: ready ? "ready" : (denied && !isRemoteMcpConnectorId(service)) || !app.available || !app.methods.length ? "unavailable"
|
||||
: matching.length ? "needs_user_action" : "available",
|
||||
reason: ready ? "Connection is installed and usable by this agent" : denied ? "An administrator has not permitted executable tools for this agent; reconnecting cannot grant that permission" : !app.available ? "Connection is disabled or unavailable"
|
||||
reason: ready ? "Connection is installed and usable by this agent" : denied ? "Ask the responsible user to grant this agent access with connection_request" : !app.available ? "Connection is disabled or unavailable"
|
||||
: matching.some((connection) => isToolConnectionAttentionHealth(connection.healthStatus)) ? "Connection needs attention"
|
||||
: matching.length ? "Review identity and access for this agent" : "Connect this service to continue",
|
||||
connectionId: ready?.id ?? null,
|
||||
@@ -639,7 +646,7 @@ export function connectionIntentService(db: Db) {
|
||||
async function request(
|
||||
claims: ConnectionRunClaims,
|
||||
serviceSlug: string,
|
||||
options: { purpose?: "ai" | "channel"; selectionInteractionId?: string; targetService?: string } = {},
|
||||
options: { purpose?: "ai" | "channel"; selectionInteractionId?: string; targetService?: string; connectionId?: string; toolNames?: string[] } = {},
|
||||
): Promise<ConnectionRequestResult> {
|
||||
const context = await loadRunContext(claims);
|
||||
return requestWithContext(context, serviceSlug, options);
|
||||
@@ -648,7 +655,7 @@ export function connectionIntentService(db: Db) {
|
||||
async function requestWithContext(
|
||||
context: Awaited<ReturnType<typeof loadRunContext>>,
|
||||
serviceSlug: string,
|
||||
options: { purpose?: "ai" | "channel"; selectionInteractionId?: string; targetService?: string } = {},
|
||||
options: { purpose?: "ai" | "channel"; selectionInteractionId?: string; targetService?: string; connectionId?: string; toolNames?: string[] } = {},
|
||||
): Promise<ConnectionRequestResult> {
|
||||
const claims = { sub: context.agent.id, company_id: context.run.companyId, run_id: context.run.id, responsible_user_id: context.run.responsibleUserId! };
|
||||
const route = parseAggregatorRoute(serviceSlug);
|
||||
@@ -660,7 +667,7 @@ export function connectionIntentService(db: Db) {
|
||||
if (!selected?.aggregator) throw forbidden("The requested provider cannot connect this app without verified support and a recorded user choice or explicit user request");
|
||||
// Reuse the saved-answer validation below; a pending question also carries
|
||||
// an interaction ID, but is never permission to create the setup card.
|
||||
if (selected.service !== serviceSlug) return request(claims, selected.service, { selectionInteractionId: found.selectionInteractionId });
|
||||
if (selected.service !== serviceSlug) return request(claims, selected.service, { ...options, targetService: undefined, selectionInteractionId: found.selectionInteractionId });
|
||||
upstreamService = { slug: selected.aggregator.targetService, name: selected.aggregator.targetName };
|
||||
}
|
||||
if (route) {
|
||||
@@ -684,6 +691,41 @@ export function connectionIntentService(db: Db) {
|
||||
if (!app.available || app.methods.length === 0) {
|
||||
throw unprocessable(`Connection service ${serviceSlug} is not available`);
|
||||
}
|
||||
let accessRequest: ConnectionIntentInteraction["payload"]["accessRequest"];
|
||||
if (!options.purpose) {
|
||||
const inventory = await connectionInventory(context.run.companyId);
|
||||
const matching = inventory.connections.filter(connection =>
|
||||
sourceSlugForConnection(connection, inventory.applicationsById) === app.slug
|
||||
&& (!options.connectionId || connection.id === options.connectionId)
|
||||
&& connection.connectionPurpose !== "ai" && connection.status === "active" && connection.enabled
|
||||
&& !isToolConnectionAttentionHealth(connection.healthStatus));
|
||||
const eligible = (await Promise.all(matching.map(async connection => {
|
||||
const { grants } = await access.listConnectionGrants(connection.id, context.run.companyId);
|
||||
return grants.some(grant => grant.status === "active" && (
|
||||
grant.kind === "organization" || grant.subjectUserId === context.run.responsibleUserId
|
||||
|| (grant.kind === "agent" && grant.subjectAgentId === context.agent.id))) ? connection : null;
|
||||
}))).filter((connection): connection is ToolConnection => Boolean(connection));
|
||||
if (options.connectionId && !eligible.length) throw notFound("The saved connection is not eligible for this request");
|
||||
if (eligible.length === 1) {
|
||||
const connection = eligible[0]!;
|
||||
const catalog = (await indexedCatalog(connection.id, context.run.companyId)).filter(tool => tool.entryKind === "tool");
|
||||
const names = options.toolNames ?? (app.slug === "composio" ? ["COMPOSIO_SEARCH_TOOLS", "COMPOSIO_MANAGE_CONNECTIONS"] : catalog.map(tool => tool.toolName));
|
||||
const tools = names.map(name => catalog.find(tool => tool.toolName === name));
|
||||
if (options.toolNames && tools.some(tool => !tool)) throw unprocessable("A requested tool is not in this connection's active catalog");
|
||||
const effective = await access.getEffectiveProfilesForAgent(context.run.companyId, context.agent.id);
|
||||
const installed = effective.installedConnections.some(item => item.id === connection.id);
|
||||
const missing = !installed || tools.some(tool => tool && !effective.allowedTools.some(allowed => allowed.id === tool.id));
|
||||
if (missing && tools.length && tools.every(tool => Boolean(tool))) {
|
||||
if (tools.length > 20) throw unprocessable("Specify the tools needed for this task (up to 20)");
|
||||
accessRequest = {
|
||||
connectionId: connection.id, connectionName: connection.name,
|
||||
tools: tools.map(tool => ({ catalogEntryId: tool!.id, toolName: tool!.toolName, versionHash: tool!.versionHash,
|
||||
permission: tool!.riskLevel === "read" ? "allowed" as const : "ask_first" as const }))
|
||||
.sort((a, b) => Number(a.permission === "ask_first") - Number(b.permission === "ask_first") || a.toolName.localeCompare(b.toolName)),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
const ready = await usableConnectionForAgent({
|
||||
companyId: context.run.companyId,
|
||||
agentId: context.agent.id,
|
||||
@@ -691,7 +733,7 @@ export function connectionIntentService(db: Db) {
|
||||
serviceSlug: app.slug,
|
||||
purpose: options.purpose,
|
||||
});
|
||||
if (ready) {
|
||||
if (ready && !accessRequest && (!options.connectionId || ready.id === options.connectionId)) {
|
||||
return {
|
||||
version: 1,
|
||||
service: app.slug,
|
||||
@@ -701,7 +743,9 @@ export function connectionIntentService(db: Db) {
|
||||
instruction: isRemoteMcpConnectorId(app.slug) ? aggregatorContinuationInstruction(app.slug, upstreamService?.name ?? "The requested app") : options.purpose === "channel" ? "An active AgentMail inbox is assigned to you. Use agentmail_inboxes to read its address; do not request another connection." : options.purpose === "ai" ? `${app.name} authentication is available for the next execution.` : `${app.name} is connected. Use its installed tools; a native continuation will refresh tools if needed.`,
|
||||
};
|
||||
}
|
||||
if (!options.purpose && await administrativeDenial(context.run.companyId, context.agent.id, app.slug, await connectionInventory(context.run.companyId))) {
|
||||
// Missing profile entries can be reviewed in a scoped access card. Acceptance
|
||||
// still revalidates every tool and refuses explicit policy denials.
|
||||
if (!options.purpose && !accessRequest && await administrativeDenial(context.run.companyId, context.agent.id, app.slug, await connectionInventory(context.run.companyId))) {
|
||||
throw forbidden("This agent has no permitted actions for this service. Ask an administrator to review tool permissions; reconnecting will not remove a denial.");
|
||||
}
|
||||
const outcomeId = context.run.contextSnapshot?.interactionId;
|
||||
@@ -716,9 +760,10 @@ export function connectionIntentService(db: Db) {
|
||||
{
|
||||
payload: {
|
||||
version: 1,
|
||||
...(accessRequest ? { accessRequest } : {}),
|
||||
serviceSlug: app.slug,
|
||||
...(options.purpose ? { purpose: options.purpose } : {}),
|
||||
serviceName: upstreamService ? `${upstreamService.name} through ${app.name}` : app.name,
|
||||
serviceName: accessRequest ? app.name : upstreamService ? `${upstreamService.name} through ${app.name}` : app.name,
|
||||
...(upstreamService ? { upstreamService } : {}),
|
||||
serviceLogoUrl: app.branding.logoUrl ?? null,
|
||||
serviceDarkLogoUrl: app.branding.darkLogoUrl ?? null,
|
||||
@@ -729,7 +774,7 @@ export function connectionIntentService(db: Db) {
|
||||
sourceRunId: context.run.id,
|
||||
sourceIdentityContextId: context.run.activeIdentityContextId,
|
||||
addresseeUserId: context.run.responsibleUserId!,
|
||||
idempotencyKey: `connection-intent:${context.run.id}:${context.run.responsibleUserId}:${app.slug}${upstreamService ? `:${upstreamService.slug}` : ""}${options.purpose ? `:${options.purpose}` : ""}`,
|
||||
idempotencyKey: `connection-intent:${context.run.id}:${context.run.responsibleUserId}:${app.slug}${upstreamService ? `:${upstreamService.slug}` : ""}${options.purpose ? `:${options.purpose}` : ""}${accessRequest ? `:access:${createHash("sha256").update(JSON.stringify(accessRequest)).digest("hex")}` : ""}`,
|
||||
},
|
||||
);
|
||||
if (interaction.status !== "pending") throw conflict("This connection request has already been resolved. Follow its recorded outcome.");
|
||||
@@ -853,6 +898,7 @@ export function connectionIntentService(db: Db) {
|
||||
id, applicationId, name, status, enabled,
|
||||
})),
|
||||
requestedAgentId: payload.requestingAgentId,
|
||||
canGrantAccess: payload.accessRequest ? options.canManageOrganizationGrant === true : undefined,
|
||||
aiConnection: managed?.binding,
|
||||
aiConnectionRequiresAdoption: managed?.requiresAdoption || undefined,
|
||||
aiRepair: selectedAiAccount ? {
|
||||
@@ -903,6 +949,15 @@ export function connectionIntentService(db: Db) {
|
||||
const txDb = tx as unknown as Db;
|
||||
const txAccess = toolAccessService(txDb);
|
||||
const txInteractions = issueThreadInteractionService(txDb);
|
||||
const current = await txInteractions.getForIssue(task, interactionId) as ConnectionIntentInteraction;
|
||||
if (current.status !== "pending") {
|
||||
if (current.status === "accepted" && current.result?.connectionId === connectionId) return current;
|
||||
throw conflict("Connection intent is already resolved");
|
||||
}
|
||||
if (payload.accessRequest && (payload.accessRequest.connectionId !== connectionId || !options.canManageOrganizationGrant)) {
|
||||
if (payload.accessRequest.connectionId !== connectionId) throw conflict("Use the connection named in this access request");
|
||||
throw forbidden("Granting agent tool access requires connection-management authority");
|
||||
}
|
||||
await tx.select({ id: toolConnections.id }).from(toolConnections).where(and(eq(toolConnections.id, connectionId), eq(toolConnections.companyId, loaded.issue.companyId))).for("update");
|
||||
let selectedConnection = await txAccess.getConnection(connectionId, loaded.issue.companyId);
|
||||
const selectedApplication = await txAccess.getApplication(
|
||||
@@ -979,7 +1034,7 @@ export function connectionIntentService(db: Db) {
|
||||
const pendingPersonalGrant = grants.find((grant) =>
|
||||
grant.kind === "user" && grant.status === "active" && grant.subjectUserId === userId
|
||||
);
|
||||
if (selectedConnection.authKind === "oauth" && pendingPersonalGrant) {
|
||||
if (!payload.accessRequest && selectedConnection.authKind === "oauth" && pendingPersonalGrant) {
|
||||
// txAccess is bound to the outer transaction. Its internal transactions
|
||||
// become savepoints, so activation, credential bindings, and the
|
||||
// requesting agent's access roll back with any later failure.
|
||||
@@ -1035,6 +1090,14 @@ export function connectionIntentService(db: Db) {
|
||||
actorId: userId,
|
||||
});
|
||||
|
||||
if (payload.accessRequest) {
|
||||
await grantConnectionAgentTools(txDb, {
|
||||
connection: selectedConnection, agentId: payload.requestingAgentId, userId,
|
||||
tools: payload.accessRequest.tools, interactionId,
|
||||
context: { issueId: task.id, projectId: task.projectId },
|
||||
});
|
||||
}
|
||||
|
||||
const effective = await txAccess.getEffectiveProfilesForAgent(loaded.issue.companyId, payload.requestingAgentId);
|
||||
if (!effective.allowedTools.some((tool) => tool.connectionId === selectedConnection.id)) throw conflict("This connection has no permitted tools. Review its action permissions before continuing.");
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ export const RUNTIME_CONNECTION_TOOL_DEFINITIONS = [
|
||||
description: CONNECTION_REQUEST_TOOL_DESCRIPTION,
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { service: { type: "string" }, targetService: { type: "string", description: "App slug returned by search only when the user explicitly named this external provider" }, selectionInteractionId: { type: "string", description: "Saved answered provider-choice interaction ID for aggregator routes" } },
|
||||
properties: { service: { type: "string" }, connectionId: { type: "string", description: "Reuse this saved connection" }, toolNames: { type: "array", items: { type: "string" }, minItems: 1, maxItems: 20, uniqueItems: true, description: "Exact indexed tools needed by this agent" }, targetService: { type: "string", description: "App slug returned by search only when the user explicitly named this external provider" }, selectionInteractionId: { type: "string", description: "Saved answered provider-choice interaction ID for aggregator routes" } },
|
||||
required: ["service"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
|
||||
@@ -2614,7 +2614,7 @@ export function issueThreadInteractionService(
|
||||
|| existing.sourceRunId !== input.sourceRunId
|
||||
|| existing.addresseeUserId !== input.addresseeUserId
|
||||
|| (existing.kind === "connection_intent"
|
||||
? (connectionIntentPayloadSchema.parse(existing.payload).serviceSlug !== payload.serviceSlug || connectionIntentPayloadSchema.parse(existing.payload).purpose !== payload.purpose)
|
||||
? (connectionIntentPayloadSchema.parse(existing.payload).serviceSlug !== payload.serviceSlug || connectionIntentPayloadSchema.parse(existing.payload).purpose !== payload.purpose || !isDeepStrictEqual(connectionIntentPayloadSchema.parse(existing.payload).accessRequest, payload.accessRequest))
|
||||
: !isDeepStrictEqual(existing.payload, payload))
|
||||
) {
|
||||
throw conflict(
|
||||
@@ -2651,7 +2651,7 @@ export function issueThreadInteractionService(
|
||||
eq(issueThreadInteractions.addresseeUserId, input.addresseeUserId),
|
||||
));
|
||||
const reusable = pending.find((candidate) =>
|
||||
connectionIntentPayloadSchema.parse(candidate.payload).serviceSlug === payload.serviceSlug && connectionIntentPayloadSchema.parse(candidate.payload).purpose === payload.purpose);
|
||||
connectionIntentPayloadSchema.parse(candidate.payload).serviceSlug === payload.serviceSlug && connectionIntentPayloadSchema.parse(candidate.payload).purpose === payload.purpose && isDeepStrictEqual(connectionIntentPayloadSchema.parse(candidate.payload).accessRequest, payload.accessRequest));
|
||||
if (reusable) return reusable;
|
||||
|
||||
const [sourceRun] = await tx.select({ context: heartbeatRuns.contextSnapshot }).from(heartbeatRuns)
|
||||
@@ -2674,7 +2674,7 @@ export function issueThreadInteractionService(
|
||||
sourceRunId: input.sourceRunId,
|
||||
originCommentIds,
|
||||
sourceIdentityContextId: input.sourceIdentityContextId ?? null,
|
||||
title: `Connect ${payload.serviceName}`,
|
||||
title: payload.accessRequest ? `Grant ${payload.serviceName} access to ${payload.requestingAgentName}?` : `Connect ${payload.serviceName}`,
|
||||
summary: `${payload.requestingAgentName} needs this connection to continue.`,
|
||||
createdByAgentId: payload.requestingAgentId,
|
||||
addresseeUserId: input.addresseeUserId,
|
||||
|
||||
@@ -304,7 +304,7 @@ export class PaperclipRunnerToolAuthority {
|
||||
return connections.search(claims, input.query, { retryProviderChoice: input.retryProviderChoice });
|
||||
}
|
||||
const input = connectionRequestInputSchema.parse(call.arguments);
|
||||
const result = await connections.request(claims, input.service, { selectionInteractionId: input.selectionInteractionId, targetService: input.targetService });
|
||||
const result = await connections.request(claims, input.service, { selectionInteractionId: input.selectionInteractionId, targetService: input.targetService, connectionId: input.connectionId, toolNames: input.toolNames });
|
||||
if (result.state === "ready" && this.binding.pinnedMcpDigest && this.binding.enqueueWakeup) {
|
||||
const current = await resolveNativeRuntimeMcpSnapshot({ db: this.db, agent: { id: this.binding.agentId, companyId: this.binding.companyId }, runId: this.binding.runId });
|
||||
if (current.digest !== this.binding.pinnedMcpDigest) {
|
||||
|
||||
@@ -1453,7 +1453,10 @@ export function toolAccessPolicyService(db: Db) {
|
||||
if (policy.policyType === "require_approval") {
|
||||
// The connection's Ask first control restricts an existing action grant;
|
||||
// it must never grant access to agents outside that connection's profile.
|
||||
if (policy.config?.source === "app_gallery_finish" && !permittedByProfile) continue;
|
||||
if (["app_gallery_finish", "connection_intent"].includes(String(policy.config?.source)) && !permittedByProfile) continue;
|
||||
if (policy.config?.source === "connection_intent" && explicitBlock) {
|
||||
return decision("deny", "deny_policy_block", explicitBlock.policy.description ?? "Tool access is blocked by policy.", effectiveProfileIds, [explicitBlock.policy.id], { redactionPlan: redaction.redactionPlan });
|
||||
}
|
||||
return decision("require_approval", "requires_approval_policy", policy.description ?? "Tool access requires approval.", effectiveProfileIds, [policy.id], { redactionPlan: redaction.redactionPlan, policyExplanation });
|
||||
}
|
||||
if (policy.policyType === "allow") {
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
import { AGGREGATOR_NAMES, isAppAggregator, type AggregatorAppsResponse, type ArcadeDiscoverySetupInput } from "@paperclipai/shared/aggregator-apps";
|
||||
import { resolveAggregatorApp, type AppCatalogAggregator } from "@paperclipai/shared/aggregator-app-catalog";
|
||||
import { AggregatorDiscoveryUnavailableError, discoverArcadeApps, discoverExecutorApps, type DiscoveredApp } from "./aggregator-app-discovery.js";
|
||||
import { COMPOSIO_APP_TOOLKITS, findComposioCatalogApp } from "@paperclipai/shared/aggregator-app-catalog";
|
||||
import type { ComposioAppAccount, ComposioAppAccountInput, ComposioAppSetupInput, ComposioAppSetupResult, ComposioAppSnapshot, ComposioAppsResponse } from "@paperclipai/shared";
|
||||
import { composioAppAccounts, composioAppSetupResult } from "./composio-app-setup.js";
|
||||
import { isInsufficientConnectionScope, INSUFFICIENT_CONNECTION_SCOPE_MESSAGE } from "./connection-permission-errors.js";
|
||||
import { ASANA_CONNECTOR_SCOPES, isAsanaConnectorProfileId, type AsanaConnectorProfileId } from "@paperclipai/shared";
|
||||
import { BROWSER_USE_TOOLS } from "@paperclipai/shared";
|
||||
@@ -58,6 +64,8 @@ import {
|
||||
toolActionRequests,
|
||||
toolCatalogEntries,
|
||||
toolConnectionInstalls,
|
||||
toolConnectionAppSnapshots,
|
||||
toolConnectionAppSyncs,
|
||||
toolConnections,
|
||||
toolOauthStates,
|
||||
toolStdioCommandTemplates,
|
||||
@@ -657,6 +665,8 @@ type ToolAccessServiceOptions = {
|
||||
remoteHttpEndpointLookup?: RemoteHttpEndpointLookup;
|
||||
/** Test seam for protocol fixtures. Production uses the DNS-pinned transport. */
|
||||
remoteHttpRequest?: (url: string, init: RequestInit) => Promise<Response>;
|
||||
/** Smaller reviewed catalog for deterministic discovery fixtures. */
|
||||
composioAppToolkits?: readonly string[];
|
||||
/** Test seam for the centrally registered Gmail OAuth broker. */
|
||||
paperclipCloudConnector?: PaperclipCloudConnector | null;
|
||||
/** @deprecated Use paperclipCloudConnector. */
|
||||
@@ -3033,6 +3043,9 @@ export function toolAccessService(
|
||||
options: ToolAccessServiceOptions = {},
|
||||
) {
|
||||
const secrets = secretService(db);
|
||||
const composioSyncJobs = new Map<string, Promise<void>>();
|
||||
const composioSyncTtlMs = 5 * 60_000;
|
||||
const composioSyncLeaseMs = 4 * 60_000;
|
||||
|
||||
async function resolvedRemoteEndpoint(
|
||||
connection: typeof toolConnections.$inferSelect,
|
||||
@@ -3629,6 +3642,360 @@ export function toolAccessService(
|
||||
return isToolConnectionAttentionHealth(status);
|
||||
}
|
||||
|
||||
async function composioCredentialKey(connection: typeof toolConnections.$inferSelect, actor: ActorInfo) {
|
||||
const usesConnectionRefs = ["arcade", "executor"].includes(String(connection.config.sourceTemplateKey)) && connection.authKind !== "oauth" && connection.credentialPolicy === "shared";
|
||||
const grant = usesConnectionRefs ? null : await vaultGrantForConnection(connection, actor);
|
||||
const refs = grant?.credentialSecretRefs ?? connection.credentialSecretRefs;
|
||||
const discovery = asRecord(asRecord(connection.config.aggregatorDiscovery)[actor.actorId!]);
|
||||
const ids = [...new Set([...refs.map(ref => ref.secretId), ...(typeof discovery.secretId === "string" ? [discovery.secretId] : [])])].sort();
|
||||
const versions = ids.length ? await db.select({ id: companySecrets.id, version: companySecrets.latestVersion }).from(companySecrets)
|
||||
.where(and(eq(companySecrets.companyId, connection.companyId), inArray(companySecrets.id, ids))).orderBy(asc(companySecrets.id)) : [];
|
||||
return createHash("sha256").update(JSON.stringify({ grant: grant?.id, refs, versions,
|
||||
...(Object.keys(discovery).length ? { discovery } : {}),
|
||||
...(connection.config.sourceTemplateKey === "arcade" || connection.config.sourceTemplateKey === "executor"
|
||||
? { headers: projectedConnectionHeaders(connection), managementUrl: connection.config.managementUrl } : {}), endpoint: remoteEndpoint(connection.config), policy: connection.credentialPolicy, connectedAt: asRecord(connection.config.oauth)?.connectedAt })).digest("hex");
|
||||
}
|
||||
|
||||
async function cachedComposioApps(connection: typeof toolConnections.$inferSelect, actor: ActorInfo): Promise<ComposioAppSnapshot[]> {
|
||||
const credentialKey = await composioCredentialKey(connection, actor);
|
||||
const rows = await db.select().from(toolConnectionAppSnapshots).where(and(
|
||||
eq(toolConnectionAppSnapshots.companyId, connection.companyId), eq(toolConnectionAppSnapshots.connectionId, connection.id),
|
||||
eq(toolConnectionAppSnapshots.userId, actor.actorId!), eq(toolConnectionAppSnapshots.credentialKey, credentialKey),
|
||||
));
|
||||
return rows.map(row => ({ connectionId: row.connectionId, toolkit: row.toolkit, status: row.status, accounts: row.accounts,
|
||||
checkedAt: row.checkedAt.toISOString(), errorAt: row.errorAt?.toISOString() ?? null }));
|
||||
}
|
||||
|
||||
async function composioAppsResponse(connection: typeof toolConnections.$inferSelect, actor: ActorInfo): Promise<ComposioAppsResponse> {
|
||||
const credentialKey = await composioCredentialKey(connection, actor);
|
||||
const [sync] = await db.select().from(toolConnectionAppSyncs).where(and(
|
||||
eq(toolConnectionAppSyncs.companyId, connection.companyId), eq(toolConnectionAppSyncs.connectionId, connection.id),
|
||||
eq(toolConnectionAppSyncs.userId, actor.actorId!), eq(toolConnectionAppSyncs.credentialKey, credentialKey),
|
||||
));
|
||||
const interrupted = sync?.status === "syncing" && sync.updatedAt.getTime() < Date.now() - composioSyncLeaseMs;
|
||||
return { apps: await cachedComposioApps(connection, actor), sync: {
|
||||
status: interrupted || sync?.status === "unsupported" ? "error" : sync?.status ?? "idle", coverage: "supported_catalog",
|
||||
checked: sync?.checked ?? 0, total: sync?.total ?? 0, failed: sync?.failed ?? 0,
|
||||
lastCompletedAt: sync?.lastCompletedAt?.toISOString() ?? null,
|
||||
error: interrupted ? "App checks were interrupted. Refresh to try again."
|
||||
: (sync?.status === "error" || sync?.status === "unsupported") ? "Couldn’t finish checking Composio apps. Refresh to try again." : null,
|
||||
} };
|
||||
}
|
||||
|
||||
async function openComposioGateway(connectionId: string, actor: ActorInfo) {
|
||||
const connection = await getConnectionRow(connectionId);
|
||||
if (actor.actorType !== "user" || !actor.actorId) throw forbidden("A human connection manager must configure this app");
|
||||
if (connection.config.sourceTemplateKey !== "composio" || connection.transport !== "mcp_remote"
|
||||
|| connection.status !== "active" || !connection.enabled) throw unprocessable("Connect your Composio gateway first");
|
||||
const catalog = await db.select().from(toolCatalogEntries).where(and(
|
||||
eq(toolCatalogEntries.companyId, connection.companyId), eq(toolCatalogEntries.connectionId, connection.id),
|
||||
));
|
||||
if (!catalog.some(tool => tool.toolName === "COMPOSIO_MANAGE_CONNECTIONS" && tool.status === "active")) {
|
||||
throw unprocessable("Refresh your Composio gateway's actions before configuring this app");
|
||||
}
|
||||
const endpoint = await resolvedRemoteEndpoint(connection, actor);
|
||||
const headers = { ...projectedConnectionHeaders(connection), ...(await resolveCredentialHeaders(connection, actor)) };
|
||||
const credentialKey = await composioCredentialKey(await getConnectionRow(connectionId), actor);
|
||||
const send = (init: RequestInit) => requestRemoteHttpEndpoint(new URL(endpoint), { ...init, signal: AbortSignal.timeout(30_000) });
|
||||
let sessionHeaders = connection.config.mcpSessionRequired === true
|
||||
? await getMcpHttpSession({ send, headers, scope: `${connection.id}:app-setup:${actor.actorId}`, requestId: "paperclip-app-setup" }) : headers;
|
||||
async function manage(toolkits: { name: string; action: "list" | "add" | "rename" | "remove"; account_id?: string; alias?: string }[], tolerateToolkitErrors = false) {
|
||||
const checkedAt = new Date();
|
||||
const id = `paperclip-app-setup-${randomUUID()}`;
|
||||
const request = () => send({ method: "POST", headers: mcpHttpRequestHeaders(sessionHeaders), body: JSON.stringify({
|
||||
jsonrpc: "2.0", id, method: "tools/call", params: { name: "COMPOSIO_MANAGE_CONNECTIONS", arguments: { toolkits } },
|
||||
}) });
|
||||
const markFailed = async () => {
|
||||
const names = toolkits.filter(tool => tool.action === "list").map(tool => tool.name);
|
||||
if (names.length) await db.update(toolConnectionAppSnapshots).set({ errorAt: checkedAt }).where(and(
|
||||
eq(toolConnectionAppSnapshots.companyId, connection.companyId), eq(toolConnectionAppSnapshots.connectionId, connectionId),
|
||||
eq(toolConnectionAppSnapshots.userId, actor.actorId!), eq(toolConnectionAppSnapshots.credentialKey, credentialKey),
|
||||
inArray(toolConnectionAppSnapshots.toolkit, names), lte(toolConnectionAppSnapshots.checkedAt, checkedAt),
|
||||
));
|
||||
};
|
||||
try {
|
||||
let response = await request();
|
||||
// Only reads retry. An uncertain account mutation must never repeat automatically.
|
||||
if (toolkits.every(tool => tool.action === "list") && (response.status === 400 || response.status === 404)) {
|
||||
await response.body?.cancel();
|
||||
sessionHeaders = await initializeMcpHttpSession({ send, headers, requestId: id });
|
||||
response = await request();
|
||||
}
|
||||
if (!response.ok) throw new HttpError(502, toolkits.every(tool => tool.action === "list")
|
||||
? "Composio could not check this app. Reconnect the gateway if its sign-in expired."
|
||||
: "Composio has not confirmed this change. Refresh the accounts before trying again.", { code: "composio_app_setup_failed", status: response.status });
|
||||
const payload = await readMcpHttpResponse(response, id);
|
||||
if (await composioCredentialKey(await getConnectionRow(connectionId), actor) !== credentialKey) {
|
||||
throw conflict("The Composio account changed while checking apps. Refresh to check the current account.");
|
||||
}
|
||||
const failedToolkits: string[] = [];
|
||||
for (const tool of toolkits.filter(tool => tool.action === "list")) {
|
||||
let accounts: ComposioAppAccount[];
|
||||
try {
|
||||
composioAppSetupResult(payload, tool.name);
|
||||
const parsed = composioAppAccounts(payload, tool.name);
|
||||
if (!parsed) throw unprocessable("Composio did not return a complete account list. Refresh the accounts before trying again.");
|
||||
accounts = parsed;
|
||||
} catch (error) {
|
||||
await db.update(toolConnectionAppSnapshots).set({ errorAt: checkedAt }).where(and(
|
||||
eq(toolConnectionAppSnapshots.companyId, connection.companyId), eq(toolConnectionAppSnapshots.connectionId, connectionId),
|
||||
eq(toolConnectionAppSnapshots.userId, actor.actorId!), eq(toolConnectionAppSnapshots.credentialKey, credentialKey),
|
||||
eq(toolConnectionAppSnapshots.toolkit, tool.name), lte(toolConnectionAppSnapshots.checkedAt, checkedAt),
|
||||
));
|
||||
if (!tolerateToolkitErrors) throw error;
|
||||
failedToolkits.push(tool.name);
|
||||
continue;
|
||||
}
|
||||
const status = accounts.some(account => account.status === "ACTIVE") ? "connected" as const : "not_connected" as const;
|
||||
await db.insert(toolConnectionAppSnapshots).values({ companyId: connection.companyId, connectionId, userId: actor.actorId!,
|
||||
credentialKey, toolkit: tool.name, accounts, status, checkedAt, errorAt: null,
|
||||
}).onConflictDoUpdate({ target: [toolConnectionAppSnapshots.companyId, toolConnectionAppSnapshots.connectionId, toolConnectionAppSnapshots.userId, toolConnectionAppSnapshots.toolkit],
|
||||
set: { accounts, status, checkedAt, credentialKey, errorAt: null }, setWhere: lte(toolConnectionAppSnapshots.checkedAt, checkedAt) });
|
||||
}
|
||||
return { payload, failedToolkits };
|
||||
} catch (error) { await markFailed(); throw error; }
|
||||
}
|
||||
return { connection, catalog, credentialKey, manage: async (...args: Parameters<typeof manage>) => (await manage(...args)).payload, checkBatch: manage };
|
||||
}
|
||||
|
||||
async function startComposioAppSync(connectionId: string, force: boolean, actor: ActorInfo) {
|
||||
const opened = await openComposioGateway(connectionId, actor);
|
||||
const { connection, credentialKey } = opened;
|
||||
const existing = await cachedComposioApps(connection, actor);
|
||||
const catalog = options.composioAppToolkits ?? COMPOSIO_APP_TOOLKITS;
|
||||
const toolkits = [...new Set([...existing.filter(app => app.accounts.length > 0).map(app => app.toolkit), ...catalog])];
|
||||
const leaseId = randomUUID();
|
||||
const startedAt = new Date();
|
||||
const [lease] = await db.insert(toolConnectionAppSyncs).values({ companyId: connection.companyId, connectionId,
|
||||
userId: actor.actorId!, credentialKey, leaseId, status: "syncing", total: toolkits.length, updatedAt: startedAt,
|
||||
}).onConflictDoUpdate({ target: [toolConnectionAppSyncs.companyId, toolConnectionAppSyncs.connectionId, toolConnectionAppSyncs.userId, toolConnectionAppSyncs.credentialKey],
|
||||
set: { leaseId, status: "syncing", checked: 0, total: toolkits.length, failed: 0, updatedAt: startedAt },
|
||||
setWhere: and(
|
||||
or(ne(toolConnectionAppSyncs.status, "syncing"), lt(toolConnectionAppSyncs.updatedAt, new Date(Date.now() - composioSyncLeaseMs))),
|
||||
force ? sql`true` : or(ne(toolConnectionAppSyncs.status, "ready"), isNull(toolConnectionAppSyncs.lastCompletedAt),
|
||||
lt(toolConnectionAppSyncs.lastCompletedAt, new Date(Date.now() - composioSyncTtlMs))),
|
||||
),
|
||||
}).returning();
|
||||
if (lease) {
|
||||
const updateLease = async (values: Partial<typeof toolConnectionAppSyncs.$inferInsert>) => {
|
||||
const updated = await db.update(toolConnectionAppSyncs).set({ ...values, updatedAt: new Date() })
|
||||
.where(and(eq(toolConnectionAppSyncs.id, lease.id), eq(toolConnectionAppSyncs.leaseId, leaseId))).returning({ id: toolConnectionAppSyncs.id });
|
||||
if (!updated.length) throw conflict("App checks were replaced by a newer sync.");
|
||||
};
|
||||
const job = (async () => {
|
||||
let failed = 0;
|
||||
try {
|
||||
for (let start = 0; start < toolkits.length; start += 32) {
|
||||
if (Date.now() - startedAt.getTime() > composioSyncLeaseMs) throw new Error("Sync deadline exceeded");
|
||||
await updateLease({});
|
||||
const current = start === 0 ? opened : await openComposioGateway(connectionId, actor);
|
||||
if (current.credentialKey !== credentialKey) throw conflict("Composio credentials changed during sync.");
|
||||
const batch = toolkits.slice(start, start + 32);
|
||||
const result = await current.checkBatch(batch.map(name => ({ name, action: "list" })), true);
|
||||
failed += result.failedToolkits.length;
|
||||
await updateLease({ checked: start + batch.length, failed });
|
||||
}
|
||||
await updateLease({ status: failed > 0 ? "error" : "ready", lastCompletedAt: new Date(), failed });
|
||||
} catch {
|
||||
const [activeLease] = await db.select({ id: toolConnectionAppSyncs.id }).from(toolConnectionAppSyncs)
|
||||
.where(and(eq(toolConnectionAppSyncs.id, lease.id), eq(toolConnectionAppSyncs.leaseId, leaseId)));
|
||||
if (!activeLease) return;
|
||||
// Preserve observations, but never present a failed check as current authorization.
|
||||
await db.update(toolConnectionAppSnapshots).set({ errorAt: new Date() }).where(and(
|
||||
eq(toolConnectionAppSnapshots.companyId, connection.companyId), eq(toolConnectionAppSnapshots.connectionId, connectionId),
|
||||
eq(toolConnectionAppSnapshots.userId, actor.actorId!), eq(toolConnectionAppSnapshots.credentialKey, credentialKey),
|
||||
lte(toolConnectionAppSnapshots.checkedAt, startedAt),
|
||||
));
|
||||
await updateLease({ status: "error", failed }).catch(() => undefined);
|
||||
}
|
||||
})();
|
||||
composioSyncJobs.set(leaseId, job);
|
||||
void job.finally(() => composioSyncJobs.delete(leaseId)).catch(() => undefined);
|
||||
}
|
||||
return composioAppsResponse(await getConnectionRow(connectionId), actor);
|
||||
}
|
||||
|
||||
function aggregatorProvider(connection: typeof toolConnections.$inferSelect): AppCatalogAggregator {
|
||||
const provider = connection.config.sourceTemplateKey;
|
||||
if (!isAppAggregator(provider) || connection.transport !== "mcp_remote") throw notFound("Aggregator gateway not found");
|
||||
return provider;
|
||||
}
|
||||
|
||||
function assertDiscoveryActor(actor: ActorInfo) {
|
||||
if (actor.actorType !== "user" || !actor.actorId) throw forbidden("A human connection manager must check accounts");
|
||||
}
|
||||
|
||||
async function aggregatorDiscoveryState(connection: typeof toolConnections.$inferSelect, actor: ActorInfo, retryUnsupported = false): Promise<AggregatorAppsResponse["discovery"]> {
|
||||
const provider = aggregatorProvider(connection);
|
||||
if (connection.status !== "active" || !connection.enabled) return { availability: "disabled", message: "Restore this gateway to check its accounts." };
|
||||
if (provider === "arcade") {
|
||||
const discovery = asRecord(asRecord(connection.config.aggregatorDiscovery)[actor.actorId!]);
|
||||
const headers = projectedConnectionHeaders(connection);
|
||||
const grant = connection.authKind === "oauth" || connection.credentialPolicy !== "shared" ? await vaultGrantForConnection(connection, actor) : null;
|
||||
const refs = grant?.credentialSecretRefs ?? connection.credentialSecretRefs;
|
||||
const hasUserId = Boolean(Object.entries(headers).find(([key]) => key.toLowerCase() === "arcade-user-id")?.[1])
|
||||
|| refs.some(ref => ref.configPath.toLowerCase() === "headers.arcade-user-id");
|
||||
if ((!discovery.secretId || !discovery.userId) && !(hasUserId && connection.authKind === "api_key")) {
|
||||
return { availability: "setup_required", message: "Set up account sync to see your Arcade apps here." };
|
||||
}
|
||||
}
|
||||
const catalog = await db.select({ name: toolCatalogEntries.toolName }).from(toolCatalogEntries).where(and(
|
||||
eq(toolCatalogEntries.companyId, connection.companyId), eq(toolCatalogEntries.connectionId, connection.id), eq(toolCatalogEntries.status, "active"),
|
||||
));
|
||||
if ((provider === "executor" && !catalog.some(tool => ["integrations", "execute"].includes(tool.name)))
|
||||
|| (provider === "composio" && !catalog.some(tool => tool.name === "COMPOSIO_MANAGE_CONNECTIONS"))) {
|
||||
return { availability: "unsupported", message: `${AGGREGATOR_NAMES[provider]} account discovery is unavailable on this gateway. Refresh its actions or check its setup.` };
|
||||
}
|
||||
if (!retryUnsupported && provider === "executor") {
|
||||
const credentialKey = await composioCredentialKey(connection, actor);
|
||||
const [sync] = await db.select({ status: toolConnectionAppSyncs.status }).from(toolConnectionAppSyncs).where(and(
|
||||
eq(toolConnectionAppSyncs.companyId, connection.companyId), eq(toolConnectionAppSyncs.connectionId, connection.id),
|
||||
eq(toolConnectionAppSyncs.userId, actor.actorId!), eq(toolConnectionAppSyncs.credentialKey, credentialKey),
|
||||
));
|
||||
if (sync?.status === "unsupported") return { availability: "unsupported", message: "Executor account discovery is unavailable on this server. You can still use the gateway’s actions." };
|
||||
}
|
||||
return { availability: "available", message: null };
|
||||
}
|
||||
|
||||
async function aggregatorAppsResponse(connection: typeof toolConnections.$inferSelect, actor: ActorInfo): Promise<AggregatorAppsResponse> {
|
||||
assertDiscoveryActor(actor);
|
||||
const provider = aggregatorProvider(connection);
|
||||
const result = await composioAppsResponse(connection, actor);
|
||||
const discovery = await aggregatorDiscoveryState(connection, actor);
|
||||
return { provider, discovery, apps: result.apps.map(snapshot => {
|
||||
const app = resolveAggregatorApp(provider, snapshot.toolkit, snapshot.accounts[0]?.appName);
|
||||
return { ...snapshot, provider, freshness: discovery.availability !== "available" || snapshot.errorAt || result.sync.status === "error" || connection.status !== "active" || !connection.enabled || Date.now() - new Date(snapshot.checkedAt).getTime() > composioSyncTtlMs ? "stale" as const : "fresh" as const, appSlug: app.slug.startsWith(`${provider}:`) ? `${provider}:${connection.id}:${snapshot.toolkit}` : snapshot.accounts[0]?.appSlug ?? app.slug, appName: snapshot.accounts[0]?.appName ?? app.name };
|
||||
}), sync: { ...result.sync, coverage: provider === "composio" ? "supported_catalog" : provider === "arcade" ? "gateway_tools" : "visible_accounts",
|
||||
error: result.sync.error ? `Couldn’t finish checking ${AGGREGATOR_NAMES[provider]} apps. Refresh to try again.` : null,
|
||||
} };
|
||||
}
|
||||
|
||||
async function discoverAggregatorInventory(connection: typeof toolConnections.$inferSelect, actor: ActorInfo): Promise<DiscoveredApp[]> {
|
||||
const provider = aggregatorProvider(connection);
|
||||
const tools = await remoteTools(connection, undefined, actor);
|
||||
connection = await getConnectionRow(connection.id);
|
||||
const headers = { ...projectedConnectionHeaders(connection), ...(await resolveCredentialHeaders(connection, actor)) };
|
||||
const endpoint = new URL(await resolvedRemoteEndpoint(connection, actor));
|
||||
if (provider === "arcade") {
|
||||
// The extra project credential never joins invocation headers or tool grants.
|
||||
if (endpoint.hostname !== "api.arcade.dev" || endpoint.protocol !== "https:") throw unprocessable("Account sync requires an Arcade Cloud gateway");
|
||||
const discovery = asRecord(asRecord(connection.config.aggregatorDiscovery)[actor.actorId!]);
|
||||
let key: string | undefined;
|
||||
let userId: string | undefined;
|
||||
if (typeof discovery.secretId === "string" && typeof discovery.userId === "string") {
|
||||
const [secret] = await db.select().from(companySecrets).where(and(eq(companySecrets.id, discovery.secretId), eq(companySecrets.companyId, connection.companyId), eq(companySecrets.ownerUserId, actor.actorId!)));
|
||||
if (!secret?.userSecretDefinitionId) throw forbidden("Your Arcade discovery credential is unavailable");
|
||||
const resolved = await secrets.resolveUserSecretValue(connection.companyId, { definitionId: secret.userSecretDefinitionId, responsibleUserId: actor.actorId!, required: true }, {
|
||||
actorType: "user", actorId: actor.actorId!, consumerType: "tool_connection", consumerId: connection.id, responsibleUserId: actor.actorId!,
|
||||
});
|
||||
key = resolved?.value;
|
||||
userId = discovery.userId;
|
||||
} else {
|
||||
userId = Object.entries(headers).find(([name]) => name.toLowerCase() === "arcade-user-id")?.[1];
|
||||
if (connection.authKind === "api_key") key = Object.entries(headers).find(([name]) => name.toLowerCase() === "authorization")?.[1].replace(/^Bearer\s+/i, "");
|
||||
}
|
||||
if (!key || !userId) throw unprocessable("Set up Arcade account sync first");
|
||||
return discoverArcadeApps({ userId, gatewayTools: tools.map(tool => tool.name), request: async path => {
|
||||
const response = await requestRemoteHttpEndpoint(new URL(path, endpoint.origin), { method: "GET", headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(30_000) });
|
||||
if (!response.ok) { await response.body?.cancel(); throw new HttpError(502, "Arcade could not list your accounts. Check the project API key and Arcade user ID."); }
|
||||
return response.json();
|
||||
} });
|
||||
}
|
||||
const send = (init: RequestInit) => requestRemoteHttpEndpoint(endpoint, { ...init, signal: AbortSignal.timeout(30_000) });
|
||||
let sessionHeaders = connection.config.mcpSessionRequired === true ? await getMcpHttpSession({ send, headers, scope: `${connection.id}:inventory:${actor.actorId}`, requestId: "paperclip-account-inventory" }) : headers;
|
||||
return discoverExecutorApps({ toolNames: tools.map(tool => tool.name), managementUrl: typeof connection.config.managementUrl === "string" ? connection.config.managementUrl : null,
|
||||
call: async (name, args) => {
|
||||
const id = `paperclip-account-inventory-${randomUUID()}`;
|
||||
const request = () => send({ method: "POST", headers: mcpHttpRequestHeaders(sessionHeaders), body: JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args } }) });
|
||||
let response = await request();
|
||||
if (response.status === 400 || response.status === 404) {
|
||||
await response.body?.cancel(); sessionHeaders = await initializeMcpHttpSession({ send, headers, requestId: id }); response = await request();
|
||||
}
|
||||
if (!response.ok) { await response.body?.cancel(); throw new HttpError(502, "Executor could not list your accounts. Reconnect if sign-in expired."); }
|
||||
return readMcpHttpResponse(response, id);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function syncAggregatorApps(connectionId: string, force: boolean, actor: ActorInfo): Promise<AggregatorAppsResponse> {
|
||||
assertDiscoveryActor(actor);
|
||||
let connection = await getConnectionRow(connectionId);
|
||||
const provider = aggregatorProvider(connection);
|
||||
const discovery = await aggregatorDiscoveryState(connection, actor, force);
|
||||
if (discovery.availability !== "available") return aggregatorAppsResponse(connection, actor);
|
||||
if (provider === "composio") {
|
||||
await startComposioAppSync(connectionId, force, actor);
|
||||
return aggregatorAppsResponse(await getConnectionRow(connectionId), actor);
|
||||
}
|
||||
// Resolve/refresh the caller's gateway credentials before fingerprinting the lease.
|
||||
await resolveCredentialHeaders(connection, actor);
|
||||
connection = await getConnectionRow(connectionId);
|
||||
const credentialKey = await composioCredentialKey(connection, actor);
|
||||
const leaseId = randomUUID();
|
||||
const startedAt = new Date();
|
||||
const [lease] = await db.insert(toolConnectionAppSyncs).values({ companyId: connection.companyId, connectionId, userId: actor.actorId!, credentialKey, leaseId, status: "syncing", updatedAt: startedAt })
|
||||
.onConflictDoUpdate({ target: [toolConnectionAppSyncs.companyId, toolConnectionAppSyncs.connectionId, toolConnectionAppSyncs.userId, toolConnectionAppSyncs.credentialKey],
|
||||
set: { leaseId, status: "syncing", checked: 0, total: 0, failed: 0, updatedAt: startedAt },
|
||||
setWhere: and(or(ne(toolConnectionAppSyncs.status, "syncing"), lt(toolConnectionAppSyncs.updatedAt, new Date(Date.now() - composioSyncLeaseMs))),
|
||||
force ? sql`true` : or(ne(toolConnectionAppSyncs.status, "ready"), isNull(toolConnectionAppSyncs.lastCompletedAt), lt(toolConnectionAppSyncs.lastCompletedAt, new Date(Date.now() - composioSyncTtlMs)))),
|
||||
}).returning();
|
||||
if (lease) {
|
||||
const job = (async () => {
|
||||
try {
|
||||
const apps = await discoverAggregatorInventory(connection, actor);
|
||||
await db.transaction(async tx => {
|
||||
const [current] = await tx.select().from(toolConnections).where(and(eq(toolConnections.id, connectionId), eq(toolConnections.companyId, connection.companyId))).for("update");
|
||||
const [active] = await tx.select().from(toolConnectionAppSyncs).where(and(eq(toolConnectionAppSyncs.id, lease.id), eq(toolConnectionAppSyncs.leaseId, leaseId))).for("update");
|
||||
if (!current || !active || current.status !== "active" || !current.enabled || Date.now() - startedAt.getTime() > composioSyncLeaseMs
|
||||
|| await composioCredentialKey(current, actor) !== credentialKey) throw conflict("The gateway changed during account discovery");
|
||||
const checkedAt = new Date();
|
||||
// Commit the entire enumeration at once; a failed later page cannot delete accounts.
|
||||
await tx.update(toolConnectionAppSnapshots).set({ accounts: [], status: "not_connected", checkedAt, errorAt: null }).where(and(
|
||||
eq(toolConnectionAppSnapshots.companyId, connection.companyId), eq(toolConnectionAppSnapshots.connectionId, connectionId), eq(toolConnectionAppSnapshots.userId, actor.actorId!), eq(toolConnectionAppSnapshots.credentialKey, credentialKey),
|
||||
));
|
||||
for (const app of apps) await tx.insert(toolConnectionAppSnapshots).values({ companyId: connection.companyId, connectionId, userId: actor.actorId!, credentialKey,
|
||||
toolkit: app.toolkit, accounts: app.accounts, status: app.accounts.some(account => account.status === "ACTIVE") ? "connected" : "not_connected", checkedAt,
|
||||
}).onConflictDoUpdate({ target: [toolConnectionAppSnapshots.companyId, toolConnectionAppSnapshots.connectionId, toolConnectionAppSnapshots.userId, toolConnectionAppSnapshots.toolkit],
|
||||
set: { accounts: app.accounts, status: app.accounts.some(account => account.status === "ACTIVE") ? "connected" : "not_connected", checkedAt, errorAt: null, credentialKey },
|
||||
});
|
||||
await tx.update(toolConnectionAppSyncs).set({ status: "ready", checked: apps.length, total: apps.length, failed: 0, updatedAt: checkedAt, lastCompletedAt: checkedAt }).where(eq(toolConnectionAppSyncs.id, lease.id));
|
||||
});
|
||||
} catch (error) {
|
||||
await db.transaction(async tx => {
|
||||
const [active] = await tx.select().from(toolConnectionAppSyncs).where(and(eq(toolConnectionAppSyncs.id, lease.id), eq(toolConnectionAppSyncs.leaseId, leaseId))).for("update");
|
||||
if (!active) return;
|
||||
await tx.update(toolConnectionAppSnapshots).set({ errorAt: new Date() }).where(and(eq(toolConnectionAppSnapshots.companyId, connection.companyId), eq(toolConnectionAppSnapshots.connectionId, connectionId), eq(toolConnectionAppSnapshots.userId, actor.actorId!), eq(toolConnectionAppSnapshots.credentialKey, credentialKey)));
|
||||
await tx.update(toolConnectionAppSyncs).set({ status: error instanceof AggregatorDiscoveryUnavailableError ? "unsupported" : "error", failed: 1, updatedAt: new Date() }).where(eq(toolConnectionAppSyncs.id, lease.id));
|
||||
});
|
||||
}
|
||||
})();
|
||||
composioSyncJobs.set(leaseId, job);
|
||||
void job.finally(() => composioSyncJobs.delete(leaseId)).catch(() => undefined);
|
||||
}
|
||||
return aggregatorAppsResponse(await getConnectionRow(connectionId), actor);
|
||||
}
|
||||
|
||||
async function configureArcadeDiscovery(connectionId: string, input: ArcadeDiscoverySetupInput, actor: ActorInfo) {
|
||||
assertDiscoveryActor(actor);
|
||||
const companyId = (await getConnectionRow(connectionId)).companyId;
|
||||
await db.transaction(async tx => {
|
||||
const [connection] = await tx.select().from(toolConnections).where(eq(toolConnections.id, connectionId)).for("update");
|
||||
if (!connection || aggregatorProvider(connection) !== "arcade" || connection.status === "archived") throw notFound("Arcade gateway not found");
|
||||
const all = asRecord(connection.config.aggregatorDiscovery);
|
||||
const before = asRecord(all[actor.actorId!]);
|
||||
const { secret } = await writeConnectionCredential(tx, {
|
||||
companyId: connection.companyId, connectionName: connection.name, configPath: "aggregatorDiscovery.apiKey", label: "Arcade account sync API key",
|
||||
value: input.apiKey, ownerUserId: actor.actorId!, actor: actorForSecret(actor),
|
||||
existingRef: typeof before.secretId === "string" ? { secretId: before.secretId, configPath: "aggregatorDiscovery.apiKey", versionSelector: "latest" } : undefined,
|
||||
definitionKey: `arcade_discovery.${connection.id}`,
|
||||
});
|
||||
const config = { ...connection.config, aggregatorDiscovery: { ...all, [actor.actorId!]: { userId: input.userId, secretId: secret.id } } };
|
||||
await tx.update(toolConnections).set({ config, transportConfig: config, updatedAt: new Date() }).where(eq(toolConnections.id, connectionId));
|
||||
});
|
||||
await logActivity(db, { companyId, actorType: "user", actorId: actor.actorId!, action: "tool_connection.account_sync_configured", entityType: "tool_connection", entityId: connectionId, details: { provider: "arcade" } });
|
||||
return syncAggregatorApps(connectionId, true, actor);
|
||||
}
|
||||
|
||||
async function audit(input: {
|
||||
companyId: string;
|
||||
connectionId?: string | null;
|
||||
@@ -6352,6 +6719,7 @@ export function toolAccessService(
|
||||
// provider error leaves an unresolvable secret and a resumable removal
|
||||
// rather than a half-open app.
|
||||
const candidateSecretIds = [
|
||||
...Object.values(asRecord(connection.config.aggregatorDiscovery)).flatMap(value => typeof asRecord(value).secretId === "string" ? [asRecord(value).secretId as string] : []),
|
||||
...connection.credentialRefs.map((ref) => ref.secretId),
|
||||
...connection.credentialSecretRefs.map((ref) => ref.secretId),
|
||||
...grantRows.flatMap((grant) =>
|
||||
@@ -16698,6 +17066,100 @@ export function toolAccessService(
|
||||
return toStdioCommandTemplate(row);
|
||||
},
|
||||
|
||||
async setupComposioApp(connectionId: string, toolkit: string, input: ComposioAppSetupInput, actor: ActorInfo): Promise<ComposioAppSetupResult> {
|
||||
if (!findComposioCatalogApp(toolkit)) throw notFound("This Composio app is not in the catalog");
|
||||
const { connection, manage } = await openComposioGateway(connectionId, actor);
|
||||
let result = composioAppSetupResult(await manage([{ name: toolkit, action: "list" }]), toolkit);
|
||||
if (input.action === "start" && result.status !== "connected") {
|
||||
result = composioAppSetupResult(await manage([{ name: toolkit, action: "add" }]), toolkit);
|
||||
if (result.status === "not_connected") throw unprocessable("Composio did not return a sign-in link for this app. Manage it in Composio to check its setup requirements.");
|
||||
}
|
||||
if (input.action === "complete") {
|
||||
if (result.status !== "connected") throw conflict("Finish connecting this app in Composio, then check again");
|
||||
const currentConnection = await getConnectionRow(connectionId);
|
||||
if (currentConnection.status !== "active" || !currentConnection.enabled) {
|
||||
throw conflict("The gateway is no longer active. Restore it before connecting this app.");
|
||||
}
|
||||
}
|
||||
await audit({ companyId: connection.companyId, connectionId, action: "tool_connection.upstream_app_setup", outcome: "success", actor,
|
||||
details: { toolkit, action: input.action, status: result.status } });
|
||||
return result;
|
||||
},
|
||||
|
||||
listAggregatorApps: async (connectionId: string, actor: ActorInfo) => aggregatorAppsResponse(await getConnectionRow(connectionId), actor),
|
||||
syncAggregatorApps,
|
||||
refreshAggregatorApps: async (connectionId: string, requested: string[], actor: ActorInfo) => {
|
||||
const connection = await getConnectionRow(connectionId);
|
||||
if (aggregatorProvider(connection) === "composio" && requested.length) {
|
||||
const { manage } = await openComposioGateway(connectionId, actor);
|
||||
if (requested.some(toolkit => !findComposioCatalogApp(toolkit))) throw notFound("This Composio app is not in the catalog");
|
||||
await manage(requested.map(name => ({ name, action: "list" })));
|
||||
return aggregatorAppsResponse(connection, actor);
|
||||
}
|
||||
return syncAggregatorApps(connectionId, true, actor);
|
||||
},
|
||||
configureArcadeDiscovery,
|
||||
syncComposioApps: startComposioAppSync,
|
||||
|
||||
async listComposioApps(connectionId: string, actor: ActorInfo) {
|
||||
const connection = await getConnectionRow(connectionId);
|
||||
if (actor.actorType !== "user" || !actor.actorId) throw forbidden("Board access required");
|
||||
if (connection.config.sourceTemplateKey !== "composio") throw notFound("Composio gateway not found");
|
||||
return composioAppsResponse(connection, actor);
|
||||
},
|
||||
|
||||
async refreshComposioApps(connectionId: string, requested: string[], actor: ActorInfo) {
|
||||
if (requested.some(toolkit => !findComposioCatalogApp(toolkit))) throw notFound("This Composio app is not in the catalog");
|
||||
const { connection, manage } = await openComposioGateway(connectionId, actor);
|
||||
const existing = await cachedComposioApps(connection, actor);
|
||||
// Migrate observations from the original direct setup flow on the first visit.
|
||||
const history = await db.select({ details: toolAccessAuditEvents.details }).from(toolAccessAuditEvents).where(and(
|
||||
eq(toolAccessAuditEvents.companyId, connection.companyId), eq(toolAccessAuditEvents.connectionId, connectionId),
|
||||
eq(toolAccessAuditEvents.actorId, actor.actorId!), eq(toolAccessAuditEvents.action, "tool_connection.upstream_app_setup"),
|
||||
)).orderBy(desc(toolAccessAuditEvents.createdAt)).limit(128);
|
||||
const known = [...existing.filter(app => app.accounts.length > 0).map(app => app.toolkit),
|
||||
...history.map(row => row.details.toolkit).filter((toolkit): toolkit is string => typeof toolkit === "string" && Boolean(findComposioCatalogApp(toolkit)))];
|
||||
const toolkits = [...new Set([...requested, ...known])];
|
||||
for (let start = 0; start < toolkits.length; start += 32) {
|
||||
await manage(toolkits.slice(start, start + 32).map(name => ({ name, action: "list" })));
|
||||
}
|
||||
return composioAppsResponse(connection, actor);
|
||||
},
|
||||
|
||||
async manageComposioAppAccount(connectionId: string, toolkit: string, input: ComposioAppAccountInput, actor: ActorInfo) {
|
||||
if (!findComposioCatalogApp(toolkit)) throw notFound("This Composio app is not in the catalog");
|
||||
const { connection, manage } = await openComposioGateway(connectionId, actor);
|
||||
if (input.action !== "add") {
|
||||
const before = composioAppAccounts(await manage([{ name: toolkit, action: "list" }]), toolkit);
|
||||
if (!before?.some(account => account.id === input.accountId)) throw notFound("This account is no longer available in the selected Composio app");
|
||||
}
|
||||
const details = { toolkit, ...(input.action !== "add" ? { accountId: input.accountId } : {}) };
|
||||
await logActivity(db, { companyId: connection.companyId, actorType: "user", actorId: actor.actorId!,
|
||||
action: `tool_connection.upstream_account_${input.action}_requested`, entityType: "tool_connection", entityId: connectionId, details });
|
||||
let payload: unknown;
|
||||
try {
|
||||
payload = await manage([{ name: toolkit, action: input.action,
|
||||
...(input.action !== "add" ? { account_id: input.accountId } : {}), ...(input.action === "rename" ? { alias: input.alias } : {}) }]);
|
||||
} catch (error) {
|
||||
await audit({ companyId: connection.companyId, connectionId, actor, action: `tool_connection.upstream_account_${input.action}`,
|
||||
outcome: "failure", reasonCode: "provider_unconfirmed", details });
|
||||
throw error;
|
||||
}
|
||||
const result = composioAppSetupResult(payload, toolkit); // Reject provider errors before reporting success.
|
||||
if (input.action === "add" && !result.authorizationUrl) throw unprocessable("Composio did not return a sign-in link. Check the app in Composio.");
|
||||
if (input.action !== "add") {
|
||||
const after = composioAppAccounts(await manage([{ name: toolkit, action: "list" }]), toolkit);
|
||||
if (!after || (input.action === "remove" ? after.some(account => account.id === input.accountId)
|
||||
: !after.some(account => account.id === input.accountId && account.alias === input.alias))) {
|
||||
throw conflict("Composio has not confirmed this change. Refresh the accounts before trying again.");
|
||||
}
|
||||
}
|
||||
await logActivity(db, { companyId: connection.companyId, actorType: "user", actorId: actor.actorId!,
|
||||
action: `tool_connection.upstream_account_${input.action}`, entityType: "tool_connection", entityId: connectionId,
|
||||
details: { toolkit, ...(input.action !== "add" ? { accountId: input.accountId } : {}) } });
|
||||
return { ...result, apps: await cachedComposioApps(connection, actor) };
|
||||
},
|
||||
|
||||
connectGalleryApp,
|
||||
|
||||
finishGalleryAppConnection,
|
||||
|
||||
@@ -7,6 +7,16 @@ import {
|
||||
const createdAt = new Date("2026-08-11T00:00:00.000Z");
|
||||
|
||||
describe("tool profile binding precedence", () => {
|
||||
it("adds an agent connection grant without dropping broader access to other apps", () => {
|
||||
const company = { profileId: "company", targetType: "company" as const, targetId: "company-1", priority: 100, createdAt };
|
||||
const grant = { profileId: "grant", targetType: "agent" as const, targetId: "agent-1", priority: 100, createdAt };
|
||||
const profiles = [
|
||||
{ id: "company", profileKey: "default", metadata: {} },
|
||||
{ id: "grant", profileKey: "connection-intent:connection-1:agent-1", metadata: { source: "connection_intent", connectionId: "connection-1", agentId: "agent-1" } },
|
||||
];
|
||||
expect(effectiveToolProfileBindings([company, grant], profiles, "connection-1")).toEqual([company, grant]);
|
||||
expect(effectiveToolProfileBindings([company, grant], profiles, "connection-2")).toEqual([company]);
|
||||
});
|
||||
it("keeps ordinary profiles at the narrowest matching scope", () => {
|
||||
const companyBinding = {
|
||||
profileId: "company-profile",
|
||||
|
||||
@@ -59,6 +59,10 @@ export function profileIdsInBindingOrder<T extends Pick<BindingLike, "profileId"
|
||||
function isWizardAppProfile(profile: ProfileLike, connectionId?: string | null): boolean {
|
||||
if (!profile.metadata || typeof profile.metadata !== "object" || Array.isArray(profile.metadata)) return false;
|
||||
const metadata = profile.metadata as Record<string, unknown>;
|
||||
if (metadata.source === "connection_intent" && typeof metadata.connectionId === "string" && typeof metadata.agentId === "string") {
|
||||
return profile.profileKey === `connection-intent:${metadata.connectionId}:${metadata.agentId}`
|
||||
&& (connectionId == null || metadata.connectionId === connectionId);
|
||||
}
|
||||
if (metadata.source !== "app_gallery_finish" || typeof metadata.connectionId !== "string") return false;
|
||||
if (profile.profileKey !== `app:${metadata.connectionId}`) return false;
|
||||
return connectionId === undefined || connectionId === null || metadata.connectionId === connectionId;
|
||||
@@ -83,8 +87,12 @@ export function effectiveToolProfileBindings<T extends BindingLike>(
|
||||
const appProfileIds = new Set(
|
||||
profiles.filter((profile) => isWizardAppProfile(profile, connectionId)).map((profile) => profile.id),
|
||||
);
|
||||
const accessProfileIds = new Set(profiles.filter(profile => {
|
||||
const metadata = profile.metadata as Record<string, unknown> | null;
|
||||
return metadata?.source === "connection_intent";
|
||||
}).map(profile => profile.id));
|
||||
const selected = [
|
||||
...narrowestScopeBindings(bindings),
|
||||
...narrowestScopeBindings(bindings.filter(binding => !accessProfileIds.has(binding.profileId))),
|
||||
...bindings.filter((binding) => appProfileIds.has(binding.profileId)),
|
||||
];
|
||||
const seen = new Set<string>();
|
||||
|
||||
Reference in new issue
Block a user