Skip to content

🤯 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.

🐛 fix: make workspace-agent Composio connectors work end-to-end (resolution + runtime auth + profile UI) (#17220)

LiJian1d89b7ce2e4d
diff --git a/apps/server/src/modules/AgentRuntime/adapters/composioConnectedIds.test.ts b/apps/server/src/modules/AgentRuntime/adapters/composioConnectedIds.test.ts
new file mode 100644
index 00000000000..908d8f4cced
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/composioConnectedIds.test.ts
@@ -0,0 +1,92 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ConnectorModel } from '@/database/models/connector';
+import { PluginModel } from '@/database/models/plugin';
+
+import { loadConnectedComposioIds } from './composioConnectedIds';
+
+vi.mock('@/database/models/plugin', () => ({ PluginModel: vi.fn() }));
+vi.mock('@/database/models/connector', () => ({ ConnectorModel: vi.fn() }));
+
+describe('loadConnectedComposioIds', () => {
+ // Regression: agent-scoped Composio connections are NOT projected into the
+ // plugin table, so the plugin-only read reported them "not connected" and the
+ // model re-ran the OAuth connect flow (`connectComposioService`) even though a
+ // valid workspace-agent connection existed in `user_connectors`.
+ let pluginModelMock: any;
+ let connectorModelMock: any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ pluginModelMock = { query: vi.fn().mockResolvedValue([]) };
+ connectorModelMock = { resolveAll: vi.fn().mockResolvedValue([]) };
+ vi.mocked(PluginModel).mockImplementation(() => pluginModelMock);
+ vi.mocked(ConnectorModel).mockImplementation(() => connectorModelMock);
+ });
+
+ it('includes an agent-scoped connector that is absent from the plugin table', async () => {
+ pluginModelMock.query.mockResolvedValueOnce([]); // nothing projected to plugins
+ connectorModelMock.resolveAll.mockResolvedValueOnce([
+ {
+ identifier: 'gmail',
+ isEnabled: true,
+ metadata: { composio: { connectedAccountId: 'ca_1', status: 'ACTIVE' } },
+ },
+ ]);
+
+ const ids = await loadConnectedComposioIds({} as any, 'user_test', 'ws-1', 'agent-1');
+
+ expect(ids.has('gmail')).toBe(true);
+ // scoped to the caller's workspace + resolved agent-aware
+ expect(ConnectorModel).toHaveBeenCalledWith(expect.anything(), 'user_test', 'ws-1');
+ expect(connectorModelMock.resolveAll).toHaveBeenCalledWith('agent-1');
+ });
+
+ it('still counts a base connection projected into the plugin table', async () => {
+ pluginModelMock.query.mockResolvedValueOnce([
+ { customParams: { composio: { status: 'ACTIVE' } }, identifier: 'gmail' },
+ ]);
+
+ const ids = await loadConnectedComposioIds({} as any, 'user_test', undefined, undefined);
+
+ expect(ids.has('gmail')).toBe(true);
+ });
+
+ it('excludes a disabled connector and a non-Composio identifier', async () => {
+ connectorModelMock.resolveAll.mockResolvedValueOnce([
+ { identifier: 'gmail', isEnabled: false, metadata: { composio: { status: 'ACTIVE' } } },
+ {
+ identifier: 'my-custom-mcp',
+ isEnabled: true,
+ metadata: { composio: { status: 'ACTIVE' } },
+ },
+ ]);
+
+ const ids = await loadConnectedComposioIds({} as any, 'user_test', 'ws-1', 'agent-1');
+
+ expect(ids.has('gmail')).toBe(false); // disabled connector row
+ expect(ids.has('my-custom-mcp')).toBe(false); // not a Composio app type
+ });
+
+ it('excludes a non-ACTIVE connector (pending / failed)', async () => {
+ connectorModelMock.resolveAll.mockResolvedValueOnce([
+ { identifier: 'gmail', isEnabled: true, metadata: { composio: { status: 'PENDING' } } },
+ ]);
+
+ const ids = await loadConnectedComposioIds({} as any, 'user_test', 'ws-1', 'agent-1');
+
+ expect(ids.has('gmail')).toBe(false);
+ });
+
+ it('falls back to the plugin-based set if the connector lookup throws', async () => {
+ pluginModelMock.query.mockResolvedValueOnce([
+ { customParams: { composio: { status: 'ACTIVE' } }, identifier: 'gmail' },
+ ]);
+ connectorModelMock.resolveAll.mockRejectedValueOnce(new Error('db down'));
+
+ const ids = await loadConnectedComposioIds({} as any, 'user_test', 'ws-1', 'agent-1');
+
+ expect(ids.has('gmail')).toBe(true); // plugin-based result survives the error
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/composioConnectedIds.ts b/apps/server/src/modules/AgentRuntime/adapters/composioConnectedIds.ts
new file mode 100644
index 00000000000..30a24cf0601
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/composioConnectedIds.ts
@@ -0,0 +1,63 @@
+import { COMPOSIO_APP_TYPES } from '@lobechat/const';
+import type { LobeChatDatabase } from '@lobechat/database';
+import debug from 'debug';
+
+import { ConnectorModel } from '@/database/models/connector';
+import { PluginModel } from '@/database/models/plugin';
+
+const log = debug('lobe-server:composio-connected-ids');
+
+/**
+ * Composio service identifiers currently connected (ACTIVE) in the caller's
+ * scope, read from BOTH sources of truth:
+ * - `user_installed_plugins` (legacy projection): personal / workspace *base*
+ * Composio connections.
+ * - `user_connectors` (`resolveAll`, agent + workspace aware): AGENT-scoped
+ * connections. These are intentionally NOT projected into the plugin table
+ * (that projection carries no `agent_id`), so a workspace-agent's Composio
+ * connection lives only on the connector row's `metadata.composio`.
+ *
+ * Without the connector union, an agent-scoped Composio connection reads as
+ * "not connected", and the model re-runs `connectComposioService` (the OAuth
+ * connect flow) instead of calling the already-authorized tool.
+ */
+export async function loadConnectedComposioIds(
+ serverDB: LobeChatDatabase,
+ userId: string,
+ workspaceId: string | undefined,
+ agentId: string | undefined,
+): Promise<Set<string>> {
+ const validComposioIds = new Set(COMPOSIO_APP_TYPES.map((tool) => tool.identifier));
+ const connected = new Set<string>();
+
+ const pluginModel = new PluginModel(serverDB, userId, workspaceId);
+ const allPlugins = await pluginModel.query();
+ for (const plugin of allPlugins) {
+ if (
+ validComposioIds.has(plugin.identifier) &&
+ (plugin.customParams as any)?.composio?.status === 'ACTIVE'
+ ) {
+ connected.add(plugin.identifier);
+ }
+ }
+
+ try {
+ const connectorModel = new ConnectorModel(serverDB, userId, workspaceId);
+ // Agent-aware: resolves the agent's own Composio connectors plus the base
+ // (workspace/personal) ones, scoped by the model's workspace ownership.
+ const connectors = await connectorModel.resolveAll(agentId);
+ for (const connector of connectors) {
+ if (
+ connector.isEnabled &&
+ validComposioIds.has(connector.identifier) &&
+ connector.metadata?.composio?.status === 'ACTIVE'
+ ) {
+ connected.add(connector.identifier);
+ }
+ }
+ } catch (error) {
+ log('loadConnectedComposioIds: connector-based lookup failed: %O', error);
+ }
+
+ return connected;
+}
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
index f45794417b0..a614874ba60 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
@@ -30,7 +30,6 @@ import { composioEnv } from '@/config/composio';
import { AgentModel } from '@/database/models/agent';
import { FileModel } from '@/database/models/file';
import { MessageModel as MessageModelClass } from '@/database/models/message';
-import { PluginModel } from '@/database/models/plugin';
import { TopicModel } from '@/database/models/topic';
import { UserModel } from '@/database/models/user';
import { UserPersonaModel } from '@/database/models/userMemory/persona';
@@ -42,6 +41,7 @@ import { toAgentContextDocuments } from '@/utils/agentDocumentContextMapping';
import type { RuntimeExecutorContext } from '../context';
import { buildPostProcessUrl, log, resolveRuntimeHistoryCount } from '../executorHelpers';
+import { loadConnectedComposioIds } from './composioConnectedIds';
import {
resolveServerCallLlmContextHints,
type ServerCallLlmContextHints,
@@ -308,17 +308,14 @@ export const buildServerCallLlmContext = async ({
let composioServicesListStr = '';
if (ctx.serverDB && ctx.userId && !!composioEnv.COMPOSIO_API_KEY) {
try {
- const pluginModel = new PluginModel(ctx.serverDB, ctx.userId, ctx.workspaceId);
- const allPlugins = await pluginModel.query();
- const validComposioIds = new Set(COMPOSIO_APP_TYPES.map((tool) => tool.identifier));
- const connectedIds = new Set(
- allPlugins
- .filter(
- (plugin) =>
- validComposioIds.has(plugin.identifier) &&
- (plugin.customParams as any)?.composio?.status === 'ACTIVE',
- )
- .map((plugin) => plugin.identifier),
+ // Connected = ACTIVE Composio connections across BOTH the legacy plugin
+ // projection AND the connector table (agent-scoped connections live only
+ // in the latter — see loadConnectedComposioIds).
+ const connectedIds = await loadConnectedComposioIds(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId,
+ agentId,
);
// Disabled services are dropped from both lists — not surfaced as
// "connected, use directly" nor as "available to connect".
@@ -382,16 +379,13 @@ export const buildServerCallLlmContext = async ({
if (composioEnv.COMPOSIO_API_KEY) {
try {
- const pluginModel = new PluginModel(ctx.serverDB, ctx.userId, ctx.workspaceId);
- const allPlugins = await pluginModel.query();
- const connectedComposioIds = new Set(
- allPlugins
- .filter(
- (plugin) =>
- composioIdentifiers.has(plugin.identifier) &&
- (plugin.customParams as any)?.composio?.status === 'ACTIVE',
- )
- .map((plugin) => plugin.identifier),
+ // Agent-scoped connections aren't in the plugin table — union the
+ // connector table so the builder marks them installed too.
+ const connectedComposioIds = await loadConnectedComposioIds(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId,
+ editingAgentId,
);
for (const tool of COMPOSIO_APP_TYPES) {
officialTools.push({
diff --git a/apps/server/src/routers/lambda/__tests__/composio.workspaceScope.test.ts b/apps/server/src/routers/lambda/__tests__/composio.workspaceScope.test.ts
new file mode 100644
index 00000000000..e928f4e17fc
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/composio.workspaceScope.test.ts
@@ -0,0 +1,157 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentModel } from '@/database/models/agent';
+import { ConnectorModel } from '@/database/models/connector';
+import { ConnectorToolModel } from '@/database/models/connectorTool';
+import { PluginModel } from '@/database/models/plugin';
+
+import { composioRouter } from '../composio';
+
+// `vi.mock` is hoisted above the imports at runtime, so the mocks are active
+// when the router module is evaluated. Kept below the imports to satisfy
+// `import-x/first`.
+vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));
+vi.mock('@/database/models/connector', () => ({ ConnectorModel: vi.fn() }));
+vi.mock('@/database/models/connectorTool', () => ({ ConnectorToolModel: vi.fn() }));
+vi.mock('@/database/models/plugin', () => ({ PluginModel: vi.fn() }));
+// A pre-configured auth config short-circuits the discovery branch.
+vi.mock('@/config/composio', () => ({ getServerComposioAuthConfigId: () => 'auth-cfg-1' }));
+vi.mock('@/libs/composio', () => ({
+ getComposioClient: () => ({
+ connectedAccounts: { link: async () => ({ id: 'acc-1', redirectUrl: 'http://redirect' }) },
+ tools: { getRawComposioTools: async () => ({ items: [] }) },
+ }),
+}));
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');
+ // The real `wsCompatProcedure` validates a Better-Auth session; for unit tests
+ // we skip auth and rely on the test ctx already carrying userId/workspaceId.
+ return {
+ requireWorkspaceRoleWhenScoped: () => mod.trpc.middleware(async (opts: any) => opts.next()),
+ wsCompatProcedure: mod.trpc.procedure,
+ };
+});
+vi.mock('@/libs/trpc/lambda/middleware', () => ({
+ serverDatabase: async (opts: any) =>
+ opts.next({ ctx: { ...opts.ctx, serverDB: opts.ctx.serverDB ?? {} } }),
+}));
+
+describe('composioRouter — workspace scoping (workspace-agent connector bug)', () => {
+ // Regression for the bug where a Composio connection bound to a WORKSPACE agent
+ // landed as (workspace_id=NULL, agent_id=agent) because the composio procedure
+ // built a personal-scoped ConnectorModel. The workspace runtime (ownership() =
+ // workspace_id = wsId) then never resolved it, so the tool showed "not
+ // installed". The fix threads ctx.workspaceId into the model constructor.
+ let connectorModelMock: any;
+ let connectorToolModelMock: any;
+ let pluginModelMock: any;
+ let agentModelMock: any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ connectorModelMock = {
+ create: vi.fn().mockResolvedValue({ id: 'conn-new' }),
+ findScopedByIdentifier: vi.fn().mockResolvedValue(null),
+ update: vi.fn().mockResolvedValue(undefined),
+ };
+ connectorToolModelMock = { deleteToolsNotIn: vi.fn(), upsertMany: vi.fn() };
+ pluginModelMock = { create: vi.fn(), findById: vi.fn(), update: vi.fn() };
+ agentModelMock = { existsOwnedById: vi.fn().mockResolvedValue(true) };
+ vi.mocked(ConnectorModel).mockImplementation(() => connectorModelMock);
+ vi.mocked(ConnectorToolModel).mockImplementation(() => connectorToolModelMock);
+ vi.mocked(PluginModel).mockImplementation(() => pluginModelMock);
+ vi.mocked(AgentModel).mockImplementation(() => agentModelMock);
+ });
+
+ const callerFor = (workspaceId?: string) =>
+ composioRouter.createCaller({
+ serverDB: {},
+ userId: 'user_test',
+ workspaceId: workspaceId ?? null,
+ } as any);
+
+ const agentInput = {
+ agentId: 'agent-1',
+ appSlug: 'gmail',
+ identifier: 'gmail',
+ label: 'Gmail',
+ };
+
+ it('builds the connector model WITH the workspaceId, so a workspace-agent connection is workspace-scoped', async () => {
+ await callerFor('ws-1').createConnection(agentInput);
+
+ // The crux: before the fix the model was `new ConnectorModel(db, userId)`
+ // (no wsId) → row (workspace_id=NULL, agent_id=agent-1). Now it carries wsId.
+ expect(ConnectorModel).toHaveBeenCalledWith(expect.anything(), 'user_test', 'ws-1');
+ expect(connectorToolModelMock).toBeDefined();
+ expect(ConnectorToolModel).toHaveBeenCalledWith(expect.anything(), 'user_test', 'ws-1');
+ // The row is agent-scoped (agent_id set), and together with wsId that makes it
+ // the workspace-agent dimension the runtime can resolve.
+ expect(connectorModelMock.create).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agent-1', identifier: 'gmail' }),
+ );
+ });
+
+ it('scopes the agent edit-rights check to the workspace', async () => {
+ await callerFor('ws-1').createConnection(agentInput);
+
+ expect(AgentModel).toHaveBeenCalledWith(expect.anything(), 'user_test', 'ws-1');
+ expect(agentModelMock.existsOwnedById).toHaveBeenCalledWith('agent-1');
+ });
+
+ it('skips the legacy plugin-table projection for agent connections', async () => {
+ await callerFor('ws-1').createConnection(agentInput);
+
+ expect(pluginModelMock.create).not.toHaveBeenCalled();
+ });
+
+ it('personal connection (no workspace) still builds a personal-scoped model — unchanged', async () => {
+ await callerFor().createConnection({ appSlug: 'gmail', identifier: 'gmail', label: 'Gmail' });
+
+ expect(ConnectorModel).toHaveBeenCalledWith(expect.anything(), 'user_test', undefined);
+ // Personal (non-agent) connections DO keep writing the legacy plugin row.
+ expect(pluginModelMock.create).toHaveBeenCalled();
+ });
+
+ it('updateComposioPlugin also scopes the model + agent check to the workspace', async () => {
+ await callerFor('ws-1').updateComposioPlugin({
+ agentId: 'agent-1',
+ appSlug: 'gmail',
+ authConfigId: 'auth-cfg-1',
+ connectedAccountId: 'acc-1',
+ identifier: 'gmail',
+ label: 'Gmail',
+ status: 'ACTIVE',
+ tools: [],
+ });
+
+ expect(ConnectorModel).toHaveBeenCalledWith(expect.anything(), 'user_test', 'ws-1');
+ expect(AgentModel).toHaveBeenCalledWith(expect.anything(), 'user_test', 'ws-1');
+ expect(agentModelMock.existsOwnedById).toHaveBeenCalledWith('agent-1');
+ });
+
+ it('blocks a non-owner member from overwriting another member’s workspace connection', async () => {
+ // buildWorkspaceWhere makes workspace rows writable workspace-wide; the
+ // row-level gate must stop a plain member from clobbering another member's
+ // Composio connection — before any remote account is created.
+ connectorModelMock.findScopedByIdentifier.mockResolvedValueOnce({
+ id: 'conn-other',
+ identifier: 'gmail',
+ userId: 'another-user',
+ });
+
+ await expect(
+ composioRouter
+ .createCaller({
+ serverDB: {},
+ userId: 'user_test',
+ workspaceId: 'ws-1',
+ workspaceRole: 'member',
+ } as any)
+ .createConnection({ appSlug: 'gmail', identifier: 'gmail', label: 'Gmail' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ expect(connectorModelMock.create).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/composio.ts b/apps/server/src/routers/lambda/composio.ts
index 6457e3d10a9..e5f25be2a6b 100644
--- a/apps/server/src/routers/lambda/composio.ts
+++ b/apps/server/src/routers/lambda/composio.ts
@@ -3,6 +3,10 @@ import { type ToolManifest } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
+import {
+ requireWorkspaceRoleWhenScoped,
+ wsCompatProcedure,
+} from '@/business/server/trpc-middlewares/workspaceAuth';
import { getServerComposioAuthConfigId } from '@/config/composio';
import { AgentModel } from '@/database/models/agent';
import { ConnectorModel } from '@/database/models/connector';
@@ -16,23 +20,61 @@ import {
} from '@/database/schemas';
import { getComposioClient } from '@/libs/composio';
import { inferCrudType } from '@/libs/mcp/utils';
-import { authedProcedure, router } from '@/libs/trpc/lambda';
+import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-const composioProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
+import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';
+
+const composioProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = 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);
+ const wsId = ctx.workspaceId ?? undefined;
+ // Workspace-scoped. A Composio connection bound to a workspace agent (or a
+ // workspace's base tools) must land as a workspace-dimension row
+ // (workspace_id = wsId); otherwise the correctly workspace-scoped runtime
+ // (ComposioService/aiAgent build the model WITH wsId) can never resolve it and
+ // the tool shows as "not installed". Personal mode (wsId undefined) is
+ // unchanged — the model falls back to `workspace_id IS NULL`. No gatekeeper:
+ // Composio rows carry no encrypted credentials (the account lives in plaintext
+ // `metadata.composio.connectedAccountId`).
+ const pluginModel = new PluginModel(ctx.serverDB, ctx.userId, wsId);
+ const connectorModel = new ConnectorModel(ctx.serverDB, ctx.userId, wsId);
+ const connectorToolModel = new ConnectorToolModel(ctx.serverDB, ctx.userId, wsId);
return opts.next({
- ctx: { ...opts.ctx, composioClient: client, connectorModel, connectorToolModel, pluginModel },
+ ctx: { ...ctx, composioClient: client, connectorModel, connectorToolModel, pluginModel },
});
});
+// Writes: in a workspace, require at least the member role (blocks viewers).
+// Personal mode passes through. Row-level creator/owner enforcement is layered
+// on top per-mutation via `assertComposioRowManageable` (mirrors the native
+// connector router's connectorWriteProcedure + assertWorkspaceRowManageable).
+const composioWriteProcedure = composioProcedure.use(requireWorkspaceRoleWhenScoped('member'));
+
+/**
+ * Before mutating (overwriting/deleting) a Composio connection in a workspace,
+ * assert the caller may manage the existing row: creator or workspace owner.
+ * `buildWorkspaceWhere` makes workspace rows writable workspace-wide, so without
+ * this any member could overwrite/remove another member's connection by
+ * identifier/agentId. Checked BEFORE any external side effect (Composio account
+ * link/delete). No-op in personal mode.
+ */
+async function assertComposioRowManageable(
+ ctx: {
+ connectorModel: ConnectorModel;
+ userId: string;
+ workspaceId?: string | null;
+ workspaceRole?: string;
+ },
+ identifier: string,
+ agentId?: string,
+): Promise<void> {
+ if (!ctx.workspaceId) return;
+ const existing = await ctx.connectorModel.findScopedByIdentifier(identifier, agentId);
+ if (existing) assertWorkspaceRowManageable(ctx, existing.userId, 'connector');
+}
+
type ComposioToolInput = {
description?: string;
inputSchema?: Record<string, unknown>;
@@ -154,15 +196,16 @@ async function assertCanEditAgent(
db: LobeChatDatabase,
userId: string,
agentId: string,
+ workspaceId?: string,
): Promise<void> {
- const agentModel = new AgentModel(db, userId);
+ const agentModel = new AgentModel(db, userId, workspaceId);
if (!(await agentModel.existsOwnedById(agentId))) {
throw new TRPCError({ code: 'FORBIDDEN', message: 'Agent not found or not editable' });
}
}
export const composioRouter = router({
- createConnection: composioProcedure
+ createConnection: composioWriteProcedure
.input(
z.object({
/** Bind the connection to this agent (Agent > Personal). Requires edit rights. */
@@ -176,7 +219,11 @@ export const composioRouter = router({
const { appSlug, identifier, label, agentId } = input;
const { userId } = ctx;
- if (agentId) await assertCanEditAgent(ctx.serverDB, userId, agentId);
+ if (agentId)
+ await assertCanEditAgent(ctx.serverDB, userId, agentId, ctx.workspaceId ?? undefined);
+ // Block overwriting another member's workspace connection before creating
+ // the remote Composio account.
+ await assertComposioRowManageable(ctx, identifier, agentId);
const callbackUrl = `${process.env.APP_URL || process.env.NEXTAUTH_URL || ''}/api/composio/oauth/callback`;
@@ -302,7 +349,7 @@ export const composioRouter = router({
};
}),
- deleteConnection: composioProcedure
+ deleteConnection: composioWriteProcedure
.input(
z.object({
agentId: z.string().optional(),
@@ -311,6 +358,9 @@ export const composioRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ // Gate before deleting the remote account, so a non-creator/owner member
+ // can't grief another member's Composio connection.
+ await assertComposioRowManageable(ctx, input.identifier, input.agentId);
try {
await (ctx.composioClient.connectedAccounts as any).delete(input.connectedAccountId);
} catch (error) {
@@ -363,15 +413,16 @@ export const composioRouter = router({
}
}),
- removeComposioPlugin: composioProcedure
+ removeComposioPlugin: composioWriteProcedure
.input(z.object({ agentId: z.string().optional(), identifier: z.string() }))
.mutation(async ({ input, ctx }) => {
+ await assertComposioRowManageable(ctx, input.identifier, input.agentId);
if (!input.agentId) await ctx.pluginModel.delete(input.identifier);
await deleteComposioConnector(ctx.connectorModel, input.identifier, input.agentId);
return { success: true };
}),
- updateComposioPlugin: composioProcedure
+ updateComposioPlugin: composioWriteProcedure
.input(
z.object({
/** Bind the connection to this agent (Agent > Personal). Requires edit rights. */
@@ -405,7 +456,9 @@ export const composioRouter = router({
agentId,
} = input;
- if (agentId) await assertCanEditAgent(ctx.serverDB, ctx.userId, agentId);
+ if (agentId)
+ await assertCanEditAgent(ctx.serverDB, ctx.userId, agentId, ctx.workspaceId ?? undefined);
+ await assertComposioRowManageable(ctx, identifier, agentId);
const existingPlugin = await ctx.pluginModel.findById(identifier);
diff --git a/apps/server/src/routers/tools/composio.ts b/apps/server/src/routers/tools/composio.ts
index 4ace05f8be1..785322af5ef 100644
--- a/apps/server/src/routers/tools/composio.ts
+++ b/apps/server/src/routers/tools/composio.ts
@@ -1,18 +1,29 @@
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
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';
+import { publicProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { MCPService } from '@/server/services/mcp';
-const composioProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
+// wsCompatProcedure (not authedProcedure): when a request carries X-Workspace-Id
+// the models below resolve in that workspace and buildWorkspaceWhere drops the
+// userId filter, so honoring the header without verifying workspace membership
+// would let any signed-in user execute another workspace's connected account.
+// The cloud override validates membership; the OSS stub is a passthrough.
+const composioProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
const composioClient = getComposioClient();
- const pluginModel = new PluginModel(opts.ctx.serverDB, opts.ctx.userId);
- const connectorModel = new ConnectorModel(opts.ctx.serverDB, opts.ctx.userId);
- return opts.next({ ctx: { ...opts.ctx, composioClient, connectorModel, pluginModel } });
+ // Workspace-scoped so a manual tool execution resolves the workspace-dimension
+ // Composio connection (workspace_id = wsId) rather than only the personal one.
+ // Personal mode (wsId undefined) falls back to `workspace_id IS NULL`.
+ const wsId = ctx.workspaceId ?? undefined;
+ const pluginModel = new PluginModel(ctx.serverDB, ctx.userId, wsId);
+ const connectorModel = new ConnectorModel(ctx.serverDB, ctx.userId, wsId);
+ return opts.next({ ctx: { ...ctx, composioClient, connectorModel, pluginModel } });
});
export const composioToolsRouter = router({
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 16c7c5072f7..659df0f9934 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -623,6 +623,7 @@
"settingAgent.agentTools.removeOwnedConfirm": "Delete this agent-exclusive connector? Its credentials will be removed.",
"settingAgent.agentTools.tabAgent": "Agent Tools",
"settingAgent.agentTools.tabUser": "User Tools",
+ "settingAgent.agentTools.tabWorkspace": "Workspace Tools",
"settingAgent.avatar.sizeExceeded": "Image size exceeds 1MB limit, please choose a smaller image",
"settingAgent.avatar.title": "Avatar",
"settingAgent.backgroundColor.title": "Background Color",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 39f5ba67601..46988b21918 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -623,6 +623,7 @@
"settingAgent.agentTools.removeOwnedConfirm": "删除这个 Agent 专属连接器?其凭据将被移除。",
"settingAgent.agentTools.tabAgent": "Agent 工具",
"settingAgent.agentTools.tabUser": "用户工具",
+ "settingAgent.agentTools.tabWorkspace": "Workspace 工具",
"settingAgent.avatar.sizeExceeded": "图片大小超过 1MB 限制,请选择更小的图片",
"settingAgent.avatar.title": "助理头像",
"settingAgent.backgroundColor.title": "头像背景色",
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index c579eaec692..771f529f1d5 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -723,6 +723,7 @@ export default {
'Delete this agent-exclusive connector? Its credentials will be removed.',
'settingAgent.agentTools.tabAgent': 'Agent Tools',
'settingAgent.agentTools.tabUser': 'User Tools',
+ 'settingAgent.agentTools.tabWorkspace': 'Workspace Tools',
'settingAgent.runtimeConfig.title': 'Model & Tools',
'settingAgent.submit': 'Update Agent',
'settingAgent.tag.desc': 'Agent tags will be displayed in the Agent Community',
diff --git a/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsx b/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsx
index 9c096057e92..24979206622 100644
--- a/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsx
+++ b/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsx
@@ -8,6 +8,8 @@ import { CopyIcon, PlugZapIcon, PlusIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { useIsWorkspaceOwner } from '@/business/client/hooks/useIsWorkspaceOwner';
import { createAgentSkillStoreModal } from '@/features/AgentSkillStore';
import PluginTag from '@/features/ProfileEditor/PluginTag';
import { usePermission } from '@/hooks/usePermission';
@@ -16,6 +18,7 @@ import { agentSelectors } from '@/store/agent/selectors';
import { useToolStore } from '@/store/tool';
import { connectorSelectors } from '@/store/tool/slices/connector';
import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';
+import { useUserStore } from '@/store/user';
/**
* The "Agent Tools" section (top of the tools area): the connectors owned by
@@ -28,6 +31,14 @@ const AgentToolsSection = memo<{ agentId: string; onStartCopy: () => void }>(
const { t } = useTranslation('setting');
const { allowed: canEdit } = usePermission('edit_own_content');
+ // Deleting an agent connector row is creator-or-owner only in a workspace
+ // (mirrors the server `assertWorkspaceRowManageable` gate). Used to hide the
+ // remove (×) on shared connectors the current member can't delete, so B
+ // never clicks into a FORBIDDEN error on A's connector.
+ const activeWorkspaceId = useActiveWorkspaceId();
+ const isWorkspaceOwner = useIsWorkspaceOwner();
+ const currentUserId = useUserStore((s) => s.user?.id);
+
const agentConnectors = useToolStore(connectorSelectors.agentConnectors(agentId), isEqual);
const detachConnectorFromAgent = useToolStore((s) => s.detachConnectorFromAgent);
const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
@@ -95,17 +106,28 @@ const AgentToolsSection = memo<{ agentId: string; onStartCopy: () => void }>(
</Text>
)}
- {agentConnectors.map((connector) => (
- <PluginTag
- agentId={agentId}
- disabled={!canEdit}
- key={connector.id}
- pluginId={connector.identifier}
- onRemove={() => {
- handleRemove(connector);
- }}
- />
- ))}
+ {agentConnectors.map((connector) => {
+ // Outside a workspace (personal), or when the row has no known
+ // creator, fall back to the existing edit-permission gate. In a
+ // workspace, only the creator or a workspace owner may delete.
+ const canManageRow =
+ !activeWorkspaceId ||
+ !connector.userId ||
+ connector.userId === currentUserId ||
+ isWorkspaceOwner;
+ return (
+ <PluginTag
+ agentId={agentId}
+ disabled={!canEdit}
+ key={connector.id}
+ pluginId={connector.identifier}
+ removable={canManageRow}
+ onRemove={() => {
+ handleRemove(connector);
+ }}
+ />
+ );
+ })}
</Flexbox>
</Flexbox>
);
diff --git a/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsx b/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsx
index 76e476a7849..5615843695f 100644
--- a/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsx
+++ b/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsx
@@ -7,6 +7,7 @@ import isEqual from 'fast-deep-equal';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import SharedAgentTool, { type AgentToolProps } from '@/features/ProfileEditor/AgentTool';
import PluginTag from '@/features/ProfileEditor/PluginTag';
import { useAgentStore } from '@/store/agent';
@@ -44,6 +45,14 @@ const UserToolsSection = memo<Props>(
const userConnectors = useToolStore(connectorSelectors.connectorList, isEqual);
const config = useAgentStore(agentSelectors.getAgentConfigById(agentId), isEqual);
const userToolCount = getActivePluginIds(config?.plugins).length;
+ // In a workspace, this section's base tools are the WORKSPACE dimension
+ // (`connector.list` is workspace-scoped), not the caller's personal tools —
+ // label it so the user knows the tools are shared workspace-scoped, not
+ // their private ones. Personal mode keeps the "User Tools" label.
+ const activeWorkspaceId = useActiveWorkspaceId();
+ const baseToolsLabel = activeWorkspaceId
+ ? t('settingAgent.agentTools.tabWorkspace')
+ : t('settingAgent.agentTools.tabUser');
// Copyable = the user's own base connectors (not agent-owned, not mounted).
const copyable = userConnectors.filter((c) => !c.agentId && !c.metadata?.mountedByAgentId);
@@ -93,7 +102,7 @@ const UserToolsSection = memo<Props>(
return (
<Flexbox gap={8}>
<Text style={{ fontSize: 12, fontWeight: 500 }} type={'secondary'}>
- {t('settingAgent.agentTools.tabUser')} · {userToolCount}
+ {baseToolsLabel} · {userToolCount}
</Text>
<SharedAgentTool {...toolProps} agentId={agentId} />
</Flexbox>
diff --git a/src/features/ProfileEditor/PluginTag.tsx b/src/features/ProfileEditor/PluginTag.tsx
index 18776d7d059..a668fdc0f9f 100644
--- a/src/features/ProfileEditor/PluginTag.tsx
+++ b/src/features/ProfileEditor/PluginTag.tsx
@@ -90,6 +90,13 @@ export interface PluginTagProps {
/** Fires when the checkbox/tag is toggled in `selectable` mode. */
onSelect?: () => void;
pluginId: string | { enabled: boolean; identifier: string; settings: Record<string, any> };
+ /**
+ * Whether the remove (×) button is shown. Default true. Set false to keep the
+ * tag interactive (clickable to open detail) while hiding removal — e.g. a
+ * shared workspace connector the current member isn't allowed to delete
+ * (only its creator or a workspace owner can).
+ */
+ removable?: boolean;
/**
* Render as a selectable chip: a leading checkbox, no remove (×) button, and
* the whole tag toggles selection. Used by the multi-select "copy" flow.
@@ -115,6 +122,7 @@ const PluginTag = memo<PluginTagProps>(
pluginId,
onRemove,
onSelect,
+ removable = true,
selectable = false,
selected = false,
disabled,
@@ -346,7 +354,7 @@ const PluginTag = memo<PluginTagProps>(
return (
<Tag
className={styles.tag}
- closable={!disabled && !selectable}
+ closable={removable && !disabled && !selectable}
closeIcon={<X size={12} />}
color={showErrorState ? 'error' : undefined}
style={selectable ? { cursor: 'pointer' } : undefined}