π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(composio): run off user_connectors.metadata, fall back to plugin table (#16932)
LiJian0d7a2e7a1ba6
diff --git a/apps/server/src/routers/lambda/composio.test.ts b/apps/server/src/routers/lambda/composio.test.tsnew file mode 100644index 00000000000..538c00635c1--- /dev/null+++ b/apps/server/src/routers/lambda/composio.test.ts@@ -0,0 +1,192 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { composioRouter } from './composio';++const mocks = vi.hoisted(() => ({+ // composio client+ authConfigsCreate: vi.fn(),+ authConfigsList: vi.fn(),+ connectedAccountsDelete: vi.fn(),+ connectedAccountsLink: vi.fn(),+ connectorCreate: vi.fn(),+ connectorDelete: vi.fn(),+ connectorQueryByIdentifiers: vi.fn(),+ connectorToolDeleteToolsNotIn: vi.fn(),+ connectorToolUpsertMany: vi.fn(),+ connectorUpdate: vi.fn(),+ getRawComposioTools: vi.fn(),+ // config+ getServerComposioAuthConfigId: vi.fn(),+ // plugin model+ pluginCreate: vi.fn(),+ pluginDelete: vi.fn(),+ pluginFindById: vi.fn(),+ pluginUpdate: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(async () => ({})) }));++vi.mock('@/config/composio', () => ({+ getServerComposioAuthConfigId: mocks.getServerComposioAuthConfigId,+}));++vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(() => ({+ create: mocks.pluginCreate,+ delete: mocks.pluginDelete,+ findById: mocks.pluginFindById,+ update: mocks.pluginUpdate,+ })),+}));++vi.mock('@/database/models/connector', () => ({+ ConnectorModel: vi.fn().mockImplementation(() => ({+ create: mocks.connectorCreate,+ delete: mocks.connectorDelete,+ queryByIdentifiers: mocks.connectorQueryByIdentifiers,+ update: mocks.connectorUpdate,+ })),+}));++vi.mock('@/database/models/connectorTool', () => ({+ ConnectorToolModel: vi.fn().mockImplementation(() => ({+ deleteToolsNotIn: mocks.connectorToolDeleteToolsNotIn,+ upsertMany: mocks.connectorToolUpsertMany,+ })),+}));++vi.mock('@/libs/composio', () => ({+ getComposioClient: () => ({+ authConfigs: { create: mocks.authConfigsCreate, list: mocks.authConfigsList },+ connectedAccounts: { delete: mocks.connectedAccountsDelete, link: mocks.connectedAccountsLink },+ tools: { getRawComposioTools: mocks.getRawComposioTools },+ }),+}));++const caller = () => composioRouter.createCaller({ userId: 'user-1' } as any);++beforeEach(() => {+ vi.clearAllMocks();+ mocks.connectorQueryByIdentifiers.mockResolvedValue([]);+ mocks.connectorCreate.mockResolvedValue({ id: 'conn-new' });+ mocks.pluginFindById.mockResolvedValue(undefined);+});++describe('composioRouter.createConnection dual-write', () => {+ it('mirrors a pending connection into user_connectors + tools', async () => {+ mocks.getServerComposioAuthConfigId.mockReturnValue('ac_env');+ mocks.connectedAccountsLink.mockResolvedValue({ id: 'ca-1', redirectUrl: 'https://auth' });+ mocks.getRawComposioTools.mockResolvedValue({+ items: [{ description: 'send', inputParameters: { type: 'object' }, slug: 'GMAIL_SEND' }],+ });++ await caller().createConnection({ appSlug: 'GMAIL', identifier: 'gmail', label: 'Gmail' });++ // plugin write kept (backward compat)+ expect(mocks.pluginCreate).toHaveBeenCalledTimes(1);+ // connector projection created with PENDING composio metadata+ expect(mocks.connectorCreate).toHaveBeenCalledTimes(1);+ expect(mocks.connectorCreate.mock.calls[0][0]).toMatchObject({+ identifier: 'gmail',+ metadata: { composio: { connectedAccountId: 'ca-1', status: 'PENDING' } },+ status: 'disconnected',+ });+ // tools seeded+ expect(mocks.connectorToolUpsertMany).toHaveBeenCalledWith('conn-new', [+ expect.objectContaining({ toolName: 'GMAIL_SEND' }),+ ]);+ // pre-auth seed must NOT prune (tool list may be incomplete before auth)+ expect(mocks.connectorToolDeleteToolsNotIn).not.toHaveBeenCalled();+ });+});++describe('composioRouter.updateComposioPlugin dual-write', () => {+ const input = {+ appSlug: 'GMAIL',+ authConfigId: 'ac_env',+ connectedAccountId: 'ca-1',+ identifier: 'gmail',+ label: 'Gmail',+ status: 'ACTIVE',+ tools: [{ description: 'send', inputSchema: { type: 'object' }, name: 'GMAIL_SEND' }],+ };++ it('creates the connector projection (ACTIVE) + tools when none exists', async () => {+ mocks.connectorQueryByIdentifiers.mockResolvedValue([]);++ const res = await caller().updateComposioPlugin(input);++ expect(res).toEqual({ savedCount: 1 });+ expect(mocks.connectorCreate).toHaveBeenCalledTimes(1);+ expect(mocks.connectorCreate.mock.calls[0][0]).toMatchObject({+ metadata: { composio: { connectedAccountId: 'ca-1', status: 'ACTIVE' } },+ status: 'connected',+ });+ expect(mocks.connectorToolUpsertMany).toHaveBeenCalledWith('conn-new', [+ expect.objectContaining({ toolName: 'GMAIL_SEND' }),+ ]);+ // authoritative refresh prunes to exactly the provided set+ expect(mocks.connectorToolDeleteToolsNotIn).toHaveBeenCalledWith('conn-new', ['GMAIL_SEND']);+ });++ it('updates an existing connector projection instead of duplicating it', async () => {+ mocks.connectorQueryByIdentifiers.mockResolvedValue([{ id: 'conn-existing' }]);++ await caller().updateComposioPlugin(input);++ expect(mocks.connectorCreate).not.toHaveBeenCalled();+ expect(mocks.connectorUpdate).toHaveBeenCalledWith(+ 'conn-existing',+ expect.objectContaining({+ metadata: expect.objectContaining({+ composio: expect.objectContaining({ status: 'ACTIVE' }),+ }),+ status: 'connected',+ }),+ );+ expect(mocks.connectorToolUpsertMany).toHaveBeenCalledWith('conn-existing', expect.any(Array));+ expect(mocks.connectorToolDeleteToolsNotIn).toHaveBeenCalledWith('conn-existing', [+ 'GMAIL_SEND',+ ]);+ });++ it('prunes all connector tools when the refreshed list is empty', async () => {+ mocks.connectorQueryByIdentifiers.mockResolvedValue([{ id: 'conn-existing' }]);++ await caller().updateComposioPlugin({ ...input, tools: [] });++ // nothing to upsert, but the stale set is fully cleared+ expect(mocks.connectorToolUpsertMany).not.toHaveBeenCalled();+ expect(mocks.connectorToolDeleteToolsNotIn).toHaveBeenCalledWith('conn-existing', []);+ });+});++describe('composioRouter delete paths clean up the connector projection', () => {+ it('removeComposioPlugin deletes the connector row when present', async () => {+ mocks.connectorQueryByIdentifiers.mockResolvedValue([{ id: 'conn-existing' }]);++ await caller().removeComposioPlugin({ identifier: 'gmail' });++ expect(mocks.pluginDelete).toHaveBeenCalledWith('gmail');+ expect(mocks.connectorDelete).toHaveBeenCalledWith('conn-existing');+ });++ it('deleteConnection deletes both plugin and connector', async () => {+ mocks.connectedAccountsDelete.mockResolvedValue(undefined);+ mocks.connectorQueryByIdentifiers.mockResolvedValue([{ id: 'conn-existing' }]);++ await caller().deleteConnection({ connectedAccountId: 'ca-1', identifier: 'gmail' });++ expect(mocks.pluginDelete).toHaveBeenCalledWith('gmail');+ expect(mocks.connectorDelete).toHaveBeenCalledWith('conn-existing');+ });++ it('does not call connector delete when no projection exists', async () => {+ mocks.connectorQueryByIdentifiers.mockResolvedValue([]);++ await caller().removeComposioPlugin({ identifier: 'gmail' });++ expect(mocks.connectorDelete).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/composio.ts b/apps/server/src/routers/lambda/composio.tsindex 42c9d4d51c0..9fbaf5fa041 100644--- a/apps/server/src/routers/lambda/composio.ts+++ b/apps/server/src/routers/lambda/composio.ts@@ -3,20 +3,133 @@ import { TRPCError } from '@trpc/server';import { z } from 'zod';import { getServerComposioAuthConfigId } from '@/config/composio';+import { ConnectorModel } from '@/database/models/connector';+import { ConnectorToolModel } from '@/database/models/connectorTool';import { PluginModel } from '@/database/models/plugin';+import {+ type ComposioConnectorMetadata,+ type ConnectorMetadata,+ ConnectorSourceType,+ ConnectorStatus,+} from '@/database/schemas';import { getComposioClient } from '@/libs/composio';+import { inferCrudType } from '@/libs/mcp/utils';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';const composioProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {const client = getComposioClient();const pluginModel = new PluginModel(opts.ctx.serverDB, opts.ctx.userId);+ // Personal-scoped (no workspaceId/gateKeeper), matching PluginModel above:+ // Composio connections are personal today, and the runtime reads them back+ // with the same scoping (ComposioService is constructed with { db, userId }).+ const connectorModel = new ConnectorModel(opts.ctx.serverDB, opts.ctx.userId);+ const connectorToolModel = new ConnectorToolModel(opts.ctx.serverDB, opts.ctx.userId);return opts.next({- ctx: { ...opts.ctx, composioClient: client, pluginModel },+ ctx: { ...opts.ctx, composioClient: client, connectorModel, connectorToolModel, pluginModel },});});+type ComposioToolInput = {+ description?: string;+ inputSchema?: Record<string, unknown>;+ name: string;+};++/**+ * Dual-write helper: mirror a Composio connection into `user_connectors`+ * (+ `user_connector_tools`) so the runtime can resolve it without touching the+ * plugin table. Idempotent on (userId, identifier). The plugin-table write is+ * kept by the callers for backward compatibility; this only adds the connector+ * projection so new connections run off metadata while old ones fall back.+ */+async function upsertComposioConnector(+ connectorModel: ConnectorModel,+ connectorToolModel: ConnectorToolModel,+ params: {+ composio: ComposioConnectorMetadata;+ identifier: string;+ label: string;+ /**+ * When true, the connector's tool set is REPLACED by `tools`: rows missing+ * from the latest list are deleted. Use for the authoritative refresh+ * (updateComposioPlugin), where the runtime manifest is built from these+ * rows, so a shrunk/emptied tool list must not leave stale tools advertised.+ * Leave false for the pre-auth seed (createConnection), whose tool list may+ * be incomplete or empty before authorization.+ */+ replaceTools?: boolean;+ tools?: ComposioToolInput[];+ },+): Promise<void> {+ const metadata: ConnectorMetadata = {+ avatar: 'π',+ composio: params.composio,+ description: `Composio: ${params.label}`,+ };++ const status =+ params.composio.status === 'ACTIVE'+ ? ConnectorStatus.connected+ : params.composio.status === 'FAILED'+ ? ConnectorStatus.error+ : ConnectorStatus.disconnected;++ const [existing] = await connectorModel.queryByIdentifiers([params.identifier]);+ let connectorId: string;+ if (existing) {+ await connectorModel.update(existing.id, {+ metadata,+ name: params.label,+ sourceType: ConnectorSourceType.marketplace,+ status,+ });+ connectorId = existing.id;+ } else {+ const created = await connectorModel.create({+ identifier: params.identifier,+ isEnabled: true,+ metadata,+ name: params.label,+ sourceType: ConnectorSourceType.marketplace,+ status,+ });+ connectorId = created.id;+ }++ if (params.tools) {+ if (params.tools.length > 0) {+ await connectorToolModel.upsertMany(+ connectorId,+ params.tools.map((t) => ({+ crudType: inferCrudType(t.name),+ description: t.description,+ inputSchema: t.inputSchema,+ toolName: t.name,+ })),+ );+ }++ // Replace (not merge) so tools removed upstream stop being advertised.+ if (params.replaceTools) {+ await connectorToolModel.deleteToolsNotIn(+ connectorId,+ params.tools.map((t) => t.name),+ );+ }+ }+}++/** Remove the connector projection for a Composio identifier (tools cascade). */+async function deleteComposioConnector(+ connectorModel: ConnectorModel,+ identifier: string,+): Promise<void> {+ const [existing] = await connectorModel.queryByIdentifiers([identifier]);+ if (existing) await connectorModel.delete(existing.id);+}+export const composioRouter = router({createConnection: composioProcedure.input(@@ -113,6 +226,26 @@ export const composioRouter = router({type: 'plugin',});+ // Dual-write: mirror the (pending) connection into user_connectors so the+ // runtime can resolve it off metadata once it goes ACTIVE. Tools sync on+ // updateComposioPlugin; seed them here too when already fetched.+ await upsertComposioConnector(ctx.connectorModel, ctx.connectorToolModel, {+ composio: {+ appSlug,+ authConfigId,+ connectedAccountId: connReq.id,+ redirectUrl: connReq.redirectUrl,+ status: 'PENDING',+ },+ identifier,+ label,+ tools: manifest.api.map((a) => ({+ description: a.description,+ inputSchema: a.parameters as Record<string, unknown>,+ name: a.name,+ })),+ });+return {authConfigId,connectedAccountId: connReq.id,@@ -136,6 +269,7 @@ export const composioRouter = router({}await ctx.pluginModel.delete(input.identifier);+ await deleteComposioConnector(ctx.connectorModel, input.identifier);return { success: true };}),@@ -182,6 +316,7 @@ export const composioRouter = router({.input(z.object({ identifier: z.string() })).mutation(async ({ input, ctx }) => {await ctx.pluginModel.delete(input.identifier);+ await deleteComposioConnector(ctx.connectorModel, input.identifier);return { success: true };}),@@ -249,6 +384,17 @@ export const composioRouter = router({});}+ // Dual-write: project the active connection + tool list into the connector+ // tables so the runtime resolves this Composio server without the plugin+ // table. `tools` already carries the full manifest from the client.+ await upsertComposioConnector(ctx.connectorModel, ctx.connectorToolModel, {+ composio: { appSlug, authConfigId, connectedAccountId, redirectUrl, status },+ identifier,+ label,+ replaceTools: true,+ tools,+ });+return { savedCount: tools.length };}),});diff --git a/apps/server/src/routers/tools/composio.test.ts b/apps/server/src/routers/tools/composio.test.tsnew file mode 100644index 00000000000..38bd8404353--- /dev/null+++ b/apps/server/src/routers/tools/composio.test.ts@@ -0,0 +1,80 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { composioToolsRouter } from './composio';++const mocks = vi.hoisted(() => ({+ connectorQueryByIdentifiers: vi.fn(),+ pluginFindById: vi.fn(),+ processToolCallResult: vi.fn(),+ toolsExecute: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(async () => ({})) }));++vi.mock('@/database/models/connector', () => ({+ ConnectorModel: vi.fn().mockImplementation(() => ({+ queryByIdentifiers: mocks.connectorQueryByIdentifiers,+ })),+}));++vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(() => ({ findById: mocks.pluginFindById })),+}));++vi.mock('@/libs/composio', () => ({+ getComposioClient: () => ({ tools: { execute: mocks.toolsExecute } }),+}));++vi.mock('@/server/services/mcp', () => ({+ MCPService: { processToolCallResult: mocks.processToolCallResult },+}));++const caller = () => composioToolsRouter.createCaller({ userId: 'user-1' } as any);+const input = { identifier: 'gmail', toolArgs: { to: '[email protected]' }, toolSlug: 'GMAIL_SEND_EMAIL' };++beforeEach(() => {+ vi.clearAllMocks();+ mocks.connectorQueryByIdentifiers.mockResolvedValue([]);+ mocks.pluginFindById.mockResolvedValue(undefined);+ mocks.toolsExecute.mockResolvedValue({ data: 'ok' });+ mocks.processToolCallResult.mockResolvedValue({ content: 'ok', success: true });+});++describe('composioToolsRouter.executeAction', () => {+ it('resolves connectedAccountId from connector metadata (new path)', async () => {+ mocks.connectorQueryByIdentifiers.mockResolvedValue([+ { metadata: { composio: { connectedAccountId: 'ca-connector' } } },+ ]);++ await caller().executeAction(input);++ expect(mocks.toolsExecute).toHaveBeenCalledWith(+ 'GMAIL_SEND_EMAIL',+ expect.objectContaining({ connectedAccountId: 'ca-connector', userId: 'user-1' }),+ );+ expect(mocks.pluginFindById).not.toHaveBeenCalled();+ });++ it('falls back to plugin customParams when no connector projection exists', async () => {+ mocks.connectorQueryByIdentifiers.mockResolvedValue([]);+ mocks.pluginFindById.mockResolvedValue({+ customParams: { composio: { connectedAccountId: 'ca-plugin' } },+ });++ await caller().executeAction(input);++ expect(mocks.toolsExecute).toHaveBeenCalledWith(+ 'GMAIL_SEND_EMAIL',+ expect.objectContaining({ connectedAccountId: 'ca-plugin' }),+ );+ });++ it('throws NOT_FOUND when neither source has a connection', async () => {+ mocks.connectorQueryByIdentifiers.mockResolvedValue([]);+ mocks.pluginFindById.mockResolvedValue(undefined);++ await expect(caller().executeAction(input)).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mocks.toolsExecute).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/tools/composio.ts b/apps/server/src/routers/tools/composio.tsindex a82631cc458..0bd7550b0ac 100644--- a/apps/server/src/routers/tools/composio.ts+++ b/apps/server/src/routers/tools/composio.ts@@ -1,6 +1,7 @@import { TRPCError } from '@trpc/server';import { z } from 'zod';+import { ConnectorModel } from '@/database/models/connector';import { PluginModel } from '@/database/models/plugin';import { getComposioClient } from '@/libs/composio';import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';@@ -10,7 +11,8 @@ import { MCPService } from '@/server/services/mcp';const composioProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {const composioClient = getComposioClient();const pluginModel = new PluginModel(opts.ctx.serverDB, opts.ctx.userId);- return opts.next({ ctx: { ...opts.ctx, composioClient, pluginModel } });+ const connectorModel = new ConnectorModel(opts.ctx.serverDB, opts.ctx.userId);+ return opts.next({ ctx: { ...opts.ctx, composioClient, connectorModel, pluginModel } });});export const composioToolsRouter = router({@@ -23,12 +25,17 @@ export const composioToolsRouter = router({}),).mutation(async ({ ctx, input }) => {- // Resolve the connected account server-side from the caller's own plugin- // record (PluginModel is user-scoped). Never trust a connectedAccountId- // supplied by the client β that would let a user drive another user's- // connection.- const plugin = await ctx.pluginModel.findById(input.identifier);- const connectedAccountId = plugin?.customParams?.composio?.connectedAccountId;+ // Resolve the connected account server-side from the caller's own records+ // (models are user-scoped). Never trust a connectedAccountId supplied by+ // the client β that would let a user drive another user's connection.+ // Connector metadata first (new path); plugin customParams as fallback for+ // connections created before the connector projection existed.+ const [connector] = await ctx.connectorModel.queryByIdentifiers([input.identifier]);+ let connectedAccountId = connector?.metadata?.composio?.connectedAccountId;+ if (!connectedAccountId) {+ const plugin = await ctx.pluginModel.findById(input.identifier);+ connectedAccountId = plugin?.customParams?.composio?.connectedAccountId;+ }if (!connectedAccountId) {throw new TRPCError({diff --git a/packages/database/src/models/__tests__/connectorTool.test.ts b/packages/database/src/models/__tests__/connectorTool.test.tsindex 5e4d3c114dd..e2d753deab3 100644--- a/packages/database/src/models/__tests__/connectorTool.test.ts+++ b/packages/database/src/models/__tests__/connectorTool.test.ts@@ -336,6 +336,45 @@ describe('ConnectorToolModel', () => {});});+ describe('deleteToolsNotIn', () => {+ it('deletes rows whose toolName is not in the keep list', async () => {+ const model = new ConnectorToolModel(serverDB, userId);+ await model.upsertMany(connectorId, [+ tool({ toolName: 'keep_a' }),+ tool({ toolName: 'keep_b' }),+ tool({ toolName: 'stale' }),+ ]);++ await model.deleteToolsNotIn(connectorId, ['keep_a', 'keep_b']);++ const rows = await model.queryAllByConnectorIds([connectorId]);+ expect(rows.map((r) => r.toolName).sort()).toEqual(['keep_a', 'keep_b']);+ });++ it('deletes all tools for the connector when the keep list is empty', async () => {+ const model = new ConnectorToolModel(serverDB, userId);+ await model.upsertMany(connectorId, [tool({ toolName: 'a' }), tool({ toolName: 'b' })]);++ await model.deleteToolsNotIn(connectorId, []);++ expect(await model.queryAllByConnectorIds([connectorId])).toHaveLength(0);+ });++ it("does not touch another user's tools with the same name", async () => {+ const model = new ConnectorToolModel(serverDB, userId);+ await model.upsertMany(connectorId, [tool({ toolName: 'shared' })]);++ const otherModel = new ConnectorToolModel(serverDB, otherUserId);+ await otherModel.upsertMany(otherConnectorId, [tool({ toolName: 'shared' })]);++ // Pruning to empty for our connector must not affect the other user's row.+ await model.deleteToolsNotIn(connectorId, []);++ const theirs = await otherModel.queryAllByConnectorIds([otherConnectorId]);+ expect(theirs.map((r) => r.toolName)).toEqual(['shared']);+ });+ });+describe('ownership in workspace mode', () => {it('isolates personal-mode tools from workspace-scoped queries', async () => {// personal tool (workspaceId IS NULL)diff --git a/packages/database/src/models/connectorTool.ts b/packages/database/src/models/connectorTool.tsindex f9159828b81..93b06f10428 100644--- a/packages/database/src/models/connectorTool.ts+++ b/packages/database/src/models/connectorTool.ts@@ -1,4 +1,4 @@-import { and, eq, inArray, ne, sql } from 'drizzle-orm';+import { and, eq, inArray, ne, notInArray, sql } from 'drizzle-orm';import type {ConnectorToolPermission,@@ -86,6 +86,21 @@ export class ConnectorToolModel {});};+ /**+ * Prune a connector's tools down to `keepToolNames` β deletes any row whose+ * toolName is not in the list. Used to give a manifest refresh replace (not+ * merge) semantics, so tools removed upstream (e.g. a Composio account that+ * now exposes fewer tools) stop being advertised to the model. An empty+ * `keepToolNames` deletes every tool for the connector.+ */+ deleteToolsNotIn = async (userConnectorId: string, keepToolNames: string[]): Promise<void> => {+ const conditions = [eq(userConnectorTools.userConnectorId, userConnectorId), this.ownership()];+ if (keepToolNames.length > 0) {+ conditions.push(notInArray(userConnectorTools.toolName, keepToolNames));+ }+ await this.db.delete(userConnectorTools).where(and(...conditions));+ };+updatePermission = async (toolId: string, permission: ConnectorToolPermission): Promise<void> => {await this.db.update(userConnectorTools)diff --git a/packages/database/src/schemas/connector.ts b/packages/database/src/schemas/connector.tsindex eee7dd36ea1..7561eee4794 100644--- a/packages/database/src/schemas/connector.ts+++ b/packages/database/src/schemas/connector.ts@@ -100,6 +100,36 @@ export const ConnectorMcpConnectionType = {export type ConnectorMcpConnectionType =(typeof ConnectorMcpConnectionType)[keyof typeof ConnectorMcpConnectionType];+/**+ * Composio runtime config carried on `user_connectors.metadata.composio`.+ *+ * This is the source of truth for running a Composio connector at runtime+ * (manifest building + tool execution), replacing the reverse lookup into+ * `user_installed_plugins.customParams.composio`. `connectedAccountId` is the+ * only field strictly required to execute a tool; the rest support connection+ * management and list display.+ */+export interface ComposioConnectorMetadata {+ appSlug: string;+ authConfigId: string;+ connectedAccountId: string;+ redirectUrl?: string;+ /** 'PENDING' | 'ACTIVE' | 'FAILED' β Composio-side connection status */+ status: string;+}++/**+ * Typed shape of the `metadata` column. Keeps an index signature so existing+ * ad-hoc keys (e.g. `customHeaders`) and future extensions stay valid.+ */+export interface ConnectorMetadata {+ [key: string]: unknown;+ avatar?: string;+ composio?: ComposioConnectorMetadata;+ customHeaders?: Record<string, string>;+ description?: string;+}+// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ// user_connectors// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -166,7 +196,7 @@ export const userConnectors = pgTable(tokenExpiresAt: timestamptz('token_expires_at'),/** Safe non-sensitive metadata for display and future extensibility */- metadata: jsonb('metadata').$type<Record<string, unknown>>(),+ metadata: jsonb('metadata').$type<ConnectorMetadata>(),...timestamps,},diff --git a/src/server/services/composio/index.test.ts b/src/server/services/composio/index.test.tsnew file mode 100644index 00000000000..255247a71d2--- /dev/null+++ b/src/server/services/composio/index.test.ts@@ -0,0 +1,207 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { ComposioService } from './index';++const mocks = vi.hoisted(() => ({+ connectorQuery: vi.fn(),+ connectorQueryByIdentifiers: vi.fn(),+ connectorToolQueryAll: vi.fn(),+ isClientAvailable: vi.fn(),+ pluginFindById: vi.fn(),+ pluginQuery: vi.fn(),+ toolsExecute: vi.fn(),+}));++vi.mock('@/database/models/connector', () => ({+ ConnectorModel: vi.fn().mockImplementation(() => ({+ query: mocks.connectorQuery,+ queryByIdentifiers: mocks.connectorQueryByIdentifiers,+ })),+}));++vi.mock('@/database/models/connectorTool', () => ({+ ConnectorToolModel: vi.fn().mockImplementation(() => ({+ queryAllByConnectorIds: mocks.connectorToolQueryAll,+ })),+}));++vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(() => ({+ findById: mocks.pluginFindById,+ query: mocks.pluginQuery,+ })),+}));++vi.mock('@/libs/composio', () => ({+ getComposioClient: () => ({ tools: { execute: mocks.toolsExecute } }),+ isComposioClientAvailable: mocks.isClientAvailable,+}));++const service = () => new ComposioService({ db: {} as any, userId: 'user-1' });++const activeConnectorRow = (overrides: Record<string, any> = {}) => ({+ id: 'conn-gmail',+ identifier: 'gmail',+ isEnabled: true,+ metadata: {+ avatar: 'π',+ composio: { appSlug: 'GMAIL', connectedAccountId: 'ca-connector', status: 'ACTIVE' },+ },+ name: 'Gmail',+ ...overrides,+});++beforeEach(() => {+ vi.clearAllMocks();+ mocks.isClientAvailable.mockReturnValue(true);+ mocks.connectorQuery.mockResolvedValue([]);+ mocks.connectorQueryByIdentifiers.mockResolvedValue([]);+ mocks.connectorToolQueryAll.mockResolvedValue([]);+ mocks.pluginQuery.mockResolvedValue([]);+ mocks.pluginFindById.mockResolvedValue(undefined);+});++describe('ComposioService.getComposioManifests', () => {+ it('builds manifests from connector rows + connector tools (new path)', async () => {+ mocks.connectorQuery.mockResolvedValue([activeConnectorRow()]);+ mocks.connectorToolQueryAll.mockResolvedValue([+ {+ description: 'Send an email',+ inputSchema: { properties: { to: {} }, type: 'object' },+ toolName: 'GMAIL_SEND_EMAIL',+ userConnectorId: 'conn-gmail',+ },+ ]);++ const manifests = await service().getComposioManifests();++ expect(manifests).toHaveLength(1);+ expect(manifests[0].identifier).toBe('gmail');+ expect(manifests[0].api).toHaveLength(1);+ expect(manifests[0].api[0].name).toBe('GMAIL_SEND_EMAIL');+ expect(manifests[0].api[0].parameters).toEqual({ properties: { to: {} }, type: 'object' });+ // Plugin table must NOT be consulted once the connector covers the identifier.+ expect(mocks.pluginQuery).toHaveBeenCalledTimes(1); // called, but yields nothing new+ });++ it('falls back to plugin table for identifiers without a connector projection', async () => {+ mocks.connectorQuery.mockResolvedValue([]);+ mocks.pluginQuery.mockResolvedValue([+ {+ customParams: { composio: { status: 'ACTIVE' } },+ identifier: 'slack',+ manifest: {+ api: [{ description: 'post', name: 'SLACK_POST', parameters: { type: 'object' } }],+ meta: { avatar: 'βοΈ', title: 'Slack' },+ },+ },+ ]);++ const manifests = await service().getComposioManifests();++ expect(manifests).toHaveLength(1);+ expect(manifests[0].identifier).toBe('slack');+ expect(manifests[0].api[0].name).toBe('SLACK_POST');+ });++ it('unions both sources and dedupes by identifier (connector wins)', async () => {+ mocks.connectorQuery.mockResolvedValue([activeConnectorRow()]);+ mocks.connectorToolQueryAll.mockResolvedValue([+ { toolName: 'GMAIL_SEND_EMAIL', userConnectorId: 'conn-gmail' },+ ]);+ mocks.pluginQuery.mockResolvedValue([+ // Same identifier as the connector β must be dropped (connector wins).+ {+ customParams: { composio: { status: 'ACTIVE' } },+ identifier: 'gmail',+ manifest: { api: [{ name: 'GMAIL_OLD' }], meta: {} },+ },+ // Distinct identifier β included via fallback.+ {+ customParams: { composio: { status: 'ACTIVE' } },+ identifier: 'slack',+ manifest: { api: [{ name: 'SLACK_POST' }], meta: {} },+ },+ ]);++ const manifests = await service().getComposioManifests();++ expect(manifests.map((m) => m.identifier).sort()).toEqual(['gmail', 'slack']);+ const gmail = manifests.find((m) => m.identifier === 'gmail')!;+ // connector version (GMAIL_SEND_EMAIL), not the plugin's GMAIL_OLD+ expect(gmail.api[0].name).toBe('GMAIL_SEND_EMAIL');+ });++ it('ignores connector rows that are not ACTIVE or are disabled', async () => {+ mocks.connectorQuery.mockResolvedValue([+ activeConnectorRow({ metadata: { composio: { status: 'PENDING' } } }),+ activeConnectorRow({ id: 'c2', identifier: 'jira', isEnabled: false }),+ ]);++ const manifests = await service().getComposioManifests();++ expect(manifests).toHaveLength(0);+ });++ it('returns empty when there are no composio connections in either source', async () => {+ const manifests = await service().getComposioManifests();+ expect(manifests).toEqual([]);+ });+});++describe('ComposioService.executeComposioTool', () => {+ const params = { args: { to: '[email protected]' }, identifier: 'gmail', toolSlug: 'GMAIL_SEND_EMAIL' };++ it('returns COMPOSIO_NOT_CONFIGURED when the client is unavailable', async () => {+ mocks.isClientAvailable.mockReturnValue(false);++ const result = await service().executeComposioTool(params);++ expect(result.success).toBe(false);+ expect(result.error?.code).toBe('COMPOSIO_NOT_CONFIGURED');+ expect(mocks.toolsExecute).not.toHaveBeenCalled();+ });++ it('resolves connectedAccountId from connector metadata (new path)', async () => {+ mocks.connectorQueryByIdentifiers.mockResolvedValue([activeConnectorRow()]);+ mocks.toolsExecute.mockResolvedValue({ data: 'sent' });++ const result = await service().executeComposioTool(params);++ expect(result.success).toBe(true);+ expect(result.content).toBe('sent');+ expect(mocks.toolsExecute).toHaveBeenCalledWith(+ 'GMAIL_SEND_EMAIL',+ expect.objectContaining({ connectedAccountId: 'ca-connector', userId: 'user-1' }),+ );+ // connector hit β plugin fallback not consulted+ expect(mocks.pluginFindById).not.toHaveBeenCalled();+ });++ it('falls back to plugin customParams when the connector has no account', async () => {+ mocks.connectorQueryByIdentifiers.mockResolvedValue([]);+ mocks.pluginFindById.mockResolvedValue({+ customParams: { composio: { connectedAccountId: 'ca-plugin' } },+ });+ mocks.toolsExecute.mockResolvedValue({ data: 'sent' });++ const result = await service().executeComposioTool(params);++ expect(result.success).toBe(true);+ expect(mocks.toolsExecute).toHaveBeenCalledWith(+ 'GMAIL_SEND_EMAIL',+ expect.objectContaining({ connectedAccountId: 'ca-plugin' }),+ );+ });++ it('returns COMPOSIO_CONFIG_NOT_FOUND when neither source has an account', async () => {+ mocks.connectorQueryByIdentifiers.mockResolvedValue([]);+ mocks.pluginFindById.mockResolvedValue(undefined);++ const result = await service().executeComposioTool(params);++ expect(result.success).toBe(false);+ expect(result.error?.code).toBe('COMPOSIO_CONFIG_NOT_FOUND');+ expect(mocks.toolsExecute).not.toHaveBeenCalled();+ });+});diff --git a/src/server/services/composio/index.ts b/src/server/services/composio/index.tsindex 10ae8112046..59e09a618d9 100644--- a/src/server/services/composio/index.ts+++ b/src/server/services/composio/index.ts@@ -3,7 +3,10 @@ import type { LobeToolManifest } from '@lobechat/context-engine';import type { LobeChatDatabase } from '@lobechat/database';import debug from 'debug';+import { ConnectorModel } from '@/database/models/connector';+import { ConnectorToolModel } from '@/database/models/connectorTool';import { PluginModel } from '@/database/models/plugin';+import type { UserConnectorToolItem } from '@/database/schemas';import { getComposioClient, isComposioClientAvailable } from '@/libs/composio';import { type ToolExecutionResult } from '@/server/services/toolExecution/types';@@ -22,8 +25,19 @@ export interface ComposioServiceOptions {userId?: string;}+/**+ * Server-side Composio runtime.+ *+ * Source of truth is `user_connectors` (+ `user_connector_tools`): a Composio+ * connection lives on a connector row whose `metadata.composio` carries the+ * runtime config (`connectedAccountId`). The legacy `user_installed_plugins`+ * projection is still read as a **fallback** for connections created before the+ * dual-write landed, so no data migration is required.+ */export class ComposioService {private pluginModel?: PluginModel;+ private connectorModel?: ConnectorModel;+ private connectorToolModel?: ConnectorToolModel;private userId?: string;constructor(options: ComposioServiceOptions = {}) {@@ -31,7 +45,10 @@ export class ComposioService {this.userId = userId;if (db && userId) {+ // Personal-scoped, mirroring the write path in the composio lambda router.this.pluginModel = new PluginModel(db, userId);+ this.connectorModel = new ConnectorModel(db, userId);+ this.connectorToolModel = new ConnectorToolModel(db, userId);}log(@@ -55,7 +72,7 @@ export class ComposioService {};}- if (!this.pluginModel || !this.userId) {+ if (!this.userId || (!this.connectorModel && !this.pluginModel)) {return {content: 'Composio service is not properly initialized',error: {@@ -67,17 +84,8 @@ export class ComposioService {}try {- const plugin = await this.pluginModel.findById(identifier);- if (!plugin) {- return {- content: `Composio server "${identifier}" not found in database`,- error: { code: 'COMPOSIO_SERVER_NOT_FOUND', message: `Server ${identifier} not found` },- success: false,- };- }-- const composioParams = plugin.customParams?.composio;- if (!composioParams?.connectedAccountId) {+ const connectedAccountId = await this.resolveConnectedAccountId(identifier);+ if (!connectedAccountId) {return {content: `Composio configuration not found for server "${identifier}"`,error: {@@ -88,8 +96,6 @@ export class ComposioService {};}- const { connectedAccountId } = composioParams;-log('executeComposioTool: calling Composio API with connectedAccountId=%s',connectedAccountId,@@ -143,30 +149,106 @@ export class ComposioService {}}- async getComposioManifests(): Promise<LobeToolManifest[]> {- if (!this.pluginModel) {- log('getComposioManifests: pluginModel not available, returning empty array');- return [];+ /**+ * Resolve the Composio `connectedAccountId` for an identifier.+ * Connector metadata first (new path); plugin customParams as fallback (old+ * connections without a connector projection).+ */+ private async resolveConnectedAccountId(identifier: string): Promise<string | undefined> {+ if (this.connectorModel) {+ const [connector] = await this.connectorModel.queryByIdentifiers([identifier]);+ const fromConnector = connector?.metadata?.composio?.connectedAccountId;+ if (fromConnector) return fromConnector;}- try {- const allPlugins = await this.pluginModel.query();-- const composioPlugins = allPlugins.filter(- (plugin) =>- VALID_COMPOSIO_IDENTIFIERS.has(plugin.identifier) &&- plugin.customParams?.composio?.status === 'ACTIVE',- );+ if (this.pluginModel) {+ const plugin = await this.pluginModel.findById(identifier);+ return plugin?.customParams?.composio?.connectedAccountId;+ }- log('getComposioManifests: found %d authenticated Composio plugins', composioPlugins.length);+ return undefined;+ }- const manifests: LobeToolManifest[] = composioPlugins- .map((plugin) => {- if (!plugin.manifest) return null;+ async getComposioManifests(): Promise<LobeToolManifest[]> {+ const manifests: LobeToolManifest[] = [];+ const coveredIdentifiers = new Set<string>();++ // 1. Connector-based (new path): rows whose metadata.composio marks them as+ // Composio connectors and are ACTIVE. Tool defs come from+ // user_connector_tools (all of them, so disabled tools stay visible for+ // downstream permission patching).+ if (this.connectorModel && this.connectorToolModel) {+ try {+ const connectors = await this.connectorModel.query();+ const composioConnectors = connectors.filter(+ (c) => c.isEnabled && c.metadata?.composio?.status === 'ACTIVE',+ );++ if (composioConnectors.length > 0) {+ const tools = await this.connectorToolModel.queryAllByConnectorIds(+ composioConnectors.map((c) => c.id),+ );+ const toolsByConnector = new Map<string, UserConnectorToolItem[]>();+ for (const tool of tools) {+ const list = toolsByConnector.get(tool.userConnectorId) ?? [];+ list.push(tool);+ toolsByConnector.set(tool.userConnectorId, list);+ }++ for (const connector of composioConnectors) {+ const connectorTools = toolsByConnector.get(connector.id) ?? [];+ if (connectorTools.length === 0) continue;++ const appType = COMPOSIO_APP_TYPES.find((t) => t.identifier === connector.identifier);+ const label = connector.name || appType?.label || connector.identifier;++ manifests.push({+ api: connectorTools.map((t) => ({+ description: t.description ?? '',+ name: t.toolName,+ parameters: (t.inputSchema ?? { properties: {}, type: 'object' }) as Record<+ string,+ unknown+ >,+ })),+ author: 'Composio',+ homepage: 'https://composio.dev',+ identifier: connector.identifier,+ meta: {+ avatar: connector.metadata?.avatar || 'βοΈ',+ description: `Composio: ${label}`,+ tags: ['composio', 'mcp'],+ title: label,+ },+ type: 'builtin',+ version: '1.0.0',+ } as LobeToolManifest);+ coveredIdentifiers.add(connector.identifier);+ }+ }+ } catch (error) {+ console.error('ComposioService.getComposioManifests (connector) error: %O', error);+ }+ }+ // 2. Plugin-based fallback (old path): only for identifiers not already+ // covered by a connector projection. Preserves manifests for connections+ // created before dual-write, so no migration is needed.+ if (this.pluginModel) {+ try {+ const allPlugins = await this.pluginModel.query();+ const composioPlugins = allPlugins.filter(+ (plugin) =>+ VALID_COMPOSIO_IDENTIFIERS.has(plugin.identifier) &&+ plugin.customParams?.composio?.status === 'ACTIVE' &&+ !coveredIdentifiers.has(plugin.identifier),+ );++ for (const plugin of composioPlugins) {+ if (!plugin.manifest) continue;const appType = COMPOSIO_APP_TYPES.find((t) => t.identifier === plugin.identifier);- return {+ manifests.push({api: plugin.manifest.api || [],author: 'Composio',homepage: 'https://composio.dev',@@ -179,16 +261,15 @@ export class ComposioService {},type: 'builtin',version: '1.0.0',- };- })- .filter(Boolean) as LobeToolManifest[];+ } as LobeToolManifest);+ }+ } catch (error) {+ console.error('ComposioService.getComposioManifests (plugin) error: %O', error);+ }+ }- log('getComposioManifests: returning %d manifests', manifests.length);+ log('getComposioManifests: returning %d manifests', manifests.length);- return manifests;- } catch (error) {- console.error('ComposioService.getComposioManifests error: %O', error);- return [];- }+ return manifests;}}