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.

✨ feat(connector): distinguish workspace and private connectors (#22941)

Rdmclin2d86a85bcea15
diff --git a/apps/server/src/modules/AgentRuntime/adapters/composioConnectedIds.test.ts b/apps/server/src/modules/AgentRuntime/adapters/composioConnectedIds.test.ts
index 153a7b001fd..85d5fa6753a 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/composioConnectedIds.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/composioConnectedIds.test.ts
@@ -19,8 +19,12 @@ describe('loadConnectedComposioIds', () => {
beforeEach(() => {
vi.clearAllMocks();
- pluginModelMock = { query: vi.fn().mockResolvedValue([]) };
- connectorModelMock = { resolveAll: vi.fn().mockResolvedValue([]) };
+ pluginModelMock = { queryComposioMirrors: vi.fn().mockResolvedValue([]) };
+ connectorModelMock = {
+ // Pass-through by default: every projection row is a legacy connection.
+ pickLegacyComposioMirrors: vi.fn(async (mirrors: unknown[]) => mirrors),
+ resolveAll: vi.fn().mockResolvedValue([]),
+ };
vi.mocked(PluginModel).mockImplementation(function () {
return pluginModelMock;
});
@@ -30,7 +34,7 @@ describe('loadConnectedComposioIds', () => {
});
it('includes an agent-scoped connector that is absent from the plugin table', async () => {
- pluginModelMock.query.mockResolvedValueOnce([]); // nothing projected to plugins
+ pluginModelMock.queryComposioMirrors.mockResolvedValueOnce([]); // nothing projected to plugins
connectorModelMock.resolveAll.mockResolvedValueOnce([
{
identifier: 'gmail',
@@ -39,22 +43,68 @@ describe('loadConnectedComposioIds', () => {
},
]);
- const ids = await loadConnectedComposioIds({} as any, 'user_test', 'ws-1', 'agent-1');
+ const ids = await loadConnectedComposioIds({} as any, 'user_test', 'ws-1', {
+ agentId: 'agent-1',
+ topicId: 'tpc-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');
+ expect(connectorModelMock.resolveAll).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ topicId: 'tpc-1',
+ });
});
- it('still counts a base connection projected into the plugin table', async () => {
- pluginModelMock.query.mockResolvedValueOnce([
- { customParams: { composio: { status: 'ACTIVE' } }, identifier: 'gmail' },
- ]);
+ const projection = (status: string, userId = 'user_test') => ({
+ customParams: { composio: { connectedAccountId: 'ca_legacy', status } },
+ identifier: 'gmail',
+ userId,
+ });
+
+ it('still counts a legacy base connection projected into the plugin table', async () => {
+ pluginModelMock.queryComposioMirrors.mockResolvedValueOnce([projection('ACTIVE')]);
- const ids = await loadConnectedComposioIds({} as any, 'user_test', undefined, undefined);
+ const ids = await loadConnectedComposioIds({} as any, 'user_test', undefined, {});
expect(ids.has('gmail')).toBe(true);
+ expect(connectorModelMock.pickLegacyComposioMirrors).toHaveBeenCalledWith([
+ expect.objectContaining({
+ connectedAccountId: 'ca_legacy',
+ identifier: 'gmail',
+ ownerUserId: 'user_test',
+ }),
+ ]);
+ });
+
+ // Regression: a teammate made the workspace's only Gmail connection private.
+ // Its projection row stays ACTIVE and workspace-wide, but a workspace agent
+ // does not load the private connector, so `ComposioService` serves it no
+ // Gmail tool. Counting the row told the model Gmail was authorized and hid
+ // it from the services it can connect.
+ it('does not count a projection row that mirrors a connector the run does not load', async () => {
+ pluginModelMock.queryComposioMirrors.mockResolvedValueOnce([projection('ACTIVE', 'mate')]);
+ connectorModelMock.pickLegacyComposioMirrors.mockResolvedValueOnce([]);
+ connectorModelMock.resolveAll.mockResolvedValueOnce([]); // private row is not resolved
+
+ const ids = await loadConnectedComposioIds({} as any, 'user_test', 'ws-1', {
+ agentId: 'workspace-agent',
+ topicId: 'tpc-1',
+ });
+
+ expect(ids.has('gmail')).toBe(false);
+ expect(connectorModelMock.pickLegacyComposioMirrors).toHaveBeenCalledWith([
+ expect.objectContaining({ identifier: 'gmail', ownerUserId: 'mate' }),
+ ]);
+ });
+
+ it('does not count an inactive legacy projection row', async () => {
+ pluginModelMock.queryComposioMirrors.mockResolvedValueOnce([projection('EXPIRED')]);
+
+ const ids = await loadConnectedComposioIds({} as any, 'user_test', undefined, {});
+
+ expect(ids.has('gmail')).toBe(false);
});
it('excludes a disabled connector and a non-Composio identifier', async () => {
@@ -67,7 +117,10 @@ describe('loadConnectedComposioIds', () => {
},
]);
- const ids = await loadConnectedComposioIds({} as any, 'user_test', 'ws-1', 'agent-1');
+ const ids = await loadConnectedComposioIds({} as any, 'user_test', 'ws-1', {
+ agentId: 'agent-1',
+ topicId: 'tpc-1',
+ });
expect(ids.has('gmail')).toBe(false); // disabled connector row
expect(ids.has('my-custom-mcp')).toBe(false); // not a Composio app type
@@ -78,18 +131,22 @@ describe('loadConnectedComposioIds', () => {
{ identifier: 'gmail', isEnabled: true, metadata: { composio: { status: 'PENDING' } } },
]);
- const ids = await loadConnectedComposioIds({} as any, 'user_test', 'ws-1', 'agent-1');
+ const ids = await loadConnectedComposioIds({} as any, 'user_test', 'ws-1', {
+ agentId: 'agent-1',
+ topicId: 'tpc-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' },
- ]);
+ pluginModelMock.queryComposioMirrors.mockResolvedValueOnce([projection('ACTIVE')]);
connectorModelMock.resolveAll.mockRejectedValueOnce(new Error('db down'));
- const ids = await loadConnectedComposioIds({} as any, 'user_test', 'ws-1', 'agent-1');
+ const ids = await loadConnectedComposioIds({} as any, 'user_test', 'ws-1', {
+ agentId: 'agent-1',
+ topicId: 'tpc-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
index 30a24cf0601..bd2b742726e 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/composioConnectedIds.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/composioConnectedIds.ts
@@ -1,9 +1,12 @@
-import { COMPOSIO_APP_TYPES } from '@lobechat/const';
import type { LobeChatDatabase } from '@lobechat/database';
import debug from 'debug';
-import { ConnectorModel } from '@/database/models/connector';
+import { ConnectorModel, type ConnectorRunTarget } from '@/database/models/connector';
import { PluginModel } from '@/database/models/plugin';
+import {
+ selectLegacyComposioMirrors,
+ VALID_COMPOSIO_IDENTIFIERS,
+} from '@/server/services/composio/legacyMirrors';
const log = debug('lobe-server:composio-connected-ids');
@@ -11,11 +14,20 @@ 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`.
+ * Composio connections created before the connector dual-write. Only the
+ * rows `ComposioService` would run (`selectLegacyComposioMirrors`) count: a
+ * projection row that mirrors a connector — e.g. a teammate's private one a
+ * workspace agent does not load — is that connector's, and is counted only
+ * when the run resolves the connector below.
+ * - `user_connectors` (`resolveAll`, agent + workspace + visibility aware):
+ * base and AGENT-scoped connections. Agent-scoped ones 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`.
+ *
+ * Counting a projection row the run cannot use would tell the model the
+ * service is authorized ("use its tools directly") and drop it from the
+ * services it can connect, while the run has no tool for it.
*
* Without the connector union, an agent-scoped Composio connection reads as
* "not connected", and the model re-runs `connectComposioService` (the OAuth
@@ -25,31 +37,28 @@ export async function loadConnectedComposioIds(
serverDB: LobeChatDatabase,
userId: string,
workspaceId: string | undefined,
- agentId: string | undefined,
+ target: ConnectorRunTarget,
): Promise<Set<string>> {
- const validComposioIds = new Set(COMPOSIO_APP_TYPES.map((tool) => tool.identifier));
const connected = new Set<string>();
+ const connectorModel = new ConnectorModel(serverDB, userId, workspaceId);
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);
- }
+ const legacyMirrors = await selectLegacyComposioMirrors(
+ await pluginModel.queryComposioMirrors(),
+ connectorModel,
+ );
+ for (const { plugin } of legacyMirrors) {
+ if (plugin.customParams?.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);
+ const connectors = await connectorModel.resolveAll(target);
for (const connector of connectors) {
if (
connector.isEnabled &&
- validComposioIds.has(connector.identifier) &&
+ VALID_COMPOSIO_IDENTIFIERS.has(connector.identifier) &&
connector.metadata?.composio?.status === 'ACTIVE'
) {
connected.add(connector.identifier);
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts
index 4f56ae124c8..05681b34496 100644
--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts
+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts
@@ -339,7 +339,10 @@ export const createServerContextFactProviders = ({
// discovered for this run (their manifests are only fetched for connected
// providers, so presence in the tool set is the connection).
listConnectedConnectorIds: async (agentId) => {
- const connected = await loadConnectedComposioIds(db, userId, ctx.workspaceId, agentId);
+ const connected = await loadConnectedComposioIds(db, userId, ctx.workspaceId, {
+ agentId,
+ topicId: ctx.topicId,
+ });
const sourceMap = selectToolSourceMap(state);
for (const [identifier, source] of Object.entries(sourceMap)) {
if (source === 'lobehubSkill') connected.add(identifier);
diff --git a/apps/server/src/routers/lambda/__tests__/agent.privateConnectors.test.ts b/apps/server/src/routers/lambda/__tests__/agent.privateConnectors.test.ts
new file mode 100644
index 00000000000..fa6846dfb02
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/agent.privateConnectors.test.ts
@@ -0,0 +1,107 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentModel } from '@/database/models/agent';
+import { ConnectorModel } from '@/database/models/connector';
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
+import { AgentService } from '@/server/services/agent';
+
+import { agentRouter } from '../agent';
+
+vi.mock('@/server/services/resourceEvents', () => ({ publishResourceEvent: vi.fn() }));
+vi.mock('../_helpers/workspaceAgentGuard', () => ({
+ getWorkspaceAgentParentGroupIds: vi.fn().mockResolvedValue([]),
+}));
+vi.mock('@/database/models/user', () => ({ UserModel: { findById: vi.fn() } }));
+vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));
+vi.mock('@/database/models/session', () => ({ SessionModel: vi.fn() }));
+vi.mock('@/database/models/task', () => ({ TaskModel: vi.fn() }));
+vi.mock('@/database/models/chatGroup', () => ({ ChatGroupModel: vi.fn() }));
+vi.mock('@/database/models/connector', () => ({ ConnectorModel: vi.fn() }));
+vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));
+vi.mock('@/database/models/knowledgeBase', () => ({ KnowledgeBaseModel: vi.fn() }));
+vi.mock('@/database/models/resourcePermission', () => ({ ResourcePermissionModel: vi.fn() }));
+vi.mock('@/database/models/workspaceUserSettings', () => ({
+ WorkspaceUserSettingsModel: vi.fn(),
+}));
+vi.mock('@/server/services/agent', () => ({ AgentService: vi.fn() }));
+vi.mock('@/server/services/workspacePermission', () => ({
+ getWorkspaceScopedPermissionMatches: vi.fn(),
+ hasWorkspaceScopedPermission: vi.fn(),
+ isWorkspacePrimaryOwner: vi.fn(),
+}));
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => ({})) }));
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanEditResource: vi.fn(),
+ assertCanPerformResourceAction: vi.fn(),
+ buildResourcePermissionState: vi.fn((params: unknown) => params),
+ canPerformResourceAction: vi.fn(),
+ getResourceMeta: vi.fn(),
+ isCollaborativeBuiltinAgent: vi.fn(() => false),
+}));
+
+const userId = 'creator-1';
+
+/**
+ * A private connector serves only its creator's private agents, and a shared
+ * agent's runs leave it out: publishing an agent that still uses one would
+ * drop its tool, or answer it with a same-identifier shared connector running
+ * another account. Both publish paths refuse it.
+ */
+describe('publishing an agent that uses private connectors', () => {
+ let agentModel: Record<string, ReturnType<typeof vi.fn>>;
+ let countPrivateAgentBindings: ReturnType<typeof vi.fn>;
+ const ctx = () => ({ agentModel, userId, workspaceId: 'ws-1' }) as never;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ agentModel = {
+ getAgentVisibilityMeta: vi
+ .fn()
+ .mockResolvedValue({ pinned: false, slug: null, userId, visibility: 'private' }),
+ publishToWorkspace: vi.fn().mockResolvedValue({ id: 'agent-1', visibility: 'public' }),
+ setVisibility: vi.fn().mockResolvedValue({ id: 'agent-1' }),
+ update: vi.fn(),
+ };
+ vi.mocked(AgentModel).mockImplementation(function () {
+ return agentModel as never;
+ });
+ countPrivateAgentBindings = vi.fn().mockResolvedValue(1);
+ vi.mocked(ConnectorModel).mockImplementation(function () {
+ return { countPrivateAgentBindings } as never;
+ });
+ vi.mocked(ResourcePermissionModel).mockImplementation(function () {
+ return {
+ getAccessLevel: vi.fn().mockResolvedValue(undefined),
+ removeAll: vi.fn(),
+ setAccessLevel: vi.fn(),
+ } as never;
+ });
+ vi.mocked(AgentService).mockImplementation(function () {
+ return {} as never;
+ });
+ });
+
+ it('refuses publishAgentToWorkspace', async () => {
+ await expect(
+ agentRouter.createCaller(ctx()).publishAgentToWorkspace({ id: 'agent-1' }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(countPrivateAgentBindings).toHaveBeenCalledWith('agent-1');
+ expect(agentModel.publishToWorkspace).not.toHaveBeenCalled();
+ });
+
+ it('refuses setAgentVisibility to public', async () => {
+ await expect(
+ agentRouter.createCaller(ctx()).setAgentVisibility({ id: 'agent-1', visibility: 'public' }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(agentModel.setVisibility).not.toHaveBeenCalled();
+ });
+
+ it('publishes once the agent uses no private connector', async () => {
+ countPrivateAgentBindings.mockResolvedValue(0);
+
+ await agentRouter.createCaller(ctx()).publishAgentToWorkspace({ id: 'agent-1' });
+
+ expect(agentModel.publishToWorkspace).toHaveBeenCalledWith('agent-1');
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/agent.teamPin.test.ts b/apps/server/src/routers/lambda/__tests__/agent.teamPin.test.ts
index 36b20d6f15a..180a20a4a4b 100644
--- a/apps/server/src/routers/lambda/__tests__/agent.teamPin.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agent.teamPin.test.ts
@@ -18,6 +18,12 @@ vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));
vi.mock('@/database/models/session', () => ({ SessionModel: vi.fn() }));
vi.mock('@/database/models/task', () => ({ TaskModel: vi.fn() }));
vi.mock('@/database/models/chatGroup', () => ({ ChatGroupModel: vi.fn() }));
+// The publish guard counts the agent's private connectors (none here)
+vi.mock('@/database/models/connector', () => ({
+ ConnectorModel: vi.fn(function () {
+ return { countPrivateAgentBindings: vi.fn().mockResolvedValue(0) };
+ }),
+}));
vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));
vi.mock('@/database/models/knowledgeBase', () => ({ KnowledgeBaseModel: vi.fn() }));
vi.mock('@/database/models/resourcePermission', () => ({ ResourcePermissionModel: vi.fn() }));
diff --git a/apps/server/src/routers/lambda/__tests__/composio.workspaceScope.test.ts b/apps/server/src/routers/lambda/__tests__/composio.workspaceScope.test.ts
index 3f33153e3bf..863ae6edf85 100644
--- a/apps/server/src/routers/lambda/__tests__/composio.workspaceScope.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/composio.workspaceScope.test.ts
@@ -15,6 +15,7 @@ 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() }));
+const composioClientMocks = vi.hoisted(() => ({ deleteAccount: vi.fn() }));
const workspaceMocks = vi.hoisted(() => ({
getConnectorMemberManage: vi.fn(async () => 'all_members' as const),
}));
@@ -27,7 +28,10 @@ vi.mock('@/database/models/workspace', () => ({
vi.mock('@/config/composio', () => ({ getServerComposioAuthConfigId: () => 'auth-cfg-1' }));
vi.mock('@/libs/composio', () => ({
getComposioClient: () => ({
- connectedAccounts: { link: async () => ({ id: 'acc-1', redirectUrl: 'http://redirect' }) },
+ connectedAccounts: {
+ delete: composioClientMocks.deleteAccount,
+ link: async () => ({ id: 'acc-1', redirectUrl: 'http://redirect' }),
+ },
tools: { getRawComposioTools: async () => ({ items: [] }) },
}),
}));
@@ -62,11 +66,28 @@ describe('composioRouter — workspace scoping (workspace-agent connector bug)',
connectorModelMock = {
create: vi.fn().mockResolvedValue({ id: 'conn-new' }),
createUnlessIdentifierHeld: vi.fn().mockResolvedValue({ created: { id: 'conn-new' } }),
+ // The row a write updates — the caller's own row in either visibility.
+ findManageableByIdentifier: vi.fn().mockResolvedValue(null),
+ // The shared row only (the lookup a create of a new row uses).
findScopedByIdentifier: vi.fn().mockResolvedValue(null),
+ delete: vi.fn().mockResolvedValue(undefined),
+ // By default the account a write names is held by the row the write
+ // resolves (the implementation is read without recording a lookup call).
+ queryComposioAccountHolders: vi.fn(async () => {
+ const row = await connectorModelMock.findManageableByIdentifier.getMockImplementation()?.();
+ return row ? [row] : [];
+ }),
update: vi.fn().mockResolvedValue(undefined),
};
connectorToolModelMock = { deleteToolsNotIn: vi.fn(), upsertMany: vi.fn() };
- pluginModelMock = { create: vi.fn(), findById: vi.fn(), update: vi.fn() };
+ pluginModelMock = {
+ create: vi.fn(),
+ deleteComposioMirrors: vi.fn(),
+ deleteComposioProjectionKeepingPrivate: vi.fn(),
+ findById: vi.fn(),
+ queryComposioMirrors: vi.fn().mockResolvedValue([]),
+ update: vi.fn(),
+ };
agentModelMock = { existsOwnedById: vi.fn().mockResolvedValue(true) };
vi.mocked(ConnectorModel).mockImplementation(function () {
return connectorModelMock;
@@ -133,6 +154,15 @@ describe('composioRouter — workspace scoping (workspace-agent connector bug)',
});
it('updateComposioPlugin also scopes the model + agent check to the workspace', async () => {
+ // createConnection already wrote the agent's row with the pending account.
+ connectorModelMock.findManageableByIdentifier.mockResolvedValue({
+ agentId: 'agent-1',
+ id: 'conn-agent',
+ metadata: { composio: { connectedAccountId: 'acc-1' } },
+ userId: 'user_test',
+ visibility: 'public',
+ });
+
await callerFor('ws-1').updateComposioPlugin({
agentId: 'agent-1',
appSlug: 'gmail',
@@ -159,15 +189,403 @@ describe('composioRouter — workspace scoping (workspace-agent connector bug)',
it('lets a member reconnect another member’s workspace connection by default', async () => {
// Shared connectors are co-maintained unless an admin restricted them.
- connectorModelMock.findScopedByIdentifier.mockResolvedValue({
+ const sharedRow = {
+ agentId: null,
id: 'conn-other',
identifier: 'gmail',
userId: 'another-user',
+ visibility: 'public' as const,
+ };
+ connectorModelMock.findManageableByIdentifier.mockResolvedValue(sharedRow);
+ connectorModelMock.findScopedByIdentifier.mockResolvedValue(sharedRow);
+
+ await expect(
+ memberCaller().createConnection({ appSlug: 'gmail', identifier: 'gmail', label: 'Gmail' }),
+ ).resolves.toBeDefined();
+ expect(connectorModelMock.update).toHaveBeenCalledWith('conn-other', expect.anything());
+ });
+
+ it('lets a member reconnect their own private connection when admins restricted management', async () => {
+ // Regression: the gate looked up the shared row while the write updates the
+ // caller's own private row, so `admins_only` blocked the owner from
+ // reconnecting a connector that is theirs alone. The gate must judge the
+ // row the write touches.
+ workspaceMocks.getConnectorMemberManage.mockResolvedValue('admins_only');
+ connectorModelMock.findManageableByIdentifier.mockResolvedValue({
+ agentId: null,
+ id: 'conn-private',
+ identifier: 'gmail',
+ userId: 'user_test',
+ visibility: 'private',
});
await expect(
memberCaller().createConnection({ appSlug: 'gmail', identifier: 'gmail', label: 'Gmail' }),
).resolves.toBeDefined();
+
+ expect(connectorModelMock.create).not.toHaveBeenCalled();
+ expect(connectorModelMock.update).toHaveBeenCalledWith('conn-private', expect.anything());
+ });
+
+ it('still blocks a member from the shared connection when they also have no private one', async () => {
+ workspaceMocks.getConnectorMemberManage.mockResolvedValue('admins_only');
+ connectorModelMock.findManageableByIdentifier.mockResolvedValue({
+ agentId: null,
+ id: 'conn-shared',
+ identifier: 'gmail',
+ userId: 'user_test',
+ visibility: 'public',
+ });
+
+ await expect(
+ memberCaller().createConnection({ appSlug: 'gmail', identifier: 'gmail', label: 'Gmail' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ expect(connectorModelMock.update).not.toHaveBeenCalled();
+ });
+
+ describe('binds the account a write names to the connector it runs on', () => {
+ // The plugin projection is workspace-wide, so every member reads every
+ // account id in it, privatized connections included, and the Composio
+ // client deletes an account by its id alone. A write is judged on the rows
+ // that actually hold the account, not on the identifier it names.
+ const sharedRow = {
+ agentId: null,
+ id: 'conn-shared',
+ identifier: 'gmail',
+ metadata: { composio: { connectedAccountId: 'acc-shared' } },
+ userId: 'another-user',
+ visibility: 'public' as const,
+ };
+ const matePrivateRow = {
+ agentId: null,
+ id: 'conn-mate',
+ identifier: 'gmail',
+ userId: 'another-user',
+ visibility: 'private' as const,
+ };
+ const refresh = (connectedAccountId: string, identifier = 'gmail') =>
+ memberCaller().updateComposioPlugin({
+ appSlug: identifier,
+ authConfigId: 'auth-cfg-1',
+ connectedAccountId,
+ identifier,
+ label: identifier,
+ status: 'ACTIVE',
+ tools: [],
+ });
+
+ const expectNothingWritten = () => {
+ expect(composioClientMocks.deleteAccount).not.toHaveBeenCalled();
+ expect(connectorModelMock.delete).not.toHaveBeenCalled();
+ expect(connectorModelMock.update).not.toHaveBeenCalled();
+ expect(connectorModelMock.create).not.toHaveBeenCalled();
+ expect(pluginModelMock.deleteComposioProjectionKeepingPrivate).not.toHaveBeenCalled();
+ };
+
+ it('refuses an account held by a teammate’s private connector', async () => {
+ // Removing it through the shared row the member can see would delete the
+ // teammate's remote account; refreshing it would copy it onto that row.
+ connectorModelMock.findManageableByIdentifier.mockResolvedValue(sharedRow);
+ connectorModelMock.queryComposioAccountHolders.mockResolvedValue([matePrivateRow]);
+
+ await expect(
+ memberCaller().deleteConnection({ connectedAccountId: 'acc-private', identifier: 'gmail' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ await expect(refresh('acc-private')).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ expect(connectorModelMock.queryComposioAccountHolders).toHaveBeenCalledWith('acc-private');
+ expectNothingWritten();
+ });
+
+ it('refuses it under any identifier the request names', async () => {
+ // ROOT CAUSE:
+ //
+ // The private-account check also matched on the request's identifier, so
+ // naming another app missed the teammate's `gmail` row; the policy was
+ // judged on an unrelated (or no) row and the account was deleted.
+ connectorModelMock.findManageableByIdentifier.mockResolvedValue(null);
+ connectorModelMock.queryComposioAccountHolders.mockResolvedValue([matePrivateRow]);
+
+ await expect(
+ memberCaller().deleteConnection({
+ connectedAccountId: 'acc-private',
+ identifier: 'notion',
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ await expect(refresh('acc-private', 'notion')).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ expectNothingWritten();
+ });
+
+ it('refuses it when a row of the caller’s names the account too', async () => {
+ // A connector's metadata is client-written: a member can add a private
+ // row naming the teammate's account and remove "their own" connection.
+ const forged = {
+ ...matePrivateRow,
+ id: 'conn-forged',
+ metadata: { composio: { connectedAccountId: 'acc-private' } },
+ userId: 'user_test',
+ };
+ connectorModelMock.findManageableByIdentifier.mockResolvedValue(forged);
+ connectorModelMock.queryComposioAccountHolders.mockResolvedValue([forged, matePrivateRow]);
+
+ await expect(
+ memberCaller().deleteConnection({ connectedAccountId: 'acc-private', identifier: 'gmail' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ expectNothingWritten();
+ });
+
+ it('refuses an account a connector the member may not maintain runs', async () => {
+ // A private row is exempt from the shared-connector policy; naming the
+ // shared account in one must not reach a shared row that admins locked.
+ workspaceMocks.getConnectorMemberManage.mockResolvedValue('admins_only');
+ const forged = {
+ ...matePrivateRow,
+ id: 'conn-forged',
+ metadata: { composio: { connectedAccountId: 'acc-shared' } },
+ userId: 'user_test',
+ };
+ connectorModelMock.findManageableByIdentifier.mockResolvedValue(forged);
+ connectorModelMock.queryComposioAccountHolders.mockResolvedValue([forged, sharedRow]);
+
+ await expect(
+ memberCaller().deleteConnection({ connectedAccountId: 'acc-shared', identifier: 'gmail' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ expectNothingWritten();
+ });
+
+ it('refuses an account another connector runs', async () => {
+ connectorModelMock.findManageableByIdentifier.mockResolvedValue(sharedRow);
+ connectorModelMock.queryComposioAccountHolders.mockResolvedValue([
+ { ...sharedRow, id: 'conn-github', identifier: 'github' },
+ ]);
+
+ await expect(
+ memberCaller().deleteConnection({ connectedAccountId: 'acc-github', identifier: 'gmail' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ expectNothingWritten();
+ });
+
+ it('acts on a legacy connection only through the app’s own projection', async () => {
+ // No connector row runs a legacy account: it exists as a plugin
+ // projection row of the app, under the shared connector policy.
+ connectorModelMock.findManageableByIdentifier.mockResolvedValue(sharedRow);
+ connectorModelMock.queryComposioAccountHolders.mockResolvedValue([]);
+ pluginModelMock.queryComposioMirrors.mockResolvedValue([
+ { customParams: { composio: { connectedAccountId: 'acc-legacy' } }, identifier: 'gmail' },
+ ]);
+
+ await expect(
+ memberCaller().deleteConnection({ connectedAccountId: 'acc-unknown', identifier: 'gmail' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expectNothingWritten();
+
+ await memberCaller().deleteConnection({
+ connectedAccountId: 'acc-legacy',
+ identifier: 'gmail',
+ });
+
+ expect(pluginModelMock.queryComposioMirrors).toHaveBeenCalledWith(['gmail']);
+ expect(composioClientMocks.deleteAccount).toHaveBeenCalledWith('acc-legacy');
+ expect(connectorModelMock.delete).toHaveBeenCalledWith('conn-shared');
+ });
+
+ it('never treats an agent connection as a legacy one', async () => {
+ // Agent connections have no plugin projection, so a base legacy account
+ // must not be removed through an agent's row.
+ connectorModelMock.queryComposioAccountHolders.mockResolvedValue([]);
+ pluginModelMock.queryComposioMirrors.mockResolvedValue([
+ { customParams: { composio: { connectedAccountId: 'acc-legacy' } }, identifier: 'gmail' },
+ ]);
+
+ await expect(
+ memberCaller().deleteConnection({
+ agentId: 'agent-1',
+ connectedAccountId: 'acc-legacy',
+ identifier: 'gmail',
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+
+ expect(pluginModelMock.queryComposioMirrors).not.toHaveBeenCalled();
+ expectNothingWritten();
+ });
+ });
+
+ it('removes the shared account’s row, not the caller’s private one', async () => {
+ // The lookup by account resolves the shared row; the member policy is then
+ // judged on that row, and that row is the one deleted.
+ const sharedRow = {
+ agentId: null,
+ id: 'conn-shared',
+ metadata: { composio: { connectedAccountId: 'acc-shared' } },
+ userId: 'another-user',
+ visibility: 'public' as const,
+ };
+ connectorModelMock.findManageableByIdentifier.mockResolvedValue(sharedRow);
+
+ await memberCaller().deleteConnection({
+ connectedAccountId: 'acc-shared',
+ identifier: 'gmail',
+ });
+
+ expect(connectorModelMock.findManageableByIdentifier).toHaveBeenCalledWith(
+ 'gmail',
+ undefined,
+ 'acc-shared',
+ );
+ expect(connectorModelMock.queryComposioAccountHolders).toHaveBeenCalledWith('acc-shared');
+ expect(composioClientMocks.deleteAccount).toHaveBeenCalledWith('acc-shared');
+ expect(connectorModelMock.delete).toHaveBeenCalledWith('conn-shared');
+ // The shared connection is the workspace's projection of the app.
+ expect(pluginModelMock.deleteComposioProjectionKeepingPrivate).toHaveBeenCalledWith('gmail');
+ expect(pluginModelMock.deleteComposioMirrors).not.toHaveBeenCalled();
+ });
+
+ describe('a private connection’s plugin projection', () => {
+ // Every member's projection row of an app is in a workspace's scope. A
+ // private connection is one member's, so writing or removing the projection
+ // by identifier would replace or drop a teammate's legacy connection.
+ const privateRow = {
+ agentId: null,
+ id: 'conn-private',
+ metadata: { composio: { connectedAccountId: 'acc-private' } },
+ userId: 'user_test',
+ visibility: 'private' as const,
+ };
+ const refresh = {
+ appSlug: 'gmail',
+ authConfigId: 'auth-cfg-1',
+ connectedAccountId: 'acc-private',
+ identifier: 'gmail',
+ label: 'Gmail',
+ status: 'ACTIVE',
+ tools: [],
+ };
+
+ beforeEach(() => {
+ connectorModelMock.findManageableByIdentifier.mockResolvedValue(privateRow);
+ pluginModelMock.findById.mockResolvedValue({ identifier: 'gmail', manifest: {} });
+ });
+
+ it('refreshes only the caller’s own projection row', async () => {
+ await memberCaller().updateComposioPlugin(refresh);
+
+ expect(pluginModelMock.update).not.toHaveBeenCalled();
+ expect(pluginModelMock.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ customParams: {
+ composio: expect.objectContaining({ connectedAccountId: 'acc-private' }),
+ },
+ identifier: 'gmail',
+ }),
+ );
+ });
+
+ it('still refreshes a shared connection across the workspace', async () => {
+ connectorModelMock.findManageableByIdentifier.mockResolvedValue({
+ ...privateRow,
+ visibility: 'public',
+ });
+
+ await memberCaller().updateComposioPlugin(refresh);
+
+ expect(pluginModelMock.update).toHaveBeenCalledWith('gmail', expect.anything());
+ expect(pluginModelMock.create).not.toHaveBeenCalled();
+ });
+
+ it('removes only the rows mirroring its account', async () => {
+ await memberCaller().deleteConnection({
+ connectedAccountId: 'acc-private',
+ identifier: 'gmail',
+ });
+ await memberCaller().removeComposioPlugin({ identifier: 'gmail' });
+
+ expect(pluginModelMock.deleteComposioProjectionKeepingPrivate).not.toHaveBeenCalled();
+ expect(pluginModelMock.deleteComposioMirrors).toHaveBeenNthCalledWith(
+ 1,
+ 'gmail',
+ 'acc-private',
+ );
+ expect(pluginModelMock.deleteComposioMirrors).toHaveBeenNthCalledWith(
+ 2,
+ 'gmail',
+ 'acc-private',
+ );
+ expect(connectorModelMock.delete).toHaveBeenCalledWith('conn-private');
+ });
+ });
+
+ describe('re-authorizing a connection', () => {
+ // A pending/failed connection is re-authorized in one write: removing its
+ // row first made the reconnect create a new, shared row (or land on a
+ // shared sibling), publishing a private account to the workspace's agents.
+ const privateRow = {
+ agentId: null,
+ id: 'conn-private',
+ metadata: { composio: { connectedAccountId: 'acc-stale' } },
+ userId: 'user_test',
+ visibility: 'private' as const,
+ };
+ const reauthorize = () =>
+ memberCaller().createConnection({
+ appSlug: 'gmail',
+ identifier: 'gmail',
+ label: 'Gmail',
+ replacesConnectedAccountId: 'acc-stale',
+ });
+
+ it('relinks the private row in place, keeping it private beside a shared sibling', async () => {
+ connectorModelMock.findManageableByIdentifier.mockResolvedValue(privateRow);
+
+ await reauthorize();
+
+ // The row is the one holding the replaced account, not the shared sibling.
+ expect(connectorModelMock.findManageableByIdentifier).toHaveBeenCalledWith(
+ 'gmail',
+ undefined,
+ 'acc-stale',
+ );
+ expect(composioClientMocks.deleteAccount).toHaveBeenCalledWith('acc-stale');
+ expect(connectorModelMock.delete).not.toHaveBeenCalled();
+ expect(connectorModelMock.create).not.toHaveBeenCalled();
+ expect(connectorModelMock.update).toHaveBeenCalledWith(
+ 'conn-private',
+ expect.objectContaining({
+ metadata: expect.objectContaining({
+ composio: expect.objectContaining({ connectedAccountId: 'acc-1' }),
+ }),
+ }),
+ );
+ // The update never rewrites the scope.
+ const [, patch] = connectorModelMock.update.mock.calls[0];
+ expect(patch).not.toHaveProperty('visibility');
+ expect(patch).not.toHaveProperty('agentId');
+ // Only the private connection's own projection rows are replaced.
+ expect(pluginModelMock.deleteComposioProjectionKeepingPrivate).not.toHaveBeenCalled();
+ expect(pluginModelMock.deleteComposioMirrors).toHaveBeenCalledWith('gmail', 'acc-stale');
+ });
+
+ it('refuses to replace an account a teammate’s private connector holds', async () => {
+ connectorModelMock.findManageableByIdentifier.mockResolvedValue({
+ ...privateRow,
+ id: 'conn-shared',
+ userId: 'another-user',
+ visibility: 'public',
+ });
+ connectorModelMock.queryComposioAccountHolders.mockResolvedValue([
+ { ...privateRow, id: 'conn-mate', userId: 'another-user' },
+ ]);
+
+ await expect(reauthorize()).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ expect(composioClientMocks.deleteAccount).not.toHaveBeenCalled();
+ expect(connectorModelMock.update).not.toHaveBeenCalled();
+ expect(connectorModelMock.create).not.toHaveBeenCalled();
+ });
});
it('blocks a member from connecting when admins restricted connector management', async () => {
diff --git a/apps/server/src/routers/lambda/__tests__/connector.deviceBinding.test.ts b/apps/server/src/routers/lambda/__tests__/connector.deviceBinding.test.ts
new file mode 100644
index 00000000000..9d004c07a86
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/connector.deviceBinding.test.ts
@@ -0,0 +1,200 @@
+// @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 { connectorRouter } from '../connector';
+
+/**
+ * Which device a workspace connector may be bound to follows who runs it, the
+ * same split as connector loading: a shared connector only a public device of
+ * the workspace, a private one also its creator's own private device.
+ */
+
+const mocks = vi.hoisted(() => ({
+ findWorkspaceDeviceById: vi.fn(),
+}));
+
+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() }));
+vi.mock('@/database/models/device', () => ({
+ DeviceModel: vi.fn(function () {
+ return { findWorkspaceDeviceById: mocks.findWorkspaceDeviceById };
+ }),
+}));
+vi.mock('@/database/models/workspace', () => ({
+ WorkspaceModel: vi.fn(function () {
+ return { getConnectorMemberManage: async () => 'all_members' };
+ }),
+}));
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },
+}));
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');
+ return {
+ requireWorkspaceRoleWhenScoped: () => mod.trpc.middleware((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 ?? {} } }),
+}));
+
+const CONNECTOR_ID = '9f1f6f30-0000-4000-8000-000000000004';
+const member = () =>
+ connectorRouter.createCaller({
+ serverDB: {},
+ userId: 'me',
+ workspaceId: 'ws-1',
+ workspaceRole: 'member',
+ } as any);
+
+const myPrivateDevice = { deviceId: 'my-laptop', userId: 'me', visibility: 'private' };
+const sharedDevice = { deviceId: 'office-nas', userId: 'enroller', visibility: 'public' };
+const devices = new Map([myPrivateDevice, sharedDevice].map((d) => [d.deviceId, d]));
+
+const stdioInput = {
+ identifier: 'my-mcp',
+ mcpConnectionType: 'stdio' as const,
+ mcpStdioConfig: { command: 'my-mcp' },
+ name: 'My MCP',
+ sourceType: 'custom' as const,
+};
+
+describe('connectorRouter device binding by visibility', () => {
+ let connectorModelMock: any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.findWorkspaceDeviceById.mockImplementation(async (id: string) => devices.get(id));
+ connectorModelMock = {
+ create: vi.fn().mockResolvedValue({ id: 'created' }),
+ changeVisibilityUnlessHeld: vi.fn().mockResolvedValue({ changed: true }),
+ createUnlessIdentifierHeld: vi.fn().mockResolvedValue({ created: { id: 'created' } }),
+ findById: vi.fn(),
+ findScopedByIdentifier: vi.fn().mockResolvedValue(null),
+ update: vi.fn(),
+ };
+ vi.mocked(ConnectorModel).mockImplementation(function () {
+ return connectorModelMock;
+ });
+ vi.mocked(AgentModel).mockImplementation(function () {
+ return {} as any;
+ });
+ vi.mocked(ConnectorToolModel).mockImplementation(function () {
+ return { queryByConnector: vi.fn().mockResolvedValue([]) } as any;
+ });
+ });
+
+ describe('create', () => {
+ it("binds a private connector to the creator's own private device", async () => {
+ await expect(
+ member().create({
+ ...stdioInput,
+ metadata: { boundDeviceId: 'my-laptop' },
+ visibility: 'private',
+ }),
+ ).resolves.toEqual({ id: 'created', isNew: true });
+ expect(connectorModelMock.createUnlessIdentifierHeld).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: expect.objectContaining({ boundDeviceId: 'my-laptop' }),
+ visibility: 'private',
+ }),
+ );
+ });
+
+ it('binds a private connector to a shared device of the workspace', async () => {
+ await expect(
+ member().create({
+ ...stdioInput,
+ metadata: { boundDeviceId: 'office-nas' },
+ visibility: 'private',
+ }),
+ ).resolves.toEqual({ id: 'created', isNew: true });
+ });
+
+ it('refuses a shared connector a private device', async () => {
+ await expect(
+ member().create({ ...stdioInput, metadata: { boundDeviceId: 'my-laptop' } }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(connectorModelMock.createUnlessIdentifierHeld).not.toHaveBeenCalled();
+ });
+
+ it('binds a shared connector to a shared device', async () => {
+ await expect(
+ member().create({ ...stdioInput, metadata: { boundDeviceId: 'office-nas' } }),
+ ).resolves.toEqual({ id: 'created', isNew: true });
+ });
+ });
+
+ describe('update', () => {
+ const privateRow = (boundDeviceId?: string) => ({
+ agentId: null,
+ id: CONNECTOR_ID,
+ identifier: 'my-mcp',
+ mcpConnectionType: 'stdio',
+ metadata: boundDeviceId ? { boundDeviceId } : {},
+ userId: 'me',
+ visibility: 'private',
+ });
+
+ it("rebinds a private connector to the creator's own private device", async () => {
+ connectorModelMock.findById.mockResolvedValue(privateRow());
+
+ await member().update({
+ id: CONNECTOR_ID,
+ patch: { metadata: { boundDeviceId: 'my-laptop' } },
+ });
+
+ expect(connectorModelMock.update).toHaveBeenCalledWith(
+ CONNECTOR_ID,
+ expect.objectContaining({ metadata: { boundDeviceId: 'my-laptop' } }),
+ );
+ });
+
+ // Sharing hands the binding to every member's runs, which can't reach it
+ it('refuses to share a private connector still bound to a private device', async () => {
+ connectorModelMock.findById.mockResolvedValue(privateRow('my-laptop'));
+
+ await expect(
+ member().update({ id: CONNECTOR_ID, patch: { visibility: 'public' } }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(connectorModelMock.update).not.toHaveBeenCalled();
+ });
+
+ it('shares a private connector bound to a shared device', async () => {
+ connectorModelMock.findById.mockResolvedValue(privateRow('office-nas'));
+
+ await member().update({ id: CONNECTOR_ID, patch: { visibility: 'public' } });
+
+ // The share claims the shared slot under the identifier lock
+ expect(connectorModelMock.changeVisibilityUnlessHeld).toHaveBeenCalledWith(
+ CONNECTOR_ID,
+ expect.any(String),
+ 'public',
+ );
+ });
+
+ it('shares a private connector the same write moves to automatic routing', async () => {
+ connectorModelMock.findById.mockResolvedValue(privateRow('my-laptop'));
+
+ await member().update({ id: CONNECTOR_ID, patch: { metadata: {}, visibility: 'public' } });
+
+ expect(connectorModelMock.changeVisibilityUnlessHeld).toHaveBeenCalledWith(
+ CONNECTOR_ID,
+ expect.any(String),
+ 'public',
+ );
+ expect(connectorModelMock.update).toHaveBeenCalledWith(
+ CONNECTOR_ID,
+ expect.objectContaining({ metadata: {} }),
+ );
+ });
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts
index d6a6ec82db1..6a7d0b9fa3a 100644
--- a/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts
@@ -70,7 +70,11 @@ describe('connectorRouter.syncPluginTools — customPlugin guard', () => {
vi.clearAllMocks();
connectorModelMock = {
+ create: vi.fn().mockResolvedValue({ id: 'conn-new' }),
createUnlessIdentifierHeld: vi.fn().mockResolvedValue({ created: { id: 'conn-new' } }),
+ findManageableByIdentifier: vi.fn().mockResolvedValue(null),
+ findScopedByIdentifier: vi.fn().mockResolvedValue(null),
+ isComposioAccountPrivateToTeammate: vi.fn().mockResolvedValue(false),
queryByIdentifiers: vi.fn().mockResolvedValue([]),
update: vi.fn(),
};
@@ -93,6 +97,7 @@ describe('connectorRouter.syncPluginTools — customPlugin guard', () => {
serverDB: {},
userId: 'user_test',
workspaceId: workspaceId ?? null,
+ ...(workspaceId && { workspaceRole: 'member' }),
} as any);
it('returns { connectorId: null } early for customPlugin rows that own an MCP endpoint', async () => {
@@ -198,16 +203,14 @@ describe('connectorRouter.syncPluginTools — customPlugin guard', () => {
// Opening connector details automatically calls syncPluginTools. The old
// update replaced metadata with display fields only, erasing the account id
// needed for execution and remote revocation.
- connectorModelMock.queryByIdentifiers.mockResolvedValue([
- {
- id: 'conn-existing',
- metadata: {
- composio: activeGmailAuthConfig(),
- mountedByAgentId: 'agent-1',
- },
- userId: 'user_test',
+ connectorModelMock.findManageableByIdentifier.mockResolvedValueOnce({
+ id: 'conn-existing',
+ metadata: {
+ composio: activeGmailAuthConfig(),
+ mountedByAgentId: 'agent-1',
},
- ]);
+ userId: 'user_test',
+ });
pluginModelMock.findById.mockResolvedValueOnce({
type: 'plugin',
customParams: {
@@ -260,6 +263,106 @@ describe('connectorRouter.syncPluginTools — customPlugin guard', () => {
expect(connectorToolModelMock.upsertMany).not.toHaveBeenCalled();
});
+ it("leaves the caller's private installed connector as it is", async () => {
+ // The shared-only lookup misses a private row, which upsertConnectorEntry
+ // then refreshes in place: the plugin row's old manifest would go back
+ // over the tools the install synced from the server.
+ connectorModelMock.findScopedByIdentifier.mockResolvedValue({
+ id: 'conn-private-installed',
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example.com',
+ sourceType: 'marketplace',
+ userId: 'user_test',
+ visibility: 'private',
+ });
+ pluginModelMock.findById.mockResolvedValueOnce({
+ type: 'plugin',
+ manifest: {
+ api: [{ description: 'Old search', name: 'search', parameters: {} }],
+ meta: { description: 'Old manifest', title: 'Search MCP' },
+ },
+ });
+
+ const result = await callerFor('ws-1').syncPluginTools({ identifier: 'search-mcp' });
+
+ expect(connectorModelMock.findScopedByIdentifier).toHaveBeenCalledWith(
+ 'search-mcp',
+ undefined,
+ undefined,
+ 'private',
+ );
+ expect(result).toEqual({ connectorId: 'conn-private-installed', toolCount: 0 });
+ expect(connectorModelMock.update).not.toHaveBeenCalled();
+ expect(connectorToolModelMock.upsertMany).not.toHaveBeenCalled();
+ });
+
+ it('refreshes a connector switched to private in place, not through a new shared twin', async () => {
+ // Regression: the lookup saw shared rows only, so refreshing a private
+ // Composio connector created an enabled shared row carrying the same
+ // account from the plugin projection, offering it to every workspace agent.
+ connectorModelMock.findManageableByIdentifier.mockResolvedValueOnce({
+ agentId: null,
+ id: 'conn-private',
+ metadata: { composio: activeGmailAuthConfig() },
+ userId: 'user_test',
+ visibility: 'private',
+ });
+ pluginModelMock.findById.mockResolvedValueOnce({
+ type: 'plugin',
+ customParams: { composio: activeGmailAuthConfig() },
+ manifest: { api: [{ name: 'send' }], meta: { title: 'Gmail' } },
+ });
+
+ const result = await callerFor('ws-1').syncPluginTools({ identifier: 'gmail' });
+
+ expect(connectorModelMock.findManageableByIdentifier).toHaveBeenCalledWith(
+ 'gmail',
+ undefined,
+ 'ca-gmail',
+ );
+ expect(result).toEqual({ connectorId: 'conn-private', toolCount: 1 });
+ expect(connectorModelMock.create).not.toHaveBeenCalled();
+ expect(connectorModelMock.update).toHaveBeenCalledWith('conn-private', {
+ metadata: expect.objectContaining({ composio: activeGmailAuthConfig() }),
+ });
+ });
+
+ it("never projects a teammate's private Composio account onto a shared row", async () => {
+ // The plugin projection is workspace-wide, so a teammate still reads the
+ // account of a connector its owner made private.
+ connectorModelMock.isComposioAccountPrivateToTeammate.mockResolvedValue(true);
+ pluginModelMock.findById.mockResolvedValue({
+ type: 'plugin',
+ customParams: { composio: activeGmailAuthConfig() },
+ manifest: { api: [{ name: 'send' }], meta: { description: 'Gmail tools', title: 'Gmail' } },
+ });
+
+ // No row of theirs: nothing is created
+ expect(await callerFor('ws-1').syncPluginTools({ identifier: 'gmail' })).toEqual({
+ connectorId: null,
+ toolCount: 0,
+ });
+ expect(connectorModelMock.create).not.toHaveBeenCalled();
+ expect(connectorToolModelMock.upsertMany).not.toHaveBeenCalled();
+
+ // Their own shared row keeps its account; only the display fields refresh
+ connectorModelMock.findManageableByIdentifier.mockResolvedValueOnce({
+ agentId: null,
+ id: 'conn-shared',
+ metadata: { composio: { ...activeGmailAuthConfig(), connectedAccountId: 'ca-shared' } },
+ userId: 'user_test',
+ visibility: 'public',
+ });
+ await callerFor('ws-1').syncPluginTools({ identifier: 'gmail' });
+
+ expect(connectorModelMock.update).toHaveBeenCalledWith('conn-shared', {
+ metadata: {
+ composio: expect.objectContaining({ connectedAccountId: 'ca-shared' }),
+ description: 'Gmail tools',
+ },
+ });
+ });
+
it('also defers when plugin has type=customPlugin AND has a manifest (no half-baked row written)', async () => {
// Some legacy customPlugin rows DO have a manifest (cached from a successful
// tools/list call earlier). The guard must not fall through just because a
@@ -513,12 +616,21 @@ describe('connectorRouter.delete — agent connector unpins from the owning agen
connectorModelMock = {
delete: vi.fn().mockResolvedValue(undefined),
findById: vi.fn(),
+ // The Composio rows below run their own account and no other row does.
+ queryComposioAccountHolders: vi
+ .fn()
+ .mockResolvedValue([
+ { agentId: null, id: 'c-composio', userId: 'user_test', visibility: 'public' },
+ ]),
};
agentModelMock = {
getAgentConfigById: vi.fn(),
update: vi.fn().mockResolvedValue(undefined),
};
- pluginModelMock = { delete: vi.fn().mockResolvedValue(undefined) };
+ pluginModelMock = {
+ deleteComposioMirrors: vi.fn().mockResolvedValue(undefined),
+ deleteComposioProjectionKeepingPrivate: vi.fn().mockResolvedValue(undefined),
+ };
mocks.connectedAccountsDelete.mockResolvedValue(undefined);
mocks.removeSubscriptions.mockResolvedValue(undefined);
vi.mocked(ConnectorModel).mockImplementation(function () {
@@ -623,7 +735,7 @@ describe('connectorRouter.delete — agent connector unpins from the owning agen
await caller().delete({ id: DELETE_ID });
expect(mocks.connectedAccountsDelete).toHaveBeenCalledWith('ca-github');
- expect(pluginModelMock.delete).toHaveBeenCalledWith('github');
+ expect(pluginModelMock.deleteComposioProjectionKeepingPrivate).toHaveBeenCalledWith('github');
expect(connectorModelMock.delete).toHaveBeenCalledWith(DELETE_ID);
});
@@ -646,11 +758,44 @@ describe('connectorRouter.delete — agent connector unpins from the owning agen
'[Composio] Failed to delete remote connection:',
expect.any(Error),
);
- expect(pluginModelMock.delete).toHaveBeenCalledWith('gmail');
+ expect(pluginModelMock.deleteComposioProjectionKeepingPrivate).toHaveBeenCalledWith('gmail');
expect(connectorModelMock.delete).toHaveBeenCalledWith(DELETE_ID);
warn.mockRestore();
});
+ it('keeps a teammate’s private account when a row of the caller’s merely names it', async () => {
+ // A connector's metadata is client-written, so a member's own row can name
+ // the account of a teammate's private connector. Deleting the row must not
+ // delete that remote account or the projection rows mirroring it.
+ connectorModelMock.findById.mockResolvedValueOnce({
+ agentId: null,
+ id: 'c-forged',
+ identifier: 'gmail',
+ metadata: { composio: { connectedAccountId: 'ca-mate' } },
+ userId: 'user_test',
+ visibility: 'private',
+ });
+ connectorModelMock.queryComposioAccountHolders.mockResolvedValueOnce([
+ { agentId: null, id: 'c-forged', userId: 'user_test', visibility: 'private' },
+ { agentId: null, id: 'c-mate', userId: 'another-user', visibility: 'private' },
+ ]);
+
+ await connectorRouter
+ .createCaller({
+ serverDB: {},
+ userId: 'user_test',
+ workspaceId: 'ws-1',
+ workspaceRole: 'member',
+ } as any)
+ .delete({ id: DELETE_ID });
+
+ expect(connectorModelMock.queryComposioAccountHolders).toHaveBeenCalledWith('ca-mate');
+ expect(mocks.connectedAccountsDelete).not.toHaveBeenCalled();
+ expect(pluginModelMock.deleteComposioProjectionKeepingPrivate).not.toHaveBeenCalled();
+ expect(pluginModelMock.deleteComposioMirrors).not.toHaveBeenCalled();
+ expect(connectorModelMock.delete).toHaveBeenCalledWith(DELETE_ID);
+ });
+
it('does not call Composio or delete a plugin for an ordinary connector', async () => {
connectorModelMock.findById.mockResolvedValueOnce({
agentId: null,
@@ -663,7 +808,7 @@ describe('connectorRouter.delete — agent connector unpins from the owning agen
await caller().delete({ id: DELETE_ID });
expect(mocks.connectedAccountsDelete).not.toHaveBeenCalled();
- expect(pluginModelMock.delete).not.toHaveBeenCalled();
+ expect(pluginModelMock.deleteComposioProjectionKeepingPrivate).not.toHaveBeenCalled();
expect(connectorModelMock.delete).toHaveBeenCalledWith(DELETE_ID);
});
diff --git a/apps/server/src/routers/lambda/__tests__/connector.visibility.test.ts b/apps/server/src/routers/lambda/__tests__/connector.visibility.test.ts
new file mode 100644
index 00000000000..6474f99930f
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/connector.visibility.test.ts
@@ -0,0 +1,509 @@
+// @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 { connectorRouter } from '../connector';
+
+const mocks = vi.hoisted(() => ({
+ auditCreate: vi.fn(),
+ getConnectorMemberManage: vi.fn(
+ async (): Promise<'admins_only' | 'all_members'> => 'all_members',
+ ),
+ updateConnectorMemberManage: vi.fn(),
+}));
+
+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() }));
+vi.mock('@/database/models/workspace', () => ({
+ WorkspaceModel: vi.fn(function () {
+ return {
+ getConnectorMemberManage: mocks.getConnectorMemberManage,
+ updateConnectorMemberManage: mocks.updateConnectorMemberManage,
+ };
+ }),
+}));
+vi.mock('@/database/models/workspaceAuditLog', () => ({
+ WorkspaceAuditLogModel: vi.fn(function () {
+ return { create: mocks.auditCreate };
+ }),
+}));
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },
+}));
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');
+ const rank: Record<string, number> = { admin: 2, member: 1, owner: 3, viewer: 0 };
+ return {
+ requireWorkspaceRoleWhenScoped: (minRole: string) =>
+ mod.trpc.middleware(async (opts: any) => {
+ const { workspaceId, workspaceRole } = opts.ctx;
+ if (workspaceId && (rank[workspaceRole] ?? -1) < rank[minRole]) {
+ const { TRPCError } = await import('@trpc/server');
+ throw new TRPCError({ code: 'FORBIDDEN', message: `Requires ${minRole}` });
+ }
+ return 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 ?? {} } }),
+}));
+
+const callerFor = (ctx: Record<string, unknown>) =>
+ connectorRouter.createCaller({ serverDB: {}, userId: 'me', ...ctx } as any);
+
+const CONNECTOR_ID = '9f1f6f30-0000-4000-8000-000000000003';
+const member = () => callerFor({ workspaceId: 'ws-1', workspaceRole: 'member' });
+
+describe('connectorRouter visibility', () => {
+ let connectorModelMock: any;
+ /** The OAuth accounts a connector row holds, as `ConnectorLinkModel` lists them. */
+ const linksOf = vi.fn();
+ let agentModelMock: any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getConnectorMemberManage.mockResolvedValue('all_members');
+ connectorModelMock = {
+ copyToAgent: vi.fn().mockResolvedValue({ id: 'copied' }),
+ create: vi.fn().mockResolvedValue({ id: 'created' }),
+ createUnlessIdentifierHeld: vi.fn().mockResolvedValue({ created: { id: 'created' } }),
+ findById: vi.fn(),
+ findScopedByIdentifier: vi.fn().mockResolvedValue(null),
+ changeVisibilityUnlessHeld: vi.fn().mockResolvedValue({ changed: true }),
+ getLinkModel: () => ({ listByConnectorIds: linksOf }),
+ update: vi.fn(),
+ };
+ linksOf.mockReset().mockResolvedValue([]);
+ agentModelMock = {
+ existsOwnedById: vi.fn().mockResolvedValue(true),
+ getAgentVisibility: vi.fn().mockResolvedValue('private'),
+ };
+ vi.mocked(ConnectorModel).mockImplementation(function () {
+ return connectorModelMock;
+ });
+ vi.mocked(AgentModel).mockImplementation(function () {
+ return agentModelMock;
+ });
+ vi.mocked(ConnectorToolModel).mockImplementation(function () {
+ return { queryByConnector: vi.fn().mockResolvedValue([]) } as any;
+ });
+ });
+
+ const createInput = {
+ identifier: 'my-mcp',
+ mcpConnectionType: 'stdio' as const,
+ mcpStdioConfig: { command: 'echo' },
+ name: 'My MCP',
+ sourceType: 'custom' as const,
+ };
+
+ describe('create', () => {
+ it('adds a private connector even when admins restricted the shared ones', async () => {
+ mocks.getConnectorMemberManage.mockResolvedValue('admins_only');
+
+ await expect(member().create({ ...createInput, visibility: 'private' })).resolves.toEqual({
+ id: 'created',
+ isNew: true,
+ });
+ expect(connectorModelMock.createUnlessIdentifierHeld).toHaveBeenCalledWith(
+ expect.objectContaining({ visibility: 'private' }),
+ );
+ });
+
+ it("looks for an existing row among the caller's private rows only", async () => {
+ await member().create({ ...createInput, visibility: 'private' });
+
+ expect(connectorModelMock.findScopedByIdentifier).toHaveBeenCalledWith(
+ 'my-mcp',
+ undefined,
+ undefined,
+ 'private',
+ );
+ });
+
+ it('never stores a Composio account a member names on a connector they add', async () => {
+ // Regression: a member read a shared connection's account id and added a
+ // private connector naming it. Every Composio write then found a
+ // teammate's private row holding the account and refused its real owner,
+ // while nobody else could see the planted row to remove it.
+ await member().create({
+ ...createInput,
+ metadata: { avatar: '🔌', composio: { connectedAccountId: 'acc-shared' } },
+ visibility: 'private',
+ });
+
+ expect(connectorModelMock.createUnlessIdentifierHeld).toHaveBeenCalledWith(
+ expect.objectContaining({ metadata: { avatar: '🔌' } }),
+ );
+ });
+
+ it("never mounts a connector a member adds on a teammate's agent", async () => {
+ // Regression: under `all_members`, a member added a shared connector
+ // naming a teammate's private agent as its mount, under the identifier of
+ // the owner's private connector. The mount outranked the owner's row, so
+ // the agent sent its tool calls to the member's server. Only
+ // mountToAgent mounts, after checking who created the agent.
+ await member().create({
+ ...createInput,
+ metadata: { avatar: '🔌', mountedByAgentId: 'agt-victim' },
+ });
+
+ expect(connectorModelMock.createUnlessIdentifierHeld).toHaveBeenCalledWith(
+ expect.objectContaining({ metadata: { avatar: '🔌' }, visibility: 'public' }),
+ );
+ });
+
+ it('shares by default, and stores personal rows as shared', async () => {
+ await member().create(createInput);
+ await callerFor({}).create({ ...createInput, visibility: 'private' });
+
+ expect(connectorModelMock.createUnlessIdentifierHeld).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({ visibility: 'public' }),
+ );
+ expect(connectorModelMock.createUnlessIdentifierHeld).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({ visibility: 'public' }),
+ );
+ });
+ it("keeps a re-added row's Composio account, so its legacy projection stays withheld", async () => {
+ // Regression: re-adding a private Composio connector cleared its account
+ // block. The legacy plugin projection then held the account alone, and
+ // workspace agents ran the private connection through the fallback.
+ const composio = { connectedAccountId: 'acc-private', linkedByUserId: 'me' };
+ connectorModelMock.findScopedByIdentifier.mockResolvedValue({
+ agentId: null,
+ id: 'mine',
+ metadata: { avatar: '🔌', composio },
+ userId: 'me',
+ visibility: 'private',
+ });
+ connectorModelMock.update.mockResolvedValue({ id: 'mine' });
+
+ await member().create({
+ ...createInput,
+ metadata: { avatar: '🛠', composio: { connectedAccountId: 'acc-forged' } },
+ visibility: 'private',
+ });
+
+ expect(connectorModelMock.update).toHaveBeenCalledWith(
+ 'mine',
+ expect.objectContaining({ metadata: { avatar: '🛠', composio } }),
+ );
+ });
+
+ it('claims a private row within its visibility and re-adds over the holder it finds', async () => {
+ // A concurrent add of the same private connector won the claim: this add
+ // rewrites that row instead of inserting a second one.
+ connectorModelMock.createUnlessIdentifierHeld.mockResolvedValue({
+ holder: { agentId: null, id: 'held', metadata: null, userId: 'me', visibility: 'private' },
+ });
+ connectorModelMock.update.mockResolvedValue({ id: 'held' });
+
+ await expect(member().create({ ...createInput, visibility: 'private' })).resolves.toEqual({
+ id: 'held',
+ isNew: false,
+ });
+ expect(connectorModelMock.createUnlessIdentifierHeld).toHaveBeenCalledWith(
+ expect.objectContaining({ identifier: 'my-mcp', visibility: 'private' }),
+ );
+ expect(connectorModelMock.update).toHaveBeenCalledWith('held', expect.anything());
+ });
+ });
+
+ describe.each(['bindAgent', 'copyToAgent', 'mountToAgent'] as const)('%s', (procedure) => {
+ const privateConnector = {
+ agentId: null,
+ id: CONNECTOR_ID,
+ identifier: 'my-mcp',
+ metadata: null,
+ userId: 'me',
+ visibility: 'private',
+ };
+
+ it('refuses to hand a private connector to a workspace agent', async () => {
+ connectorModelMock.findById.mockResolvedValue(privateConnector);
+ agentModelMock.getAgentVisibility.mockResolvedValue('public');
+
+ await expect(
+ member()[procedure]({ agentId: 'agt-shared', connectorId: CONNECTOR_ID }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(connectorModelMock.update).not.toHaveBeenCalled();
+ expect(connectorModelMock.copyToAgent).not.toHaveBeenCalled();
+ });
+
+ it("allows it on the creator's own private agent", async () => {
+ connectorModelMock.findById.mockResolvedValue(privateConnector);
+
+ await expect(
+ member()[procedure]({ agentId: 'agt-mine', connectorId: CONNECTOR_ID }),
+ ).resolves.toBeDefined();
+ });
+
+ it('leaves shared connectors to the existing rules', async () => {
+ connectorModelMock.findById.mockResolvedValue({ ...privateConnector, visibility: 'public' });
+ agentModelMock.getAgentVisibility.mockResolvedValue('public');
+
+ await expect(
+ member()[procedure]({ agentId: 'agt-shared', connectorId: CONNECTOR_ID }),
+ ).resolves.toBeDefined();
+ expect(agentModelMock.getAgentVisibility).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('unbindAgent', () => {
+ const agentRow = (visibility: 'private' | 'public') => ({
+ agentId: 'agt-mine',
+ id: CONNECTOR_ID,
+ identifier: 'my-mcp',
+ metadata: null,
+ userId: 'me',
+ visibility,
+ });
+
+ it('returns a private agent row to the base scope beside a shared sibling', async () => {
+ // Regression: the base-slot check looked among shared rows only, so the
+ // shared connector of the same identifier blocked the private row's
+ // return with CONFLICT although its private slot was empty. The move
+ // looks for a holder in the row's own visibility (see the model).
+ connectorModelMock.findById.mockResolvedValue(agentRow('private'));
+ connectorModelMock.moveToBaseUnlessIdentifierHeld = vi
+ .fn()
+ .mockResolvedValue({ moved: true });
+
+ await expect(member().unbindAgent({ connectorId: CONNECTOR_ID })).resolves.toEqual({
+ id: CONNECTOR_ID,
+ });
+ expect(connectorModelMock.moveToBaseUnlessIdentifierHeld).toHaveBeenCalledWith(
+ CONNECTOR_ID,
+ 'my-mcp',
+ );
+ });
+
+ it('still refuses to return a row into an occupied slot of its visibility', async () => {
+ connectorModelMock.findById.mockResolvedValue(agentRow('public'));
+ connectorModelMock.moveToBaseUnlessIdentifierHeld = vi
+ .fn()
+ .mockResolvedValue({ holder: { id: 'base-row' } });
+
+ await expect(member().unbindAgent({ connectorId: CONNECTOR_ID })).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect(connectorModelMock.update).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('update visibility', () => {
+ const row = (overrides: Record<string, unknown> = {}) => ({
+ agentId: null,
+ id: CONNECTOR_ID,
+ identifier: 'my-mcp',
+ metadata: null,
+ userId: 'me',
+ visibility: 'public',
+ ...overrides,
+ });
+
+ it('lets the creator make their shared connector private', async () => {
+ connectorModelMock.findById.mockResolvedValue(row());
+
+ await member().update({ id: CONNECTOR_ID, patch: { visibility: 'private' } });
+
+ expect(connectorModelMock.changeVisibilityUnlessHeld).toHaveBeenCalledWith(
+ CONNECTOR_ID,
+ 'my-mcp',
+ 'private',
+ );
+ });
+
+ it('refuses when the destination slot was taken meanwhile', async () => {
+ // Regression: two members sharing private connectors of one identifier
+ // at once both passed the separate slot lookup and both became shared
+ connectorModelMock.findById.mockResolvedValue(row({ visibility: 'private' }));
+ vi.spyOn(mocks, 'getConnectorMemberManage').mockResolvedValue('all_members');
+ connectorModelMock.changeVisibilityUnlessHeld.mockResolvedValue({ holder: { id: 'other' } });
+
+ await expect(
+ member().update({ id: CONNECTOR_ID, patch: { visibility: 'public' } }),
+ ).rejects.toMatchObject({ code: 'CONFLICT' });
+ expect(connectorModelMock.update).not.toHaveBeenCalled();
+ });
+
+ it('lets the member who linked a Composio account make it private', async () => {
+ connectorModelMock.findById.mockResolvedValue(
+ row({ metadata: { composio: { connectedAccountId: 'acc-1', linkedByUserId: 'me' } } }),
+ );
+
+ await member().update({ id: CONNECTOR_ID, patch: { visibility: 'private' } });
+
+ expect(connectorModelMock.changeVisibilityUnlessHeld).toHaveBeenCalledWith(
+ CONNECTOR_ID,
+ 'my-mcp',
+ 'private',
+ );
+ });
+
+ it.each([
+ ['a workspace agent', 'public', true],
+ ["a teammate's private agent", 'private', false],
+ ] as const)(
+ 'refuses to make private a connector mounted on %s',
+ async (_label, agentVisibility, owned) => {
+ // Regression: the switch succeeded, run scoping then dropped the row
+ // from the agent it is mounted on, and its configured tool vanished.
+ connectorModelMock.findById.mockResolvedValue(
+ row({ metadata: { mountedByAgentId: 'agt-mounted' } }),
+ );
+ agentModelMock.getAgentVisibility.mockResolvedValue(agentVisibility);
+ agentModelMock.existsOwnedById.mockResolvedValue(owned);
+
+ await expect(
+ member().update({ id: CONNECTOR_ID, patch: { visibility: 'private' } }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(connectorModelMock.update).not.toHaveBeenCalled();
+ },
+ );
+
+ it('makes private a connector mounted on its creator’s own private agent', async () => {
+ connectorModelMock.findById.mockResolvedValue(
+ row({ metadata: { mountedByAgentId: 'agt-mine' } }),
+ );
+
+ await member().update({ id: CONNECTOR_ID, patch: { visibility: 'private' } });
+
+ expect(connectorModelMock.changeVisibilityUnlessHeld).toHaveBeenCalledWith(
+ CONNECTOR_ID,
+ 'my-mcp',
+ 'private',
+ );
+ });
+
+ it('refuses to make private a connector holding an account a teammate authorized', async () => {
+ // Regression: only Composio's linker was checked, so a creator could make
+ // private a shared OAuth connector a teammate had authorized and run the
+ // teammate's token from their own private agent.
+ connectorModelMock.findById.mockResolvedValue(row());
+ linksOf.mockResolvedValue([
+ { id: 'lnk_me', userId: 'me' },
+ { id: 'lnk_mate', userId: 'mate' },
+ ]);
+
+ await expect(
+ member().update({ id: CONNECTOR_ID, patch: { visibility: 'private' } }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(linksOf).toHaveBeenCalledWith([CONNECTOR_ID]);
+ expect(connectorModelMock.update).not.toHaveBeenCalled();
+ });
+
+ it('makes private a connector whose accounts are all the creator’s own', async () => {
+ connectorModelMock.findById.mockResolvedValue(row());
+ linksOf.mockResolvedValue([{ id: 'lnk_me', userId: 'me' }]);
+
+ await member().update({ id: CONNECTOR_ID, patch: { visibility: 'private' } });
+
+ expect(connectorModelMock.changeVisibilityUnlessHeld).toHaveBeenCalledWith(
+ CONNECTOR_ID,
+ 'my-mcp',
+ 'private',
+ );
+ });
+
+ it('refuses to make private a Composio account someone else linked', async () => {
+ // The creator opened a teammate's legacy connection first, so the row is
+ // theirs, but the account runs as the teammate. Making it private would
+ // take the teammate's connection from the teammate and everyone else.
+ connectorModelMock.findById.mockResolvedValue(
+ row({ metadata: { composio: { connectedAccountId: 'acc-1', linkedByUserId: 'mate' } } }),
+ );
+
+ await expect(
+ member().update({ id: CONNECTOR_ID, patch: { visibility: 'private' } }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(connectorModelMock.update).not.toHaveBeenCalled();
+ });
+
+ it('keeps the Composio account a row names when an edit sends another', async () => {
+ connectorModelMock.findById.mockResolvedValue(
+ row({
+ metadata: { composio: { connectedAccountId: 'acc-1', linkedByUserId: 'me' } },
+ visibility: 'private',
+ }),
+ );
+
+ await member().update({
+ id: CONNECTOR_ID,
+ patch: { metadata: { avatar: '🔌', composio: { connectedAccountId: 'acc-shared' } } },
+ });
+
+ expect(connectorModelMock.update).toHaveBeenCalledWith(
+ CONNECTOR_ID,
+ expect.objectContaining({
+ metadata: {
+ avatar: '🔌',
+ composio: { connectedAccountId: 'acc-1', linkedByUserId: 'me' },
+ },
+ }),
+ );
+ });
+
+ it('never mounts a connector through an edit', async () => {
+ connectorModelMock.findById.mockResolvedValue(row({ metadata: { avatar: '🔌' } }));
+
+ await member().update({
+ id: CONNECTOR_ID,
+ patch: { metadata: { avatar: '🔌', mountedByAgentId: 'agt-victim' } },
+ });
+
+ expect(connectorModelMock.update).toHaveBeenCalledWith(
+ CONNECTOR_ID,
+ expect.objectContaining({ metadata: { avatar: '🔌' } }),
+ );
+ });
+
+ it('never lets someone else change who a connector is shared with', async () => {
+ connectorModelMock.findById.mockResolvedValue(row({ userId: 'someone-else' }));
+
+ await expect(
+ callerFor({ workspaceId: 'ws-1', workspaceRole: 'owner' }).update({
+ id: CONNECTOR_ID,
+ patch: { visibility: 'private' },
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(connectorModelMock.update).not.toHaveBeenCalled();
+ });
+
+ it('follows the member policy when sharing a private connector', async () => {
+ mocks.getConnectorMemberManage.mockResolvedValue('admins_only');
+ connectorModelMock.findById.mockResolvedValue(row({ visibility: 'private' }));
+
+ await expect(
+ member().update({ id: CONNECTOR_ID, patch: { visibility: 'public' } }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it('refuses a second shared connector of the same identifier', async () => {
+ connectorModelMock.findById.mockResolvedValue(row({ visibility: 'private' }));
+ connectorModelMock.findScopedByIdentifier.mockResolvedValue(row({ id: 'other' }));
+
+ await expect(
+ member().update({ id: CONNECTOR_ID, patch: { visibility: 'public' } }),
+ ).rejects.toMatchObject({ code: 'CONFLICT' });
+ });
+
+ it("leaves an agent's own connector to its agent", async () => {
+ connectorModelMock.findById.mockResolvedValue(row({ agentId: 'agt-1' }));
+
+ await expect(
+ member().update({ id: CONNECTOR_ID, patch: { visibility: 'private' } }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/plugin.composioLinkRedaction.test.ts b/apps/server/src/routers/lambda/__tests__/plugin.composioLinkRedaction.test.ts
new file mode 100644
index 00000000000..7d5742a2134
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/plugin.composioLinkRedaction.test.ts
@@ -0,0 +1,74 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { PluginModel } from '@/database/models/plugin';
+
+import { pluginRouter } from '../plugin';
+
+vi.mock('@/database/models/plugin', () => ({ PluginModel: vi.fn() }));
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');
+ return { wsCompatProcedure: mod.trpc.procedure };
+});
+vi.mock('@/libs/trpc/lambda/middleware', () => ({
+ serverDatabase: async (opts: any) =>
+ opts.next({ ctx: { ...opts.ctx, serverDB: opts.ctx.serverDB ?? {} } }),
+}));
+
+const pendingRow = (linkedByUserId: string) => ({
+ customParams: {
+ composio: {
+ connectedAccountId: 'ca_1',
+ linkedByUserId,
+ redirectUrl: 'https://composio.example/link/abc',
+ status: 'INITIATED',
+ },
+ },
+ identifier: 'gmail',
+});
+
+/**
+ * A pending hosted OAuth link is a live capability of whoever started it. The
+ * generic plugin list is workspace-wide, so it must keep the link only for its
+ * linker, like `composio.getComposioPlugins` does.
+ */
+describe('pluginRouter.getPlugins composio link redaction', () => {
+ const query = vi.fn();
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(PluginModel).mockImplementation(function () {
+ return { query } as any;
+ });
+ });
+
+ const list = (ctx: { userId: string; workspaceId?: string }) =>
+ pluginRouter.createCaller(ctx as any).getPlugins();
+
+ it("drops a teammate's pending link in a workspace", async () => {
+ query.mockResolvedValue([pendingRow('user-2')]);
+
+ const [row] = await list({ userId: 'user-1', workspaceId: 'ws-1' });
+
+ expect(row.customParams?.composio).not.toHaveProperty('redirectUrl');
+ // A teammate's private connection is never listed to the client
+ expect(query).toHaveBeenCalledWith({ forClient: true });
+ expect(row.customParams?.composio).toMatchObject({ connectedAccountId: 'ca_1' });
+ });
+
+ it('keeps the link for its linker', async () => {
+ query.mockResolvedValue([pendingRow('user-1')]);
+
+ const [row] = await list({ userId: 'user-1', workspaceId: 'ws-1' });
+
+ expect(row.customParams?.composio?.redirectUrl).toBe('https://composio.example/link/abc');
+ });
+
+ it('keeps every link outside a workspace', async () => {
+ query.mockResolvedValue([pendingRow('user-2')]);
+
+ const [row] = await list({ userId: 'user-1' });
+
+ expect(row.customParams?.composio?.redirectUrl).toBe('https://composio.example/link/abc');
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/plugin.legacyWrites.test.ts b/apps/server/src/routers/lambda/__tests__/plugin.legacyWrites.test.ts
index 82ac374686d..d8db18a25a7 100644
--- a/apps/server/src/routers/lambda/__tests__/plugin.legacyWrites.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/plugin.legacyWrites.test.ts
@@ -117,4 +117,44 @@ describe('pluginRouter legacy create routes', () => {
procedure: 'createPlugin',
});
});
+ describe('server-owned Composio account', () => {
+ // Regression: a member copied a teammate's private Composio account (read
+ // off the workspace projection) into a plugin row of another identifier.
+ // The row passed for a legacy connection, and executeAction ran it.
+ const forged = {
+ composio: { connectedAccountId: 'acc-victim', linkedByUserId: 'victim', status: 'ACTIVE' },
+ mcp: { type: 'http', url: 'https://mcp.example.com' },
+ };
+
+ it.each(['createPlugin', 'createOrInstallPlugin'] as const)(
+ '%s drops a client-written composio block',
+ async (procedure) => {
+ await caller()[procedure]({
+ customParams: forged,
+ identifier: 'slack',
+ manifest: { api: [], identifier: 'slack' },
+ type: 'plugin',
+ });
+
+ expect(pluginModel.create).toHaveBeenCalledWith(
+ expect.objectContaining({ customParams: { mcp: forged.mcp } }),
+ );
+ },
+ );
+
+ it('updatePlugin keeps the stored block instead of the client one', async () => {
+ const stored = { connectedAccountId: 'acc-own', linkedByUserId: 'user-1' };
+ pluginModel.findById.mockResolvedValue({
+ customParams: { composio: stored },
+ userId: 'user-1',
+ });
+
+ await caller().updatePlugin({ customParams: forged, id: 'gmail' });
+
+ expect(pluginModel.update).toHaveBeenCalledWith(
+ 'gmail',
+ expect.objectContaining({ customParams: { composio: stored, mcp: forged.mcp } }),
+ );
+ });
+ });
});
diff --git a/apps/server/src/routers/lambda/_helpers/composioAccountBinding.ts b/apps/server/src/routers/lambda/_helpers/composioAccountBinding.ts
new file mode 100644
index 00000000000..88354b0532c
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/composioAccountBinding.ts
@@ -0,0 +1,80 @@
+import { TRPCError } from '@trpc/server';
+
+import type { ConnectorModel } from '@/database/models/connector';
+import type { PluginModel } from '@/database/models/plugin';
+
+import { assertConnectorMaintainable } from './connectorManagePolicy';
+
+type ComposioAccountCtx = Parameters<typeof assertConnectorMaintainable>[0] & {
+ connectorModel: Pick<ConnectorModel, 'queryComposioAccountHolders'>;
+};
+
+/**
+ * Why the caller may not act on a Composio account (delete it remotely, or
+ * point a connector at it) through `target`, the connector row their request
+ * was authorized on; `undefined` when they may.
+ *
+ * The account is resolved on its own, by id. The identifier a request also
+ * names is the caller's to choose, and every member reads the account ids of
+ * the workspace-wide plugin projection. The Composio client deletes an account
+ * by its id alone, so the remote delete reaches every row that runs it:
+ *
+ * - an account a teammate's private connector holds is that member's, even
+ * when a row of the caller's names it too;
+ * - an account other rows hold is acted on only through one of them, and only
+ * when the caller may maintain each of them;
+ * - an account no row holds is a legacy connection, which exists only as a
+ * plugin projection row of the app (`loadLegacyMirrors`). A write that has
+ * no legacy connection to act on (an agent's, which has no projection)
+ * omits it, and such an account is refused.
+ *
+ * The holders can be trusted because only the server writes the account a
+ * row names: the Composio connect paths link it, and the generic connector
+ * create/update drop any `composio` block a client sends
+ * (`withServerOwnedMetadata`). A member cannot plant a private row naming a
+ * teammate's account to lock its owner out of it.
+ */
+export const findComposioAccountConflict = async (
+ ctx: ComposioAccountCtx,
+ target: { id: string } | null,
+ connectedAccountId: string,
+ loadLegacyMirrors?: () => ReturnType<PluginModel['queryComposioMirrors']>,
+): Promise<TRPCError | undefined> => {
+ const holders = await ctx.connectorModel.queryComposioAccountHolders(connectedAccountId);
+
+ if (holders.some((row) => row.visibility === 'private' && row.userId !== ctx.userId)) {
+ return new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'This Composio connection belongs to another member’s private connector',
+ });
+ }
+
+ if (holders.length === 0) {
+ const mirrors = loadLegacyMirrors ? await loadLegacyMirrors() : [];
+ const isLegacy = mirrors.some(
+ (mirror) => mirror.customParams?.composio?.connectedAccountId === connectedAccountId,
+ );
+ if (isLegacy) return;
+ return new TRPCError({
+ code: 'NOT_FOUND',
+ message: 'This Composio connection is not one of this connector’s connections',
+ });
+ }
+
+ if (!target || !holders.some((row) => row.id === target.id)) {
+ return new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'This Composio connection belongs to a different connector',
+ });
+ }
+
+ for (const row of holders) {
+ if (row.id === target.id) continue;
+ try {
+ await assertConnectorMaintainable(ctx, row);
+ } catch (error) {
+ if (error instanceof TRPCError) return error;
+ throw error;
+ }
+ }
+};
diff --git a/apps/server/src/routers/lambda/_helpers/composioProjection.ts b/apps/server/src/routers/lambda/_helpers/composioProjection.ts
new file mode 100644
index 00000000000..68eec81f91e
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/composioProjection.ts
@@ -0,0 +1,55 @@
+import type { ConnectorVisibility } from '@lobechat/types';
+
+import type { PluginModel } from '@/database/models/plugin';
+
+/**
+ * Remove the legacy plugin projection of a base Composio connection that is
+ * being removed. In a workspace every member's projection row of an app is in
+ * scope. A shared connection is the workspace's projection of the app, so it
+ * goes, except the rows mirroring a member's private connection of the same
+ * app, which still runs on them. A private connection is one member's: only the
+ * rows mirroring its account go, and a teammate's legacy connection stays.
+ */
+export const removeComposioProjection = async (
+ pluginModel: Pick<
+ PluginModel,
+ 'deleteComposioMirrors' | 'deleteComposioProjectionKeepingPrivate'
+ >,
+ connection: {
+ connectedAccountId?: string | null;
+ identifier: string;
+ visibility?: ConnectorVisibility | null;
+ },
+): Promise<void> => {
+ if (connection.visibility !== 'private') {
+ await pluginModel.deleteComposioProjectionKeepingPrivate(connection.identifier);
+ return;
+ }
+ if (connection.connectedAccountId) {
+ await pluginModel.deleteComposioMirrors(connection.identifier, connection.connectedAccountId);
+ }
+};
+
+/**
+ * The legacy plugin projection is workspace-wide, but a pending hosted OAuth
+ * link (`customParams.composio.redirectUrl`) is a live capability of whoever
+ * started it: a teammate redeeming it would bind their own provider account to
+ * that connection (a private one included). Every read that returns plugin
+ * rows to a client keeps the link only for its linker; outside a workspace
+ * every row is the caller's own.
+ */
+export const redactForeignComposioLinks = <
+ T extends {
+ customParams?: { composio?: { linkedByUserId?: string; redirectUrl?: string } } | null;
+ },
+>(
+ plugins: T[],
+ ctx: { userId: string; workspaceId?: string | null },
+): T[] =>
+ plugins.map((plugin) => {
+ const composio = plugin.customParams?.composio;
+ if (!composio?.redirectUrl || !ctx.workspaceId || composio.linkedByUserId === ctx.userId)
+ return plugin;
+ const { redirectUrl: _redirectUrl, ...rest } = composio;
+ return { ...plugin, customParams: { ...plugin.customParams, composio: rest } };
+ });
diff --git a/apps/server/src/routers/lambda/_helpers/connectorDeviceBinding.test.ts b/apps/server/src/routers/lambda/_helpers/connectorDeviceBinding.test.ts
index 6f3273bcd36..84e026abd89 100644
--- a/apps/server/src/routers/lambda/_helpers/connectorDeviceBinding.test.ts
+++ b/apps/server/src/routers/lambda/_helpers/connectorDeviceBinding.test.ts
@@ -18,6 +18,9 @@ const serverDB = {} as never;
const personal = { serverDB, userId: 'u1' };
const workspace = { serverDB, userId: 'u1', workspaceId: 'ws1' };
+const shared = { userId: 'u1', visibility: 'public' } as const;
+const mine = { userId: 'u1', visibility: 'private' } as const;
+
describe('assertConnectorDeviceBindingAllowed', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -27,7 +30,10 @@ describe('assertConnectorDeviceBindingAllowed', () => {
findPersonalByDeviceId.mockResolvedValue({ deviceId: 'laptop' });
await expect(
- assertConnectorDeviceBindingAllowed(personal, { boundDeviceId: 'laptop' }),
+ assertConnectorDeviceBindingAllowed(personal, {
+ connector: shared,
+ metadata: { boundDeviceId: 'laptop' },
+ }),
).resolves.toBeUndefined();
expect(DeviceModel).toHaveBeenCalledWith(serverDB, 'u1');
expect(findPersonalByDeviceId).toHaveBeenCalledWith('laptop');
@@ -37,7 +43,10 @@ describe('assertConnectorDeviceBindingAllowed', () => {
findPersonalByDeviceId.mockResolvedValue(undefined);
await expect(
- assertConnectorDeviceBindingAllowed(personal, { boundDeviceId: 'someone-else' }),
+ assertConnectorDeviceBindingAllowed(personal, {
+ connector: shared,
+ metadata: { boundDeviceId: 'someone-else' },
+ }),
).rejects.toMatchObject({ code: 'BAD_REQUEST' });
});
@@ -45,7 +54,10 @@ describe('assertConnectorDeviceBindingAllowed', () => {
findWorkspaceDeviceById.mockResolvedValue({ deviceId: 'ws-nas', visibility: 'public' });
await expect(
- assertConnectorDeviceBindingAllowed(workspace, { boundDeviceId: 'ws-nas' }),
+ assertConnectorDeviceBindingAllowed(workspace, {
+ connector: shared,
+ metadata: { boundDeviceId: 'ws-nas' },
+ }),
).resolves.toBeUndefined();
expect(DeviceModel).toHaveBeenCalledWith(serverDB, 'u1', 'ws1');
});
@@ -53,10 +65,17 @@ describe('assertConnectorDeviceBindingAllowed', () => {
// Only the member who enrolled a private device can reach it, while every
// member's runs use a workspace connector
it('refuses a workspace connector a private device, even the caller’s own', async () => {
- findWorkspaceDeviceById.mockResolvedValue({ deviceId: 'my-private', visibility: 'private' });
+ findWorkspaceDeviceById.mockResolvedValue({
+ deviceId: 'my-private',
+ userId: 'u1',
+ visibility: 'private',
+ });
await expect(
- assertConnectorDeviceBindingAllowed(workspace, { boundDeviceId: 'my-private' }),
+ assertConnectorDeviceBindingAllowed(workspace, {
+ connector: shared,
+ metadata: { boundDeviceId: 'my-private' },
+ }),
).rejects.toMatchObject({ code: 'BAD_REQUEST' });
});
@@ -64,25 +83,153 @@ describe('assertConnectorDeviceBindingAllowed', () => {
findWorkspaceDeviceById.mockResolvedValue(undefined);
await expect(
- assertConnectorDeviceBindingAllowed(workspace, { boundDeviceId: 'personal-laptop' }),
+ assertConnectorDeviceBindingAllowed(workspace, {
+ connector: shared,
+ metadata: { boundDeviceId: 'personal-laptop' },
+ }),
).rejects.toMatchObject({ code: 'BAD_REQUEST' });
});
+ describe('a private workspace connector', () => {
+ // Only its creator's private agents load it, so their own device is reachable
+ it('may bind its creator’s own private device', async () => {
+ findWorkspaceDeviceById.mockResolvedValue({
+ deviceId: 'my-private',
+ userId: 'u1',
+ visibility: 'private',
+ });
+
+ await expect(
+ assertConnectorDeviceBindingAllowed(workspace, {
+ connector: mine,
+ metadata: { boundDeviceId: 'my-private' },
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('may bind a public device of the workspace', async () => {
+ findWorkspaceDeviceById.mockResolvedValue({
+ deviceId: 'ws-nas',
+ userId: 'enroller',
+ visibility: 'public',
+ });
+
+ await expect(
+ assertConnectorDeviceBindingAllowed(workspace, {
+ connector: mine,
+ metadata: { boundDeviceId: 'ws-nas' },
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ // The device read only returns the caller's own private rows; one written
+ // for another member's connector must still be that member's device
+ it('refuses a private device of someone other than its creator', async () => {
+ findWorkspaceDeviceById.mockResolvedValue({
+ deviceId: 'owner-private',
+ userId: 'u1',
+ visibility: 'private',
+ });
+
+ await expect(
+ assertConnectorDeviceBindingAllowed(workspace, {
+ connector: { userId: 'teammate', visibility: 'private' },
+ metadata: { boundDeviceId: 'owner-private' },
+ previous: { metadata: {}, visibility: 'private' },
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
+ it('refuses a teammate’s private device, which the caller cannot read', async () => {
+ findWorkspaceDeviceById.mockResolvedValue(undefined);
+
+ await expect(
+ assertConnectorDeviceBindingAllowed(workspace, {
+ connector: mine,
+ metadata: { boundDeviceId: 'teammate-private' },
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
+ // Sharing hands the kept binding to every member's runs
+ it('cannot be shared while it stays bound to a private device', async () => {
+ findWorkspaceDeviceById.mockResolvedValue({
+ deviceId: 'my-private',
+ userId: 'u1',
+ visibility: 'private',
+ });
+
+ await expect(
+ assertConnectorDeviceBindingAllowed(workspace, {
+ connector: shared,
+ metadata: undefined,
+ previous: { metadata: { boundDeviceId: 'my-private' }, visibility: 'private' },
+ }),
+ ).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: expect.stringContaining('before sharing it'),
+ });
+ });
+
+ it('can be shared when it is bound to a public device', async () => {
+ findWorkspaceDeviceById.mockResolvedValue({
+ deviceId: 'ws-nas',
+ userId: 'enroller',
+ visibility: 'public',
+ });
+
+ await expect(
+ assertConnectorDeviceBindingAllowed(workspace, {
+ connector: shared,
+ metadata: undefined,
+ previous: { metadata: { boundDeviceId: 'ws-nas' }, visibility: 'private' },
+ }),
+ ).resolves.toBeUndefined();
+ expect(findWorkspaceDeviceById).toHaveBeenCalledWith('ws-nas');
+ });
+
+ it('can be shared once the same write unbinds it', async () => {
+ await expect(
+ assertConnectorDeviceBindingAllowed(workspace, {
+ connector: shared,
+ metadata: {},
+ previous: { metadata: { boundDeviceId: 'my-private' }, visibility: 'private' },
+ }),
+ ).resolves.toBeUndefined();
+ expect(DeviceModel).not.toHaveBeenCalled();
+ });
+ });
+
it('skips writes without a binding, and a binding the write keeps unchanged', async () => {
- await assertConnectorDeviceBindingAllowed(workspace, { description: 'x' });
- await assertConnectorDeviceBindingAllowed(workspace, undefined);
- await assertConnectorDeviceBindingAllowed(
- workspace,
- { boundDeviceId: 'unshared-since' },
- { boundDeviceId: 'unshared-since' },
- );
+ await assertConnectorDeviceBindingAllowed(workspace, {
+ connector: shared,
+ metadata: { description: 'x' },
+ });
+ await assertConnectorDeviceBindingAllowed(workspace, {
+ connector: shared,
+ metadata: undefined,
+ });
+ await assertConnectorDeviceBindingAllowed(workspace, {
+ connector: shared,
+ metadata: { boundDeviceId: 'unshared-since' },
+ previous: { metadata: { boundDeviceId: 'unshared-since' }, visibility: 'public' },
+ });
+ // An edit that leaves metadata alone keeps the binding, as does making it private
+ await assertConnectorDeviceBindingAllowed(workspace, {
+ connector: mine,
+ metadata: undefined,
+ previous: { metadata: { boundDeviceId: 'unshared-since' }, visibility: 'public' },
+ });
expect(DeviceModel).not.toHaveBeenCalled();
});
it('refuses a malformed binding', async () => {
await expect(
- assertConnectorDeviceBindingAllowed(personal, { boundDeviceId: 42 }),
+ assertConnectorDeviceBindingAllowed(personal, {
+ connector: shared,
+ metadata: { boundDeviceId: 42 },
+ }),
).rejects.toMatchObject({ code: 'BAD_REQUEST' });
});
});
diff --git a/apps/server/src/routers/lambda/_helpers/connectorDeviceBinding.ts b/apps/server/src/routers/lambda/_helpers/connectorDeviceBinding.ts
index c1b7d0a4860..d6567965d78 100644
--- a/apps/server/src/routers/lambda/_helpers/connectorDeviceBinding.ts
+++ b/apps/server/src/routers/lambda/_helpers/connectorDeviceBinding.ts
@@ -1,4 +1,5 @@
import type { LobeChatDatabase } from '@lobechat/database';
+import type { ConnectorVisibility } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import type { WorkspaceRole } from '@/business/server/trpc-middlewares/workspaceAuth';
@@ -13,50 +14,86 @@ interface DeviceBindingCtx {
workspaceRole?: WorkspaceRole;
}
+/** A connector write, as far as its device binding is concerned. */
+export interface ConnectorBindingWrite {
+ /** The connector after the write: its creator and who it is shared with. */
+ connector: { userId: string; visibility: ConnectorVisibility };
+ /** The metadata the write stores; `undefined` keeps the stored metadata. */
+ metadata: Record<string, unknown> | null | undefined;
+ /** The stored row before the write; absent for a new connector. */
+ previous?: {
+ metadata?: Record<string, unknown> | null;
+ visibility: ConnectorVisibility;
+ };
+}
+
/**
* Whether a connector write may bind the connector to the device its metadata
* names (`metadata.boundDeviceId`). A binding pins every call to that device,
- * so it must be one the connector's every runner can reach:
+ * so it must be one every run that loads the connector can reach. Who runs it
+ * follows the connector's visibility, the same split as connector loading:
*
* - personal connector (no `workspaceId`): one of the caller's personal
* devices — its runs only ever reach the owner's own pool;
- * - workspace connector: a PUBLIC device of that workspace. A private
- * enrollment resolves only for the member who enrolled it, so other
- * members' runs could never reach it.
+ * - shared workspace connector: a PUBLIC device of that workspace. Every
+ * member's runs load it, and a private enrollment resolves only for the
+ * member who enrolled it;
+ * - private workspace connector: a public device of the workspace, or a
+ * private one its creator enrolled. Only the creator's private agents load
+ * it, so the creator's own private device is always reachable.
*
* A binding the write keeps unchanged is not checked again: the device may
* have been unshared since, and an unrelated edit must not fail on it (its
- * calls already fail with the reason).
+ * calls already fail with the reason). Sharing a private connector is the
+ * exception: it hands the kept binding to every member's runs, so the binding
+ * must then pass the shared rule.
*
* Throws `BAD_REQUEST` for a binding outside those devices.
*/
export const assertConnectorDeviceBindingAllowed = async (
ctx: DeviceBindingCtx,
- metadata: Record<string, unknown> | null | undefined,
- previousMetadata?: Record<string, unknown> | null,
+ { connector, metadata, previous }: ConnectorBindingWrite,
): Promise<void> => {
- const deviceId = metadata?.boundDeviceId;
- if (deviceId === undefined || deviceId === previousMetadata?.boundDeviceId) return;
+ const previousDeviceId = previous?.metadata?.boundDeviceId;
+ const deviceId = metadata === undefined ? previousDeviceId : metadata?.boundDeviceId;
+ if (deviceId === undefined) return;
+ const sharing = previous?.visibility === 'private' && connector.visibility !== 'private';
+ if (deviceId === previousDeviceId && !sharing) return;
if (typeof deviceId !== 'string' || !deviceId) {
throw new TRPCError({ code: 'BAD_REQUEST', message: 'Invalid bound device' });
}
- const allowed = ctx.workspaceId
- ? (
- await new DeviceModel(ctx.serverDB, ctx.userId, ctx.workspaceId).findWorkspaceDeviceById(
- deviceId,
- )
- )?.visibility === 'public'
- : !!(await new DeviceModel(ctx.serverDB, ctx.userId).findPersonalByDeviceId(deviceId));
-
- if (!allowed) {
+ if (!ctx.workspaceId) {
+ if (await new DeviceModel(ctx.serverDB, ctx.userId).findPersonalByDeviceId(deviceId)) return;
throw new TRPCError({
code: 'BAD_REQUEST',
- message: ctx.workspaceId
- ? 'A workspace MCP server can only be bound to a shared (public) device of this workspace.'
- : 'An MCP server can only be bound to one of your own devices.',
+ message: 'An MCP server can only be bound to one of your own devices.',
});
}
+
+ // Scoped like every workspace device read: public devices plus the caller's
+ // own private ones
+ const device = await new DeviceModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId,
+ ).findWorkspaceDeviceById(deviceId);
+ const isPrivateConnector = connector.visibility === 'private';
+ if (
+ device?.visibility === 'public' ||
+ (isPrivateConnector && device?.visibility === 'private' && device.userId === connector.userId)
+ ) {
+ return;
+ }
+
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: isPrivateConnector
+ ? 'A private MCP server can only be bound to a shared (public) device of this workspace or to a private device of the member who added it.'
+ : sharing && deviceId === previousDeviceId
+ ? 'This MCP server is bound to a private device, which other members cannot reach. Bind it to a shared (public) device of this workspace, or to Auto, before sharing it.'
+ : 'A workspace MCP server can only be bound to a shared (public) device of this workspace.',
+ });
};
/**
diff --git a/apps/server/src/routers/lambda/_helpers/connectorEditDetail.ts b/apps/server/src/routers/lambda/_helpers/connectorEditDetail.ts
new file mode 100644
index 00000000000..e8ea01e1e97
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/connectorEditDetail.ts
@@ -0,0 +1,17 @@
+import type { DecryptedConnector } from '@/database/models/connector';
+
+/**
+ * A connector as its edit form reads it (and a desktop running a stdio
+ * connector itself). User-set credentials (bearer token, custom headers) stay,
+ * so the form can display them; machine-managed secrets do not:
+ * - `oidcConfig.clientSecret` (the DCR-registered secret) is stripped;
+ * - OAuth tokens are dropped, since the UI only needs to know an OAuth flow is
+ * configured, which `oidcConfig` already shows.
+ */
+export const toConnectorEditDetail = <Tool>(connector: DecryptedConnector, tools: Tool[]) => {
+ const { oidcConfig, credentials, ...rest } = connector;
+ const safeOidcConfig = oidcConfig ? { ...oidcConfig, clientSecret: undefined } : oidcConfig;
+ const safeCredentials = credentials?.type === 'oauth2' ? null : credentials;
+
+ return { ...rest, credentials: safeCredentials, oidcConfig: safeOidcConfig, tools };
+};
diff --git a/apps/server/src/routers/lambda/_helpers/connectorManagePolicy.test.ts b/apps/server/src/routers/lambda/_helpers/connectorManagePolicy.test.ts
index 4c220b12579..b712ae1913e 100644
--- a/apps/server/src/routers/lambda/_helpers/connectorManagePolicy.test.ts
+++ b/apps/server/src/routers/lambda/_helpers/connectorManagePolicy.test.ts
@@ -81,6 +81,27 @@ describe('connectorManagePolicy', () => {
assertConnectorMaintainable(ctxFor('member'), { agentId: 'a1' }),
).resolves.toBeUndefined();
});
+
+ it('keeps a private row to its creator and the workspace owner, whatever the policy', async () => {
+ workspaceMocks.getConnectorMemberManage.mockResolvedValue('admins_only');
+ const privateRow = (userId?: string) => ({ userId, visibility: 'private' as const });
+
+ // The creator maintains (and creates) their own private connector even
+ // when admins restricted the shared ones.
+ await expect(
+ assertConnectorMaintainable(ctxFor('member'), privateRow('me')),
+ ).resolves.toBeUndefined();
+ await expect(
+ assertConnectorMaintainable(ctxFor('member'), privateRow()),
+ ).resolves.toBeUndefined();
+ // An admin does not co-maintain someone else's private connector.
+ await expect(
+ assertConnectorMaintainable(ctxFor('admin'), privateRow('someone-else')),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ await expect(
+ assertConnectorMaintainable(ctxFor('owner'), privateRow('someone-else')),
+ ).resolves.toBeUndefined();
+ });
});
describe('assertConnectorCredentialsManageable', () => {
@@ -103,5 +124,22 @@ describe('connectorManagePolicy', () => {
assertConnectorCredentialsManageable(ctxFor('member'), { userId: 'me' }),
).rejects.toMatchObject({ code: 'FORBIDDEN' });
});
+
+ it("reads a private row's credentials as its creator or the owner only", async () => {
+ workspaceMocks.getConnectorMemberManage.mockResolvedValue('admins_only');
+
+ await expect(
+ assertConnectorCredentialsManageable(ctxFor('member'), {
+ userId: 'me',
+ visibility: 'private',
+ }),
+ ).resolves.toBeUndefined();
+ await expect(
+ assertConnectorCredentialsManageable(ctxFor('admin'), {
+ userId: 'someone-else',
+ visibility: 'private',
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
});
});
diff --git a/apps/server/src/routers/lambda/_helpers/connectorManagePolicy.ts b/apps/server/src/routers/lambda/_helpers/connectorManagePolicy.ts
index 4dd74ff3aeb..40c94d58ba8 100644
--- a/apps/server/src/routers/lambda/_helpers/connectorManagePolicy.ts
+++ b/apps/server/src/routers/lambda/_helpers/connectorManagePolicy.ts
@@ -1,4 +1,4 @@
-import type { WorkspaceConnectorMemberManage } from '@lobechat/types';
+import type { ConnectorVisibility, WorkspaceConnectorMemberManage } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { WorkspaceModel } from '@/database/models/workspace';
@@ -17,8 +17,13 @@ interface ConnectorManageCtx {
interface ConnectorRowRef {
agentId?: string | null;
userId?: string | null;
+ /** A new row's requested visibility, or the existing row's. */
+ visibility?: ConnectorVisibility | null;
}
+/** A member's own connector (私人): never co-maintained, whatever the policy says. */
+const isPrivateRow = (row?: ConnectorRowRef) => row?.visibility === 'private';
+
export const isWorkspaceConnectorAdmin = (
ctx: Pick<ConnectorManageCtx, 'workspaceId' | 'workspaceRole'>,
) => ctx.workspaceRole === 'owner' || ctx.workspaceRole === 'admin';
@@ -52,7 +57,9 @@ const forbidden = () =>
* Gate a maintenance write (connect, re-authorize, edit, sync, remove) on a
* workspace connector by the workspace's member policy. Shared rows are
* co-maintained, so the creator does not matter here; agent-scoped rows belong
- * to their agent's setup and keep the creator-or-owner rule.
+ * to their agent's setup and keep the creator-or-owner rule. A private row is
+ * its creator's own: the member policy (which governs the shared connectors)
+ * does not apply, and only the creator or the workspace owner may touch it.
*/
export const assertConnectorMaintainable = async (
ctx: ConnectorManageCtx,
@@ -64,6 +71,11 @@ export const assertConnectorMaintainable = async (
if (row.userId) assertWorkspaceRowManageable(ctx, row.userId, 'connector');
return;
}
+ if (isPrivateRow(row)) {
+ // A new private row is created by the caller, who owns it.
+ assertWorkspaceRowManageable(ctx, row?.userId ?? ctx.userId, 'connector');
+ return;
+ }
if (!(await canManageWorkspaceConnectors(ctx))) throw forbidden();
};
@@ -78,6 +90,8 @@ export const assertConnectorCredentialsManageable = async (
row: ConnectorRowRef,
): Promise<void> => {
if (!ctx.workspaceId) return;
- if (!row.agentId && !(await canManageWorkspaceConnectors(ctx))) throw forbidden();
+ if (!row.agentId && !isPrivateRow(row) && !(await canManageWorkspaceConnectors(ctx))) {
+ throw forbidden();
+ }
assertWorkspaceRowManageable(ctx, row.userId, 'connector');
};
diff --git a/apps/server/src/routers/lambda/_helpers/connectorVisibility.ts b/apps/server/src/routers/lambda/_helpers/connectorVisibility.ts
new file mode 100644
index 00000000000..f70e7728a44
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/connectorVisibility.ts
@@ -0,0 +1,158 @@
+import type { ConnectorVisibility } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+
+import type { AgentModel } from '@/database/models/agent';
+import type { ConnectorModel } from '@/database/models/connector';
+
+import { canManageWorkspaceConnectors } from './connectorManagePolicy';
+
+export interface ConnectorWriteCtx {
+ agentModel: AgentModel;
+ userId: string;
+ workspaceId?: string | null;
+}
+
+/**
+ * The visibility a base connector is written with: only a workspace row can be
+ * private; personal rows are implicitly their owner's.
+ */
+export const resolveWriteVisibility = (
+ ctx: Pick<ConnectorWriteCtx, 'workspaceId'>,
+ requested: ConnectorVisibility | undefined,
+): ConnectorVisibility => (ctx.workspaceId && requested === 'private' ? 'private' : 'public');
+
+/**
+ * A private connector serves only its creator's private agents. Binding,
+ * copying or mounting it onto a workspace agent would hand the creator's
+ * credentials to every member who runs that agent, so it is refused.
+ */
+export const assertPrivateConnectorTarget = async (
+ ctx: ConnectorWriteCtx,
+ connector: { userId: string; visibility: ConnectorVisibility },
+ agentId: string,
+): Promise<void> => {
+ if (!ctx.workspaceId || connector.visibility !== 'private') return;
+ if (
+ connector.userId !== ctx.userId ||
+ (await ctx.agentModel.getAgentVisibility(agentId)) !== 'private'
+ ) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'A private connector can only be used by your own private agents',
+ });
+ }
+};
+
+/**
+ * Validate a visibility change on an existing workspace connector and return
+ * the new value, or `undefined` when nothing changes.
+ *
+ * - Only the creator decides: making it private takes it away from every
+ * other member, making it shared hands the creator's credentials to them.
+ * - A Composio account runs as the member who linked it, so only that member
+ * makes it private; likewise every OAuth account (`link.userId`) the row holds
+ * must be the caller's own. A row can hold someone else's account (a teammate's
+ * legacy connection migrated into a row by whoever opened it first, an
+ * owner's reconnect): making it private would keep that account to the
+ * creator and take it from its own linker and the rest of the workspace.
+ * - Sharing it follows the member policy for shared connectors.
+ * - Agent-scoped rows follow their agent and are not switched here; a base row
+ * mounted on an agent goes private only while that agent is the caller's
+ * own private agent.
+ * - At most one shared row and one private row per member per identifier.
+ */
+export const resolveVisibilityChange = async (
+ ctx: ConnectorWriteCtx &
+ Parameters<typeof canManageWorkspaceConnectors>[0] & { connectorModel: ConnectorModel },
+ target: {
+ agentId: string | null;
+ id: string;
+ identifier: string;
+ metadata?: {
+ composio?: { connectedAccountId?: string; linkedByUserId?: string };
+ mountedByAgentId?: string;
+ } | null;
+ userId: string;
+ visibility: ConnectorVisibility;
+ },
+ requested: ConnectorVisibility | undefined,
+): Promise<ConnectorVisibility | undefined> => {
+ if (!ctx.workspaceId || !requested || requested === target.visibility) return undefined;
+ if (target.agentId) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: "An agent's connector follows its agent; change the agent instead",
+ });
+ }
+ if (target.userId !== ctx.userId) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Only the member who added this connector can change who it is shared with',
+ });
+ }
+ const composio = target.metadata?.composio;
+ if (
+ requested === 'private' &&
+ composio?.connectedAccountId &&
+ (composio.linkedByUserId ?? target.userId) !== ctx.userId
+ ) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message:
+ 'This connection was authorized by another member. Reconnect it with your own account to make it private',
+ });
+ }
+ // An OAuth account runs as the member who authorized it (`link.userId`):
+ // made private, a teammate's account would serve only the creator's private
+ // agents, and the teammate could no longer see or remove it
+ if (
+ requested === 'private' &&
+ (await ctx.connectorModel.getLinkModel().listByConnectorIds([target.id])).some(
+ (link) => link.userId !== ctx.userId,
+ )
+ ) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message:
+ 'This connector holds an account another member authorized. Remove that account, or reconnect with your own, to make it private',
+ });
+ }
+ // A mounted row serves its agent: made private, a shared agent's runs (or a
+ // teammate's private agent's) leave it out, and the tool configured on that
+ // agent quietly disappears or falls to a same-identifier shared connector.
+ const mountedBy = target.metadata?.mountedByAgentId;
+ if (
+ requested === 'private' &&
+ mountedBy &&
+ (!(await ctx.agentModel.existsOwnedById(mountedBy)) ||
+ (await ctx.agentModel.getAgentVisibility(mountedBy)) !== 'private')
+ ) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message:
+ 'This connector is mounted on an agent other members use. Unmount it from that agent before making it private',
+ });
+ }
+ if (requested === 'public' && !(await canManageWorkspaceConnectors(ctx))) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Only workspace owners and admins can share connectors in this workspace',
+ });
+ }
+ const clash = await ctx.connectorModel.findScopedByIdentifier(
+ target.identifier,
+ undefined,
+ undefined,
+ requested,
+ );
+ if (clash && clash.id !== target.id) {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message:
+ requested === 'public'
+ ? `The workspace already shares a "${target.identifier}" connector`
+ : `You already have a private "${target.identifier}" connector`,
+ });
+ }
+ return requested;
+};
diff --git a/apps/server/src/routers/lambda/_helpers/upsertConnectorEntry.test.ts b/apps/server/src/routers/lambda/_helpers/upsertConnectorEntry.test.ts
new file mode 100644
index 00000000000..f7409ad038a
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/upsertConnectorEntry.test.ts
@@ -0,0 +1,136 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { and, eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { ConnectorModel } from '@/database/models/connector';
+import { userConnectors, users, workspaces } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { upsertConnectorEntry } from './upsertConnectorEntry';
+
+const owner = 'uce-owner';
+const mate = 'uce-mate';
+const workspaceId = 'uce-ws';
+
+const gmailAccount = {
+ appSlug: 'GMAIL',
+ authConfigId: 'ac-gmail',
+ connectedAccountId: 'ca-owner-gmail',
+ status: 'ACTIVE',
+};
+
+let serverDB: LobeChatDatabase;
+
+/** A detail-panel refresh of the Gmail plugin projection, as `syncPluginTools` sends it. */
+const syncGmail = (userId: string) =>
+ upsertConnectorEntry(
+ {
+ connectorModel: new ConnectorModel(serverDB, userId, workspaceId),
+ serverDB,
+ userId,
+ workspaceId,
+ workspaceRole: 'member',
+ },
+ {
+ composio: gmailAccount,
+ description: 'Gmail tools',
+ identifier: 'gmail',
+ name: 'Gmail',
+ sourceType: 'marketplace',
+ },
+ );
+
+const gmailRows = () =>
+ serverDB
+ .select({ id: userConnectors.id, metadata: userConnectors.metadata })
+ .from(userConnectors)
+ .where(
+ and(eq(userConnectors.workspaceId, workspaceId), eq(userConnectors.identifier, 'gmail')),
+ );
+
+beforeEach(async () => {
+ serverDB = await getTestDB();
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: owner }, { id: mate }]);
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'WS', primaryOwnerId: owner, slug: 'uce-ws' });
+ // The owner's Composio Gmail connector, switched to private
+ await serverDB.insert(userConnectors).values({
+ identifier: 'gmail',
+ metadata: { composio: gmailAccount },
+ name: 'Gmail',
+ sourceType: 'marketplace',
+ status: 'connected',
+ userId: owner,
+ visibility: 'private',
+ workspaceId,
+ });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('upsertConnectorEntry with a private connector', () => {
+ it('refreshes the owner’s private row instead of creating a shared one', async () => {
+ // Regression: the lookup saw shared rows only, so the refresh created an
+ // enabled shared Gmail row holding the private account.
+ const [privateRow] = await gmailRows();
+
+ expect(await syncGmail(owner)).toEqual({ connectorId: privateRow.id, writable: true });
+ expect(await gmailRows()).toEqual([
+ { id: privateRow.id, metadata: { composio: gmailAccount, description: 'Gmail tools' } },
+ ]);
+ });
+
+ it('creates nothing for a teammate reading the private account off the projection', async () => {
+ expect(await syncGmail(mate)).toEqual({ connectorId: null, writable: false });
+ expect(await gmailRows()).toHaveLength(1);
+ });
+
+ it('never stamps the projection’s linker onto a private row naming the same account', async () => {
+ // A member writes a teammate's legacy account id (readable off the
+ // projection) into their own private row's metadata. The detail-panel sync
+ // must not then copy in the projection's attribution, or the row passes
+ // for the teammate's connection and hides it from the workspace.
+ const linker = 'uce-legacy-linker';
+ const legacy = { ...gmailAccount, connectedAccountId: 'ca-legacy', linkedByUserId: linker };
+ const [forged] = await serverDB
+ .insert(userConnectors)
+ .values({
+ identifier: 'gmail',
+ metadata: { composio: { connectedAccountId: 'ca-legacy' } },
+ name: 'Gmail',
+ sourceType: 'custom',
+ status: 'connected',
+ userId: mate,
+ visibility: 'private',
+ workspaceId,
+ })
+ .returning();
+
+ await upsertConnectorEntry(
+ {
+ connectorModel: new ConnectorModel(serverDB, mate, workspaceId),
+ serverDB,
+ userId: mate,
+ workspaceId,
+ workspaceRole: 'member',
+ },
+ { composio: legacy, identifier: 'gmail', name: 'Gmail', sourceType: 'marketplace' },
+ );
+
+ const [row] = await serverDB
+ .select({ metadata: userConnectors.metadata })
+ .from(userConnectors)
+ .where(eq(userConnectors.id, forged.id));
+ expect(row.metadata?.composio).toEqual({ connectedAccountId: 'ca-legacy' });
+ expect(
+ await new ConnectorModel(serverDB, mate, workspaceId).pickLegacyComposioMirrors([
+ { connectedAccountId: 'ca-legacy', identifier: 'gmail', ownerUserId: linker },
+ ]),
+ ).toHaveLength(1);
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/upsertConnectorEntry.ts b/apps/server/src/routers/lambda/_helpers/upsertConnectorEntry.ts
index 3c9582b5981..faf1ca4a0cd 100644
--- a/apps/server/src/routers/lambda/_helpers/upsertConnectorEntry.ts
+++ b/apps/server/src/routers/lambda/_helpers/upsertConnectorEntry.ts
@@ -15,6 +15,14 @@ import { isWorkspaceNonOwner } from './assertWorkspaceRowManageable';
* panel, so an existing row created by someone else must not be rewritten by a
* non-owner caller — the row is returned read-only (`writable: false`) and the
* caller skips the tool upsert instead of throwing, keeping browsing intact.
+ *
+ * The row is the caller's own in any visibility, so a connector switched to
+ * private is refreshed in place rather than shadowed by a new shared row that
+ * republishes its account to the workspace. The workspace-wide plugin
+ * projection can still carry the Composio account of a teammate's private
+ * connector: that account is never copied onto a row the caller sees, and no
+ * row is created for it (`connectorId: null`). Nor is the projection's account
+ * copied onto a private row: only display fields are refreshed there.
*/
export async function upsertConnectorEntry(
ctx: {
@@ -32,11 +40,10 @@ export async function upsertConnectorEntry(
name: string;
sourceType: string;
},
-): Promise<{ connectorId: string; writable: boolean }> {
+): Promise<{ connectorId: string; writable: boolean } | { connectorId: null; writable: false }> {
const metadata: ConnectorMetadata = {};
if (params.description) metadata.description = params.description;
if (params.avatar) metadata.avatar = params.avatar;
- if (params.composio) metadata.composio = params.composio;
// Viewers keep browse access: they resolve existing rows read-only below,
// but must never create or rewrite connector state. These bootstrap
@@ -54,18 +61,41 @@ export async function upsertConnectorEntry(
workspaceId: ctx.workspaceId,
});
- const refresh = async (row: Pick<DecryptedConnector, 'id' | 'metadata' | 'userId'>) => {
- const writable = canWrite && (!isWorkspaceNonOwner(ctx) || row.userId === ctx.userId);
+ const accountId = params.composio?.connectedAccountId;
+ const row = await ctx.connectorModel.findManageableByIdentifier(
+ params.identifier,
+ undefined,
+ accountId,
+ );
+ const accountIsTeammatePrivate =
+ !!accountId &&
+ row?.metadata?.composio?.connectedAccountId !== accountId &&
+ (await ctx.connectorModel.isComposioAccountPrivateToTeammate(accountId));
+ // The projection is workspace-wide, so it is no source of truth for a
+ // private row's account: copying its block (with the linker it attributes
+ // the account to) onto a private row whose metadata merely names the same
+ // account id would make the row pass for that member's connection, hiding
+ // the legacy connection from everyone else. A private row's account is
+ // written by its own OAuth connect path only.
+ if (params.composio && !accountIsTeammatePrivate && row?.visibility !== 'private') {
+ metadata.composio = params.composio;
+ }
+
+ const refresh = async (target: Pick<DecryptedConnector, 'id' | 'metadata' | 'userId'>) => {
+ const writable = canWrite && (!isWorkspaceNonOwner(ctx) || target.userId === ctx.userId);
if (writable) {
// Preserve runtime-owned metadata (especially Composio account identity)
// while refreshing display fields from the latest plugin manifest.
- await ctx.connectorModel.update(row.id, { metadata: { ...row.metadata, ...metadata } });
+ await ctx.connectorModel.update(target.id, {
+ metadata: { ...target.metadata, ...metadata },
+ });
}
- return { connectorId: row.id, writable };
+ return { connectorId: target.id, writable };
};
- const [existing] = await ctx.connectorModel.queryByIdentifiers([params.identifier]);
- if (existing) return refresh(existing);
+ if (row) return refresh(row);
+
+ if (accountIsTeammatePrivate) return { connectorId: null, writable: false };
if (!canWrite) {
throw new TRPCError({ code: 'FORBIDDEN', message: 'Viewers cannot install connectors' });
diff --git a/apps/server/src/routers/lambda/agent/visibility.ts b/apps/server/src/routers/lambda/agent/visibility.ts
index a4f59dff2e5..ed60aa796bd 100644
--- a/apps/server/src/routers/lambda/agent/visibility.ts
+++ b/apps/server/src/routers/lambda/agent/visibility.ts
@@ -4,10 +4,12 @@ import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { ChatGroupModel } from '@/database/models/chatGroup';
+import { ConnectorModel } from '@/database/models/connector';
import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import { TaskModel } from '@/database/models/task';
import type { ResourceAccessLevel } from '@/database/schemas';
import { DEFAULT_RESOURCE_ACCESS_LEVELS, RESOURCE_ACCESS_LEVELS_BY_TYPE } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
import { router } from '@/libs/trpc/lambda';
import {
assertCanPerformResourceAction,
@@ -17,6 +19,31 @@ import {
import { releasePrivatePin } from '../_helpers/sidebarPin';
import { agentProcedure } from './procedures';
+/**
+ * A private connector serves only its creator's private agents, and a shared
+ * agent's runs leave it out. Publishing an agent that still uses one would
+ * drop its configured tool for everyone, or silently answer it with a shared
+ * connector of the same identifier running another account. Both publish
+ * paths guard it, as group publishing guards private member agents.
+ */
+const assertNoPrivateConnectorBindings = async (
+ ctx: { serverDB: LobeChatDatabase; userId: string; workspaceId?: string | null },
+ agentId: string,
+) => {
+ if (!ctx.workspaceId) return;
+ const bindings = await new ConnectorModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId,
+ ).countPrivateAgentBindings(agentId);
+ if (bindings > 0)
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message:
+ 'Cannot publish an agent that still uses private connectors. Remove them from the agent or share them with the workspace first.',
+ });
+};
+
export const visibilityRouter = router({
/**
* Publish a private agent into the workspace. Only the creator of a
@@ -33,6 +60,7 @@ export const visibilityRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ await assertNoPrivateConnectorBindings(ctx, input.id);
// Hand a private pin to the creator's personal list BEFORE the row goes
// public: done afterwards, a failure in between would leave a public
// pinned row — a team pin no owner/admin chose.
@@ -173,6 +201,8 @@ export const visibilityRouter = router({
}
}
+ if (input.visibility === 'public') await assertNoPrivateConnectorBindings(ctx, input.id);
+
// Before the row turns public, so a failure never leaves a team pin
// nobody with the role set (see `publishAgentToWorkspace`).
if (input.visibility === 'public' && meta.pinned) {
diff --git a/apps/server/src/routers/lambda/composio.configuration.test.ts b/apps/server/src/routers/lambda/composio.configuration.test.ts
index 6925c410c55..59e54def403 100644
--- a/apps/server/src/routers/lambda/composio.configuration.test.ts
+++ b/apps/server/src/routers/lambda/composio.configuration.test.ts
@@ -52,6 +52,34 @@ describe('composioRouter without a configured API key', () => {
expect(PluginModel).toHaveBeenCalledWith(expect.anything(), userId, workspaceId);
});
+ it("withholds a pending connection's hosted link from everyone but its linker", async () => {
+ // Regression: any member could read a teammate's (private) pending link from
+ // the workspace-wide projection and bind their own account to it.
+ const pending = (linkedByUserId: string) => ({
+ customParams: {
+ composio: {
+ connectedAccountId: `acc-${linkedByUserId}`,
+ linkedByUserId,
+ redirectUrl: `https://composio.dev/link/${linkedByUserId}`,
+ status: 'PENDING',
+ },
+ },
+ identifier: 'gmail',
+ });
+ mocks.pluginQuery.mockResolvedValue([pending('me'), pending('mate')]);
+
+ const plugins = await callerFor('me', 'workspace-1').getComposioPlugins();
+ // A teammate's private connection is never listed to the client
+ expect(mocks.pluginQuery).toHaveBeenCalledWith({ forClient: true });
+
+ expect(plugins[0].customParams?.composio?.redirectUrl).toBe('https://composio.dev/link/me');
+ expect(plugins[1].customParams?.composio).toEqual({
+ connectedAccountId: 'acc-mate',
+ linkedByUserId: 'mate',
+ status: 'PENDING',
+ });
+ });
+
it('still rejects unauthenticated plugin listing before reading the database', async () => {
await expect(callerFor().getComposioPlugins()).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
expect(mocks.pluginQuery).not.toHaveBeenCalled();
diff --git a/apps/server/src/routers/lambda/composio.test.ts b/apps/server/src/routers/lambda/composio.test.ts
index c5043fefa16..4fceab229cd 100644
--- a/apps/server/src/routers/lambda/composio.test.ts
+++ b/apps/server/src/routers/lambda/composio.test.ts
@@ -14,7 +14,9 @@ const mocks = vi.hoisted(() => ({
connectorCreate: vi.fn(),
connectorCreateUnlessIdentifierHeld: vi.fn(),
connectorDelete: vi.fn(),
+ connectorFindManageableByIdentifier: vi.fn(),
connectorFindScopedByIdentifier: vi.fn(),
+ connectorQueryComposioAccountHolders: vi.fn(),
connectorToolDeleteToolsNotIn: vi.fn(),
connectorToolUpsertMany: vi.fn(),
connectorUpdate: vi.fn(),
@@ -25,6 +27,7 @@ const mocks = vi.hoisted(() => ({
pluginCreate: vi.fn(),
pluginDelete: vi.fn(),
pluginFindById: vi.fn(),
+ pluginQueryComposioMirrors: vi.fn(),
pluginUpdate: vi.fn(),
}));
@@ -38,8 +41,9 @@ vi.mock('@/database/models/plugin', () => ({
PluginModel: vi.fn().mockImplementation(function () {
return {
create: mocks.pluginCreate,
- delete: mocks.pluginDelete,
+ deleteComposioProjectionKeepingPrivate: mocks.pluginDelete,
findById: mocks.pluginFindById,
+ queryComposioMirrors: mocks.pluginQueryComposioMirrors,
update: mocks.pluginUpdate,
};
}),
@@ -51,7 +55,9 @@ vi.mock('@/database/models/connector', () => ({
create: mocks.connectorCreate,
createUnlessIdentifierHeld: mocks.connectorCreateUnlessIdentifierHeld,
delete: mocks.connectorDelete,
+ findManageableByIdentifier: mocks.connectorFindManageableByIdentifier,
findScopedByIdentifier: mocks.connectorFindScopedByIdentifier,
+ queryComposioAccountHolders: mocks.connectorQueryComposioAccountHolders,
update: mocks.connectorUpdate,
};
}),
@@ -83,10 +89,24 @@ const caller = () => composioRouter.createCaller({ userId: 'user-1' } as any);
beforeEach(() => {
vi.clearAllMocks();
- mocks.connectorFindScopedByIdentifier.mockResolvedValue(null);
+ mocks.connectorFindManageableByIdentifier.mockResolvedValue(null);
mocks.connectorCreate.mockResolvedValue({ id: 'conn-new' });
mocks.connectorCreateUnlessIdentifierHeld.mockResolvedValue({ created: { id: 'conn-new' } });
mocks.pluginFindById.mockResolvedValue(undefined);
+ mocks.pluginQueryComposioMirrors.mockResolvedValue([]);
+ // By default the account a write names is held by the row the write resolves
+ // (the implementation is read without recording a lookup call).
+ mocks.connectorQueryComposioAccountHolders.mockImplementation(async () => {
+ const row = await mocks.connectorFindManageableByIdentifier.getMockImplementation()?.();
+ return row ? [{ agentId: null, userId: 'user-1', visibility: 'public', ...row }] : [];
+ });
+});
+
+/** The plugin projection row of a legacy connection, which no connector row runs. */
+const legacyMirror = (connectedAccountId: string) => ({
+ customParams: { composio: { connectedAccountId } },
+ identifier: 'gmail',
+ userId: 'user-1',
});
/** @example OAuth callback polling reports whether Gmail can be read. */
@@ -184,7 +204,9 @@ describe('composioRouter.updateComposioPlugin dual-write', () => {
};
it('creates the connector projection (ACTIVE) + tools when none exists', async () => {
- mocks.connectorFindScopedByIdentifier.mockResolvedValue(null);
+ // A legacy connection: only the plugin projection holds the account.
+ mocks.connectorFindManageableByIdentifier.mockResolvedValue(null);
+ mocks.pluginQueryComposioMirrors.mockResolvedValue([legacyMirror('ca-1')]);
const res = await caller().updateComposioPlugin(input);
@@ -201,8 +223,45 @@ describe('composioRouter.updateComposioPlugin dual-write', () => {
expect(mocks.connectorToolDeleteToolsNotIn).toHaveBeenCalledWith('conn-new', ['GMAIL_SEND']);
});
+ it('updates the private row a connector was switched to, instead of republishing it', async () => {
+ // A refresh resolves the caller's own row in either visibility; missing the
+ // private one would create a second, public row for the same account.
+ mocks.connectorFindManageableByIdentifier.mockResolvedValue({
+ agentId: null,
+ id: 'conn-private',
+ metadata: { composio: { connectedAccountId: 'ca-1' } },
+ userId: 'user-1',
+ visibility: 'private',
+ });
+
+ await caller().updateComposioPlugin(input);
+
+ expect(mocks.connectorCreate).not.toHaveBeenCalled();
+ expect(mocks.connectorUpdate).toHaveBeenCalledWith(
+ 'conn-private',
+ expect.objectContaining({ status: 'connected' }),
+ );
+ });
+
+ it('updates the row holding the refreshed account, resolved once', async () => {
+ // Refreshing the shared account must not overwrite the caller's private
+ // connection of the same app: the account picks the row, and the policy
+ // check and the update use that same row.
+ mocks.connectorFindManageableByIdentifier.mockResolvedValue({ id: 'conn-shared' });
+
+ await caller().updateComposioPlugin(input);
+
+ expect(mocks.connectorFindManageableByIdentifier).toHaveBeenCalledTimes(1);
+ expect(mocks.connectorFindManageableByIdentifier).toHaveBeenCalledWith(
+ 'gmail',
+ undefined,
+ 'ca-1',
+ );
+ expect(mocks.connectorUpdate).toHaveBeenCalledWith('conn-shared', expect.anything());
+ });
+
it('updates an existing connector projection instead of duplicating it', async () => {
- mocks.connectorFindScopedByIdentifier.mockResolvedValue({ id: 'conn-existing' });
+ mocks.connectorFindManageableByIdentifier.mockResolvedValue({ id: 'conn-existing' });
await caller().updateComposioPlugin(input);
@@ -223,7 +282,7 @@ describe('composioRouter.updateComposioPlugin dual-write', () => {
});
it('prunes all connector tools when the refreshed list is empty', async () => {
- mocks.connectorFindScopedByIdentifier.mockResolvedValue({ id: 'conn-existing' });
+ mocks.connectorFindManageableByIdentifier.mockResolvedValue({ id: 'conn-existing' });
await caller().updateComposioPlugin({ ...input, tools: [] });
@@ -235,7 +294,7 @@ describe('composioRouter.updateComposioPlugin dual-write', () => {
describe('composioRouter delete paths clean up the connector projection', () => {
it('removeComposioPlugin deletes the connector row when present', async () => {
- mocks.connectorFindScopedByIdentifier.mockResolvedValue({ id: 'conn-existing' });
+ mocks.connectorFindManageableByIdentifier.mockResolvedValue({ id: 'conn-existing' });
await caller().removeComposioPlugin({ identifier: 'gmail' });
@@ -245,7 +304,7 @@ describe('composioRouter delete paths clean up the connector projection', () =>
it('deleteConnection deletes both plugin and connector', async () => {
mocks.connectedAccountsDelete.mockResolvedValue(undefined);
- mocks.connectorFindScopedByIdentifier.mockResolvedValue({ id: 'conn-existing' });
+ mocks.connectorFindManageableByIdentifier.mockResolvedValue({ id: 'conn-existing' });
await caller().deleteConnection({ connectedAccountId: 'ca-1', identifier: 'gmail' });
@@ -253,8 +312,61 @@ describe('composioRouter delete paths clean up the connector projection', () =>
expect(mocks.connectorDelete).toHaveBeenCalledWith('conn-existing');
});
+ it('deleteConnection removes the row holding the account it deletes', async () => {
+ // Regression: the row was looked up by identifier alone, so with a private
+ // and a shared connection of the same app, deleting the shared account
+ // removed the caller's private row and left the shared one pointing at a
+ // deleted account.
+ mocks.connectedAccountsDelete.mockResolvedValue(undefined);
+ mocks.connectorFindManageableByIdentifier.mockResolvedValue({ id: 'conn-shared' });
+
+ await caller().deleteConnection({ connectedAccountId: 'ca-shared', identifier: 'gmail' });
+
+ expect(mocks.connectorFindManageableByIdentifier).toHaveBeenCalledTimes(1);
+ expect(mocks.connectorFindManageableByIdentifier).toHaveBeenCalledWith(
+ 'gmail',
+ undefined,
+ 'ca-shared',
+ );
+ expect(mocks.connectedAccountsDelete).toHaveBeenCalledWith('ca-shared');
+ expect(mocks.connectorDelete).toHaveBeenCalledWith('conn-shared');
+ });
+
+ it('deleteConnection removes a legacy connection the plugin projection holds', async () => {
+ mocks.pluginQueryComposioMirrors.mockResolvedValue([legacyMirror('ca-legacy')]);
+
+ await caller().deleteConnection({ connectedAccountId: 'ca-legacy', identifier: 'gmail' });
+
+ expect(mocks.pluginQueryComposioMirrors).toHaveBeenCalledWith(['gmail']);
+ expect(mocks.connectedAccountsDelete).toHaveBeenCalledWith('ca-legacy');
+ expect(mocks.pluginDelete).toHaveBeenCalledWith('gmail');
+ });
+
+ it('deleteConnection refuses an account that is none of the connection’s', async () => {
+ // The Composio client deletes by account id alone: an account neither a
+ // connector row nor the app's plugin projection holds is not the caller's
+ // to delete, nor is one another connector runs.
+ mocks.pluginQueryComposioMirrors.mockResolvedValue([legacyMirror('ca-legacy')]);
+
+ await expect(
+ caller().deleteConnection({ connectedAccountId: 'ca-elsewhere', identifier: 'gmail' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+
+ mocks.connectorFindManageableByIdentifier.mockResolvedValue({ id: 'conn-gmail' });
+ mocks.connectorQueryComposioAccountHolders.mockResolvedValue([
+ { agentId: null, id: 'conn-github', identifier: 'github', userId: 'user-1' },
+ ]);
+ await expect(
+ caller().deleteConnection({ connectedAccountId: 'ca-github', identifier: 'gmail' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ expect(mocks.connectedAccountsDelete).not.toHaveBeenCalled();
+ expect(mocks.pluginDelete).not.toHaveBeenCalled();
+ expect(mocks.connectorDelete).not.toHaveBeenCalled();
+ });
+
it('does not call connector delete when no projection exists', async () => {
- mocks.connectorFindScopedByIdentifier.mockResolvedValue(null);
+ mocks.connectorFindManageableByIdentifier.mockResolvedValue(null);
await caller().removeComposioPlugin({ identifier: 'gmail' });
diff --git a/apps/server/src/routers/lambda/composio.ts b/apps/server/src/routers/lambda/composio.ts
index e23716537fb..aa5f826c513 100644
--- a/apps/server/src/routers/lambda/composio.ts
+++ b/apps/server/src/routers/lambda/composio.ts
@@ -25,6 +25,11 @@ import { inferCrudType } from '@/libs/mcp/utils';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { findComposioAccountConflict } from './_helpers/composioAccountBinding';
+import {
+ redactForeignComposioLinks,
+ removeComposioProjection,
+} from './_helpers/composioProjection';
import { assertConnectorMaintainable } from './_helpers/connectorManagePolicy';
const composioDbProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
@@ -54,31 +59,77 @@ const composioProcedure = composioDbProcedure.use(async (opts) =>
// Writes: in a workspace, require at least the member role (blocks viewers).
// Personal mode passes through. The workspace connector policy is layered on
-// top per-mutation via `assertComposioRowManageable` (mirrors the native
+// top per-mutation via `resolveComposioWriteTarget` (mirrors the native
// connector router's connectorWriteProcedure + assertConnectorMaintainable).
const composioWriteProcedure = composioProcedure.use(requireWorkspaceRoleWhenScoped('member'));
+interface ComposioWriteRef {
+ agentId?: string;
+ /** The Composio account the write is about, when it already exists. */
+ connectedAccountId?: string;
+ identifier: string;
+}
+
+/** The connector row a Composio write updates or removes; null when it creates one. */
+type ComposioWriteTarget = Awaited<ReturnType<ConnectorModel['findManageableByIdentifier']>>;
+
/**
- * Before connecting, re-authorizing or removing a Composio connection in a
- * workspace, assert the caller may maintain it under the workspace connector
- * policy (members co-maintain shared rows unless an admin restricted it;
- * agent-scoped rows keep the creator-or-owner rule). Checked BEFORE any
- * external side effect (Composio account link/delete). No-op in personal mode.
+ * Resolve the connector row a Composio write touches, and assert the caller may
+ * maintain it under the workspace connector policy (members co-maintain shared
+ * rows unless an admin restricted it; private and agent-scoped rows keep the
+ * creator-or-owner rule). The write then mutates exactly this row, so the
+ * check and the change can never land on two different rows.
+ *
+ * `connectedAccountId` (refresh, removal) picks the row holding that account:
+ * a member with a private connection may also see a shared one of the same
+ * identifier, and Settings lists the shared account from the plugin projection.
+ * Without it (a new connection) the caller's own private row wins over the
+ * shared one; checking the shared row instead would let `admins_only` block a
+ * member from reconnecting a connector that is theirs alone.
+ *
+ * The account itself is then bound to that row by id, not by the identifier
+ * the request names ({@link findComposioAccountConflict}): the remote delete
+ * acts on the account id alone, so a write naming a teammate's private
+ * account, or an account another connector runs, is refused.
+ *
+ * Checked BEFORE any external side effect (Composio account link/delete). The
+ * policy is a no-op in personal mode.
*/
-async function assertComposioRowManageable(
+async function resolveComposioWriteTarget(
ctx: {
connectorModel: ConnectorModel;
+ pluginModel: PluginModel;
serverDB: LobeChatDatabase;
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);
- await assertConnectorMaintainable(ctx, { agentId, userId: existing?.userId });
+ { agentId, connectedAccountId, identifier }: ComposioWriteRef,
+): Promise<ComposioWriteTarget> {
+ const target = await ctx.connectorModel.findManageableByIdentifier(
+ identifier,
+ agentId,
+ connectedAccountId,
+ );
+
+ if (connectedAccountId) {
+ // Only a base connection has a legacy plugin projection to act on.
+ const conflict = await findComposioAccountConflict(
+ ctx,
+ target,
+ connectedAccountId,
+ agentId ? undefined : () => ctx.pluginModel.queryComposioMirrors([identifier]),
+ );
+ if (conflict) throw conflict;
+ }
+ if (!ctx.workspaceId) return target;
+
+ await assertConnectorMaintainable(ctx, {
+ agentId,
+ userId: target?.userId,
+ visibility: target?.visibility,
+ });
+ return target;
}
type ComposioToolInput = {
@@ -123,6 +174,8 @@ async function upsertComposioConnector(
*/
agentId?: string;
composio: ComposioConnectorMetadata;
+ /** The row {@link resolveComposioWriteTarget} authorized; null creates one. */
+ existing: ComposioWriteTarget;
identifier: string;
label: string;
/**
@@ -151,14 +204,17 @@ async function upsertComposioConnector(
: ConnectorStatus.disconnected;
// Exact-scope idempotency: an agent connection updates/creates the agent's own
- // row, a personal connection the base row — never crossing scopes.
+ // row, a personal connection the base row — never crossing scopes. The row is
+ // found in any visibility: a connector switched to private must still be
+ // updated here, or the upsert would create a second, public row for the same
+ // account and republish the private connection to the workspace.
+ const { existing } = params;
const fields = {
metadata,
name: params.label,
sourceType: ConnectorSourceType.marketplace,
status,
};
- const existing = await connectorModel.findScopedByIdentifier(params.identifier, params.agentId);
let connectorId: string;
if (existing) {
await connectorModel.update(existing.id, fields);
@@ -197,16 +253,6 @@ async function upsertComposioConnector(
}
}
-/** Remove the connector projection for a Composio identifier (tools cascade). */
-async function deleteComposioConnector(
- connectorModel: ConnectorModel,
- identifier: string,
- agentId?: string,
-): Promise<void> {
- const existing = await connectorModel.findScopedByIdentifier(identifier, agentId);
- if (existing) await connectorModel.delete(existing.id);
-}
-
/**
* Guard: the caller must OWN (have created) the agent before a Composio account
* is bound to it. Uses `existsOwnedById` (creator-only) rather than the
@@ -234,10 +280,18 @@ export const composioRouter = router({
appSlug: z.string(),
identifier: z.string(),
label: z.string(),
+ /**
+ * Re-authorize the connection running this account, in place: the row
+ * holding it keeps its identity and visibility, and the stale account
+ * goes before the new one is linked. Removing the row first instead
+ * would recreate it as a shared connector, publishing a private
+ * connection to the workspace (or landing on a shared sibling).
+ */
+ replacesConnectedAccountId: z.string().optional(),
}),
)
.mutation(async ({ input, ctx }) => {
- const { appSlug, identifier, label, agentId } = input;
+ const { appSlug, identifier, label, agentId, replacesConnectedAccountId } = input;
const { userId } = ctx;
assertSupportedComposioApp(identifier, appSlug);
@@ -245,8 +299,13 @@ export const composioRouter = router({
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);
+ // the remote Composio account. A re-authorization resolves the row holding
+ // the replaced account, bound to it like a removal of that account.
+ const existing = await resolveComposioWriteTarget(ctx, {
+ agentId,
+ connectedAccountId: replacesConnectedAccountId,
+ identifier,
+ });
const callbackUrl = `${process.env.APP_URL || process.env.NEXTAUTH_URL || ''}/api/composio/oauth/callback`;
@@ -284,7 +343,16 @@ export const composioRouter = router({
// agent connector is intentionally a *separate* account from the user's
// (and from other agents'), all under the same Composio user entity but
// distinguished by connectedAccountId — so agent links must allow multiple.
- // Personal connections keep the default (one account per auth config).
+ // Personal connections keep the default (one account per auth config), so
+ // the account being replaced is removed first. Best-effort: the prior link
+ // has likely expired already.
+ if (replacesConnectedAccountId) {
+ try {
+ await (ctx.composioClient.connectedAccounts as any).delete(replacesConnectedAccountId);
+ } catch (error) {
+ console.warn('[Composio] Failed to delete the replaced connection:', error);
+ }
+ }
const connReq = await (ctx.composioClient.connectedAccounts as any).link(
userId,
authConfigId,
@@ -326,6 +394,14 @@ export const composioRouter = router({
// skip it for agent connections — the runtime resolves those off the
// agent-scoped connector row's metadata instead.
if (!agentId) {
+ // The replaced account's projection goes as a removal would drop it: a
+ // shared connection's is the app's, a private one's only its own rows.
+ if (replacesConnectedAccountId)
+ await removeComposioProjection(ctx.pluginModel, {
+ connectedAccountId: replacesConnectedAccountId,
+ identifier,
+ visibility: existing?.visibility,
+ });
await ctx.pluginModel.create({
customParams: {
composio: {
@@ -359,6 +435,7 @@ export const composioRouter = router({
redirectUrl: connReq.redirectUrl,
status: 'PENDING',
},
+ existing,
identifier,
label,
tools: manifest.api.map((a) => ({
@@ -386,8 +463,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);
+ // can't grief another member's Composio connection. The row holding this
+ // account is the one removed below.
+ const existing = await resolveComposioWriteTarget(ctx, input);
try {
await (ctx.composioClient.connectedAccounts as any).delete(input.connectedAccountId);
} catch (error) {
@@ -396,15 +474,25 @@ export const composioRouter = router({
// Agent connections have no plugin-table row; only remove the base plugin
// projection for personal connections.
- if (!input.agentId) await ctx.pluginModel.delete(input.identifier);
- await deleteComposioConnector(ctx.connectorModel, input.identifier, input.agentId);
+ if (!input.agentId) {
+ await removeComposioProjection(ctx.pluginModel, {
+ connectedAccountId: input.connectedAccountId,
+ identifier: input.identifier,
+ visibility: existing?.visibility,
+ });
+ }
+ // Tools cascade.
+ if (existing) await ctx.connectorModel.delete(existing.id);
return { success: true };
}),
getComposioPlugins: composioDbProcedure.query(async ({ ctx }) => {
- const allPlugins = await ctx.pluginModel.query();
- return allPlugins.filter((plugin) => plugin.customParams?.composio);
+ const allPlugins = await ctx.pluginModel.query({ forClient: true });
+ return redactForeignComposioLinks(
+ allPlugins.filter((plugin) => plugin.customParams?.composio),
+ ctx,
+ );
}),
getConnection: composioProcedure
@@ -464,9 +552,15 @@ export const composioRouter = router({
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);
+ const existing = await resolveComposioWriteTarget(ctx, input);
+ if (!input.agentId) {
+ await removeComposioProjection(ctx.pluginModel, {
+ connectedAccountId: existing?.metadata?.composio?.connectedAccountId,
+ identifier: input.identifier,
+ visibility: existing?.visibility,
+ });
+ }
+ if (existing) await ctx.connectorModel.delete(existing.id);
return { success: true };
}),
@@ -508,7 +602,13 @@ export const composioRouter = router({
if (agentId)
await assertCanEditAgent(ctx.serverDB, ctx.userId, agentId, ctx.workspaceId ?? undefined);
- await assertComposioRowManageable(ctx, identifier, agentId);
+ // The row holding this account: refreshing a shared account must not
+ // overwrite the caller's private connection of the same app.
+ const existing = await resolveComposioWriteTarget(ctx, {
+ agentId,
+ connectedAccountId,
+ identifier,
+ });
const existingPlugin = await ctx.pluginModel.findById(identifier);
@@ -543,8 +643,11 @@ export const composioRouter = router({
// Personal-only plugin projection: skip for agent connections (see
// createConnection). The agent row's metadata is the runtime source.
+ // Updating by identifier rewrites every member's projection row of the
+ // app; a private connection is the caller's alone, so it refreshes only
+ // the caller's own row and leaves a teammate's legacy connection intact.
if (!agentId) {
- if (existingPlugin) {
+ if (existingPlugin && existing?.visibility !== 'private') {
await ctx.pluginModel.update(identifier, { customParams, manifest });
} else {
await ctx.pluginModel.create({
@@ -570,6 +673,7 @@ export const composioRouter = router({
redirectUrl,
status,
},
+ existing,
identifier,
label,
replaceTools: true,
diff --git a/apps/server/src/routers/lambda/connector.getForEdit.test.ts b/apps/server/src/routers/lambda/connector.getForEdit.test.ts
index 55ae544ef18..e444e604133 100644
--- a/apps/server/src/routers/lambda/connector.getForEdit.test.ts
+++ b/apps/server/src/routers/lambda/connector.getForEdit.test.ts
@@ -1,13 +1,17 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { AgentModel } from '@/database/models/agent';
import { ConnectorModel } from '@/database/models/connector';
+import { ConnectorLinkModel } from '@/database/models/connectorLink';
import { ConnectorToolModel } from '@/database/models/connectorTool';
+import { toolSetsFrom } from '@/server/services/aiAgent/__tests__/helpers/connectorToolSets';
import { connectorRouter } from './connector';
vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));
vi.mock('@/database/models/connector', () => ({ ConnectorModel: vi.fn() }));
+vi.mock('@/database/models/connectorLink', () => ({ ConnectorLinkModel: vi.fn() }));
vi.mock('@/database/models/connectorTool', () => ({ ConnectorToolModel: vi.fn() }));
vi.mock('@/database/models/plugin', () => ({ PluginModel: vi.fn() }));
const workspaceMocks = vi.hoisted(() => ({
@@ -81,3 +85,362 @@ describe('connectorRouter.getForEdit', () => {
expect(queryByConnector).not.toHaveBeenCalled();
});
});
+
+describe('connectorRouter.getForRun', () => {
+ const resolveByIdentifiers = vi.fn();
+ const existsById = vi.fn();
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(AgentModel).mockImplementation(function () {
+ return { existsById } as never;
+ });
+ vi.mocked(ConnectorModel).mockImplementation(function () {
+ return { resolveByIdentifiers, resolveToolSets: toolSetsFrom(resolveByIdentifiers) } as never;
+ });
+ vi.mocked(ConnectorToolModel).mockImplementation(function () {
+ return { queryByConnector } as never;
+ });
+ existsById.mockResolvedValue(true);
+ resolveByIdentifiers.mockResolvedValue([connector]);
+ queryByConnector.mockResolvedValue(tools);
+ });
+
+ const caller = (userId: string) =>
+ connectorRouter.createCaller({
+ serverDB: {},
+ userId,
+ workspaceId: 'workspace',
+ workspaceRole: 'member',
+ } as never);
+
+ const input = { agentId: 'agent-private', identifier: 'local-mcp', topicId: 'topic-group' };
+
+ it('returns the row the conversation resolves on the server, not one the client picked', async () => {
+ // A desktop runs a stdio connector itself. Only the server can tell a
+ // private agent's own topic from a group topic, so it names the row.
+ await expect(caller('creator').getForRun(input)).resolves.toMatchObject({
+ id: connector.id,
+ mcpStdioConfig: connector.mcpStdioConfig,
+ tools,
+ });
+
+ expect(resolveByIdentifiers).toHaveBeenCalledWith(['local-mcp'], {
+ agentId: 'agent-private',
+ topicId: 'topic-group',
+ });
+ // A private agent may resolve its owner's personal connector, whose tools
+ // live in the personal scope.
+ expect(ConnectorToolModel).toHaveBeenCalledWith(expect.anything(), 'creator', 'workspace', {
+ agentRun: true,
+ });
+ });
+
+ it('resolves nothing for an agent the caller cannot see', async () => {
+ existsById.mockResolvedValue(false);
+
+ await expect(caller('creator').getForRun(input)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(resolveByIdentifiers).not.toHaveBeenCalled();
+ });
+
+ it('keeps the resolved configuration behind the creator gate', async () => {
+ await expect(caller('another-member').getForRun(input)).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ expect(queryByConnector).not.toHaveBeenCalled();
+ });
+});
+
+describe('connectorRouter.resolveForRun', () => {
+ const resolveByIdentifiers = vi.fn();
+ const existsById = vi.fn();
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(AgentModel).mockImplementation(function () {
+ return { existsById } as never;
+ });
+ vi.mocked(ConnectorModel).mockImplementation(function () {
+ return { resolveByIdentifiers, resolveToolSets: toolSetsFrom(resolveByIdentifiers) } as never;
+ });
+ vi.mocked(ConnectorToolModel).mockImplementation(function () {
+ return { queryByConnector } as never;
+ });
+ existsById.mockResolvedValue(true);
+ resolveByIdentifiers.mockResolvedValue([connector]);
+ queryByConnector.mockResolvedValue(tools);
+ });
+
+ const caller = (userId: string) =>
+ connectorRouter.createCaller({
+ serverDB: {},
+ userId,
+ workspaceId: 'workspace',
+ workspaceRole: 'viewer',
+ } as never);
+
+ const input = { agentId: 'agent-private', identifier: 'local-mcp', topicId: 'topic-group' };
+
+ it('names the row the conversation runs on, with its transport but not its configuration', async () => {
+ // Any member who can call the tool may ask: the answer routes the call and
+ // judges its approval, never the creator-gated stdio command and env that
+ // getForRun returns.
+ await expect(caller('another-member').resolveForRun(input)).resolves.toEqual({
+ agentId: undefined,
+ id: connector.id,
+ identifier: 'local-mcp',
+ isEnabled: true,
+ links: [],
+ mcpConnectionType: 'stdio',
+ mcpServerUrl: undefined,
+ metadata: {},
+ sourceType: undefined,
+ status: undefined,
+ toolIdentifier: 'local-mcp',
+ tools,
+ });
+ expect(resolveByIdentifiers).toHaveBeenCalledWith(['local-mcp'], {
+ agentId: 'agent-private',
+ topicId: 'topic-group',
+ });
+ });
+
+ it("lists the accounts of the owner's personal connector a private agent runs", async () => {
+ // The workspace scope cannot list a personal row's accounts; without them
+ // a desktop's local call could not tell that the model must name one.
+ const account = (id: string) => ({
+ createdAt: new Date('2026-01-01T00:00:00Z'),
+ credentials: { accessToken: id, type: 'oauth2' },
+ id,
+ name: id,
+ status: 'connected',
+ userConnectorId: 'personal-row',
+ userId: 'creator',
+ });
+ const personalLinks = {
+ listByConnectorIds: vi.fn().mockResolvedValue([account('lnk_a'), account('lnk_b')]),
+ };
+ const personalModel = {
+ forRow() {
+ return this;
+ },
+ getLinkModel: () => personalLinks,
+ };
+ vi.mocked(ConnectorModel).mockImplementation(function () {
+ return {
+ forRow: () => personalModel,
+ resolveByIdentifiers,
+ resolveToolSets: toolSetsFrom(resolveByIdentifiers),
+ } as never;
+ });
+ resolveByIdentifiers.mockResolvedValue([
+ {
+ ...connector,
+ credentials: null,
+ id: 'personal-row',
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://nas.tail1234.ts.net/mcp',
+ oidcConfig: { clientId: 'client', scheme: 'dcr' },
+ workspaceId: null,
+ },
+ ]);
+
+ const answer = await caller('creator').resolveForRun(input);
+
+ expect(answer?.links.map((link) => link.id)).toEqual(['lnk_a', 'lnk_b']);
+ expect(personalLinks.listByConnectorIds).toHaveBeenCalledWith(['personal-row']);
+ });
+
+ it("reads the tools of the owner's personal connector a private agent runs", async () => {
+ // Regression: the client's workspace lists never hold a personal row, so a
+ // desktop could not tell that the call runs a stdio connector and sent it
+ // to the server, which cannot run one.
+ await caller('creator').resolveForRun(input);
+
+ expect(ConnectorToolModel).toHaveBeenCalledWith(expect.anything(), 'creator', 'workspace', {
+ agentRun: true,
+ });
+ expect(queryByConnector).toHaveBeenCalledWith(connector.id);
+ });
+
+ it('carries the install state the client routes by, and no other metadata', async () => {
+ // A personal marketplace stdio install keeps running on the desktop under a
+ // device gateway, and an unfinished install is not run: the client reads
+ // both off this answer for a row its lists lack.
+ resolveByIdentifiers.mockResolvedValue([
+ {
+ ...connector,
+ agentId: null,
+ metadata: {
+ composio: { connectedAccountId: 'ca-1' },
+ description: 'Local files',
+ marketplaceInstalled: true,
+ },
+ sourceType: 'marketplace',
+ status: 'connected',
+ },
+ ]);
+
+ await expect(caller('creator').resolveForRun(input)).resolves.toMatchObject({
+ agentId: null,
+ metadata: { marketplaceInstalled: true },
+ sourceType: 'marketplace',
+ status: 'connected',
+ });
+ const answer = await caller('creator').resolveForRun(input);
+ expect(answer?.metadata).toEqual({ marketplaceInstalled: true });
+ });
+
+ it('carries where an HTTP server is reached from, so a personal one runs on its device', async () => {
+ // Regression: a private agent's own topic may run its owner's personal HTTP
+ // connector, which no workspace list on the client holds. Without
+ // `connectVia`, a public-looking address set to connect through the device
+ // (Tailscale MagicDNS) routed to the server, which refuses it; without
+ // `boundDeviceId`, one bound to another device was run here.
+ resolveByIdentifiers.mockResolvedValue([
+ {
+ ...connector,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://nas.tail1234.ts.net/mcp',
+ metadata: { boundDeviceId: 'laptop', connectVia: 'device', description: 'NAS' },
+ },
+ ]);
+
+ const answer = await caller('creator').resolveForRun(input);
+
+ expect(answer?.metadata).toEqual({ boundDeviceId: 'laptop', connectVia: 'device' });
+ });
+
+ it('answers null when the conversation resolves no row', async () => {
+ resolveByIdentifiers.mockResolvedValue([]);
+ await expect(caller('creator').resolveForRun(input)).resolves.toBeNull();
+
+ existsById.mockResolvedValue(false);
+ await expect(caller('creator').resolveForRun(input)).resolves.toBeNull();
+ });
+});
+
+describe('connectorRouter.getLocalCallToken', () => {
+ const resolveByIdentifiers = vi.fn();
+ const findById = vi.fn();
+ const existsById = vi.fn();
+ // A personal OAuth HTTP connector on a tailnet, set to connect through the device
+ const personal = {
+ credentials: null,
+ id: '9f1f6f30-0000-4000-8000-00000000000a',
+ identifier: 'nas',
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://nas.tail1234.ts.net/mcp',
+ metadata: { connectVia: 'device' },
+ oidcConfig: { clientId: 'client', scheme: 'dcr' },
+ userId: 'creator',
+ workspaceId: null,
+ };
+ const account = {
+ credentials: { accessToken: 'personal-access', type: 'oauth2' },
+ id: 'lnk_personal',
+ name: 'Personal',
+ status: 'connected',
+ userConnectorId: personal.id,
+ userId: 'creator',
+ };
+ // Accounts are listed per scope: the workspace's, or the creator's personal one
+ const workspaceLinks = { listByConnectorIds: vi.fn() };
+ const personalLinks = { listByConnectorIds: vi.fn() };
+ const personalModel = {
+ forRow() {
+ return this;
+ },
+ getLinkModel: () => personalLinks,
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(AgentModel).mockImplementation(function () {
+ return { existsById } as never;
+ });
+ vi.mocked(ConnectorModel).mockImplementation(function () {
+ const model = {
+ findById,
+ forRow: (row: { workspaceId: string | null }) =>
+ row.workspaceId === null ? personalModel : model,
+ getLinkModel: () => workspaceLinks,
+ resolveByIdentifiers,
+ resolveToolSets: toolSetsFrom(resolveByIdentifiers),
+ };
+ return model as never;
+ });
+ vi.mocked(ConnectorLinkModel).mockImplementation(function () {
+ return workspaceLinks as never;
+ });
+ existsById.mockResolvedValue(true);
+ resolveByIdentifiers.mockResolvedValue([personal]);
+ // The workspace scope can read neither a personal row by id nor its accounts
+ findById.mockResolvedValue(null);
+ workspaceLinks.listByConnectorIds.mockResolvedValue([]);
+ personalLinks.listByConnectorIds.mockResolvedValue([account]);
+ });
+
+ const caller = (userId: string) =>
+ connectorRouter.createCaller({
+ serverDB: {},
+ userId,
+ workspaceId: 'workspace',
+ workspaceRole: 'member',
+ } as never);
+
+ const run = { agentId: 'agent-private', identifier: 'nas', topicId: 'topic-own' };
+
+ it("returns the token of the personal connector a private agent's conversation runs", async () => {
+ // Regression: `getForRun` returned the owner's personal row for a private
+ // agent's own topic, but the token was looked up by id in the workspace
+ // scope, which cannot find it, so the desktop call failed with NOT_FOUND.
+ await expect(caller('creator').getLocalCallToken({ id: personal.id, run })).resolves.toEqual({
+ accessToken: 'personal-access',
+ type: 'oauth2',
+ });
+ expect(resolveByIdentifiers).toHaveBeenCalledWith(['nas'], {
+ agentId: 'agent-private',
+ topicId: 'topic-own',
+ });
+ expect(findById).not.toHaveBeenCalled();
+ expect(personalLinks.listByConnectorIds).toHaveBeenCalledWith([personal.id]);
+ expect(workspaceLinks.listByConnectorIds).not.toHaveBeenCalled();
+ });
+
+ it('refuses a row the conversation does not run', async () => {
+ // A group topic resolves the shared row: a private connector's token is not its own
+ resolveByIdentifiers.mockResolvedValue([{ ...personal, id: 'shared-row' }]);
+
+ await expect(
+ caller('creator').getLocalCallToken({ id: personal.id, run }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('resolves nothing for an agent the caller cannot see', async () => {
+ existsById.mockResolvedValue(false);
+
+ await expect(
+ caller('creator').getLocalCallToken({ id: personal.id, run }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(resolveByIdentifiers).not.toHaveBeenCalled();
+ });
+
+ it('keeps the token behind the creator gate', async () => {
+ await expect(
+ caller('another-member').getLocalCallToken({ id: personal.id, run }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it("reads a row of the caller's scope by id outside a conversation", async () => {
+ findById.mockResolvedValue({ ...personal, workspaceId: 'workspace' });
+ workspaceLinks.listByConnectorIds.mockResolvedValue([account]);
+
+ await expect(caller('creator').getLocalCallToken({ id: personal.id })).resolves.toEqual({
+ accessToken: 'personal-access',
+ type: 'oauth2',
+ });
+ expect(findById).toHaveBeenCalledWith(personal.id);
+ expect(resolveByIdentifiers).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/connector/agentScope.ts b/apps/server/src/routers/lambda/connector/agentScope.ts
index 7f328154f81..44d36ebfe90 100644
--- a/apps/server/src/routers/lambda/connector/agentScope.ts
+++ b/apps/server/src/routers/lambda/connector/agentScope.ts
@@ -5,6 +5,7 @@ import { AgentModel } from '@/database/models/agent';
import { router } from '@/libs/trpc/lambda';
import { assertConnectorCredentialsManageable } from '../_helpers/connectorManagePolicy';
+import { assertPrivateConnectorTarget } from '../_helpers/connectorVisibility';
import { connectorWriteProcedure } from './procedures';
/**
@@ -34,6 +35,7 @@ export const connectorAgentScopeRouter = router({
if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
// Rebinding routes the connector's credentials to the agent — creator/owner only.
await assertConnectorCredentialsManageable(ctx, connector);
+ await assertPrivateConnectorTarget(ctx, connector, input.agentId);
const existingAgentRow = await ctx.connectorModel.findScopedByIdentifier(
connector.identifier,
@@ -64,6 +66,9 @@ export const connectorAgentScopeRouter = router({
await assertConnectorCredentialsManageable(ctx, connector);
if (!connector.agentId) return { id: input.connectorId }; // already base — no-op
+ // The base slot it returns to is its own visibility's: a private row and a
+ // shared row of one identifier live side by side in the base scope. The
+ // lookup and the move are one step under the identifier lock.
const moved = await ctx.connectorModel.moveToBaseUnlessIdentifierHeld(
input.connectorId,
connector.identifier,
@@ -93,8 +98,10 @@ export const connectorAgentScopeRouter = router({
const source = await ctx.connectorModel.findById(input.connectorId);
if (!source) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
// Cloning duplicates the source's encrypted credentials into a row the
- // agent owner controls — creator/owner only.
+ // agent owner controls — creator/owner only. The copy keeps the source's
+ // visibility, so a private connector stays private on the agent.
await assertConnectorCredentialsManageable(ctx, source);
+ await assertPrivateConnectorTarget(ctx, source, input.agentId);
const existing = await ctx.connectorModel.findScopedByIdentifier(
source.identifier,
@@ -130,6 +137,7 @@ export const connectorAgentScopeRouter = router({
// Mounting routes the source's credentials to the agent and locks the
// row (metadata.mountedByAgentId) — creator/owner only.
await assertConnectorCredentialsManageable(ctx, connector);
+ await assertPrivateConnectorTarget(ctx, connector, input.agentId);
if (connector.agentId) {
throw new TRPCError({
code: 'BAD_REQUEST',
diff --git a/apps/server/src/routers/lambda/connector/index.ts b/apps/server/src/routers/lambda/connector/index.ts
index 16a5f3c73a2..6a65602bd3e 100644
--- a/apps/server/src/routers/lambda/connector/index.ts
+++ b/apps/server/src/routers/lambda/connector/index.ts
@@ -1,7 +1,8 @@
import { builtinTools } from '@lobechat/builtin-tools';
import { getComposioAppByIdentifier, hasCallableMcpEndpoint } from '@lobechat/const';
import { isFullAccessApiKey } from '@lobechat/const/apiKeyScope';
-import { upsertPluginMode } from '@lobechat/types';
+import type { ConnectorVisibility } from '@lobechat/types';
+import { CONNECTOR_VISIBILITIES, upsertPluginMode } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import pMap from 'p-map';
import { z } from 'zod';
@@ -24,15 +25,9 @@ import {
ConnectorToolPermission,
} from '@/database/schemas';
import { getComposioClient } from '@/libs/composio';
-import { getMCPConnectionErrorType, inferCrudType } from '@/libs/mcp/utils';
+import { inferCrudType } from '@/libs/mcp/utils';
import { mergeRouters, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import {
- callConnectorToolById,
- ConnectorToolCallError,
- readConnectorUiResourceById,
-} from '@/server/services/connector/exec';
-import { getConnectorLocalCallToken } from '@/server/services/connector/localCallToken';
import { getConnectorRedirectUri } from '@/server/services/connector/oauth';
import { loadConnectorPresentation } from '@/server/services/connector/presentation';
import {
@@ -54,16 +49,18 @@ import {
import {
resolveConnectorAuthorizerId,
resolveUserDisplayMap,
- withTrustedLinkedByUserId,
+ withServerOwnedMetadata,
} from '@/server/utils/connectorAttribution';
import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
import { toClientToolSyncInputs } from '../_helpers/clientToolSyncInputs';
-import { withRequestConnectorCallers } from '../_helpers/connectorCallContext';
+import { findComposioAccountConflict } from '../_helpers/composioAccountBinding';
+import { removeComposioProjection } from '../_helpers/composioProjection';
import {
assertBoundDeviceOperable,
assertConnectorDeviceBindingAllowed,
} from '../_helpers/connectorDeviceBinding';
+import { toConnectorEditDetail } from '../_helpers/connectorEditDetail';
import {
assertConnectorCredentialsManageable,
assertConnectorMaintainable,
@@ -72,10 +69,12 @@ import {
isWorkspaceConnectorAdmin,
} from '../_helpers/connectorManagePolicy';
import { resolveDefaultPermission } from '../_helpers/connectorToolPermission';
+import { resolveVisibilityChange, resolveWriteVisibility } from '../_helpers/connectorVisibility';
import { upsertConnectorEntry } from '../_helpers/upsertConnectorEntry';
import { connectorAccountProcedures } from './accounts';
import { connectorAgentScopeRouter } from './agentScope';
import { connectorProcedure, connectorWriteProcedure } from './procedures';
+import { connectorRunRouter } from './run';
/** Per-connector DB reads and writes a request runs at once, however many rows it covers. */
const DB_CONCURRENCY = 5;
@@ -138,6 +137,12 @@ const createConnectorSchema = z.object({
ConnectorSourceType.custom,
ConnectorSourceType.marketplace,
]),
+ /**
+ * Workspace only: `private` keeps the connector to its creator and their
+ * private agents (私人); `public` (default) shares it with the workspace.
+ * Ignored in personal mode and for agent-scoped connectors.
+ */
+ visibility: z.enum(CONNECTOR_VISIBILITIES).optional(),
});
const connectorCoreRouter = router({
@@ -272,14 +277,8 @@ const connectorCoreRouter = router({
/**
* Return the connector record with decrypted user-set credentials so the
- * edit form can pre-fill accurately. Only the connector owner can call this
- * (enforced by connectorProcedure ownership check).
- *
- * Machine-managed secrets are intentionally excluded:
- * - OAuth access/refresh tokens (type 'oauth2') → stripped, returned as null
- * - oidcConfig.clientSecret (DCR-registered secret) → stripped
- * User-set credentials (bearer token, custom headers) are returned as-is so
- * the edit form can display them.
+ * edit form can pre-fill accurately (see {@link toConnectorEditDetail} for
+ * what is stripped). Only the connector owner can call this.
*/
// Member-gated even though it's a query: it returns decrypted credentials
// for edit prefill, so a creator later downgraded to viewer must not reach it.
@@ -288,26 +287,13 @@ const connectorCoreRouter = router({
.query(async ({ input, ctx }) => {
const connector = await ctx.connectorModel.findById(input.id);
if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
- // Edit-read returns decrypted credentials — creator/owner only. Not gated by
- // the member policy: desktop stdio/local connectors read their config
- // here at run time, so a restriction must not stop the creator using them.
+ // Edit-read returns decrypted credentials — creator/owner only.
assertWorkspaceRowManageable(ctx, connector.userId, 'connector');
- const { oidcConfig, credentials, ...rest } = connector;
- const safeOidcConfig = oidcConfig ? { ...oidcConfig, clientSecret: undefined } : oidcConfig;
- // OAuth tokens are machine-managed — don't return them; the UI only needs
- // to know an OAuth flow is configured (reflected via oidcConfig presence).
- const safeCredentials = credentials?.type === 'oauth2' ? null : credentials;
-
const tools = await ctx.connectorToolModel.queryByConnector(connector.id);
- return { ...rest, credentials: safeCredentials, oidcConfig: safeOidcConfig, tools };
+ return toConnectorEditDetail(connector, tools);
}),
- /** The OAuth access token a device-routed connector's local desktop call sends. */
- getLocalCallToken: connectorWriteProcedure
- .input(z.object({ id: z.string().uuid(), linkId: z.string().optional() }))
- .mutation(({ ctx, input }) => getConnectorLocalCallToken(ctx, input.id, input.linkId)),
-
/**
* Test an MCP server that runs on the user's device (an HTTP server set to
* connect through it, or one bound to a device): its manifest, read on the
@@ -406,20 +392,23 @@ const connectorCoreRouter = router({
mcpConnectionType: input.mcpConnectionType ?? null,
mcpServerUrl: input.mcpServerUrl ?? null,
mcpStdioConfig: input.mcpStdioConfig ?? null,
- // Drop any client-supplied `composio.linkedByUserId` — it is server-owned
- // (written by the OAuth connect path), and trusting it here would let a
- // member spoof connector attribution. No existing row on create → the
- // field is simply removed.
+ // Drop any client-supplied `composio` block or `mountedByAgentId`: both
+ // are server-owned. Trusting the first would let a member spoof
+ // connector attribution, or name a teammate's account on a private row
+ // of their own so its real owner can no longer refresh or remove it.
+ // Trusting the second would let a member mount a shared row on a
+ // teammate's private agent, past `mountToAgent`'s checks, and have it
+ // outrank the owner's private connector.
metadata:
- withoutEvalConnectorMarker(withTrustedLinkedByUserId(input.metadata, undefined)) ?? null,
+ withoutEvalConnectorMarker(withServerOwnedMetadata(input.metadata, undefined)) ?? null,
name: input.name,
oidcConfig: input.oidcConfig ?? null,
};
- // Idempotent on (user_id, identifier): re-adding or re-authorizing the same
- // connector updates the existing row instead of violating the unique index.
- // Status resets to `disconnected` — the OAuth callback / tool sync promotes
- // it back to `connected` on success.
+ // Idempotent on (scope, visibility, identifier): re-adding or
+ // re-authorizing the same connector updates the existing row. Status
+ // resets to `disconnected` — the OAuth callback / tool sync promotes it
+ // back to `connected` on success.
//
// `sourceType` is honored on update so the legacy customPlugin → connector
// migration can promote a half-baked `marketplace` row left behind by the
@@ -435,6 +424,10 @@ const connectorCoreRouter = router({
// enforcing "one connector per identifier per agent" at the app layer (the
// DB indexes are non-unique so multiple same-identifier rows can coexist
// across scopes).
+ //
+ // A private connector is looked up among the caller's own private rows, so
+ // adding one never rewrites the shared connector of the same identifier.
+ const visibility = agentId ? 'public' : resolveWriteVisibility(ctx, input.visibility);
const row = {
...fields,
isEnabled: input.isEnabled ?? true,
@@ -444,16 +437,30 @@ const connectorCoreRouter = router({
// Adding a workspace connector follows the member policy. Re-adding over
// someone else's row rewrites its server/command while the row stays theirs
// (their runs would execute it, and they could read the new credentials), so
- // that keeps the creator-or-owner rule.
+ // that keeps the creator-or-owner rule. A private connector is the caller's
+ // own and skips the member policy.
const assertWritable = async (existing?: {
agentId: string | null;
metadata?: Record<string, unknown> | null;
userId: string;
+ visibility: ConnectorVisibility;
}) => {
if (existing && existing.userId !== ctx.userId)
await assertConnectorCredentialsManageable(ctx, existing);
- else await assertConnectorMaintainable(ctx, { agentId, userId: existing?.userId });
- await assertConnectorDeviceBindingAllowed(ctx, input.metadata, existing?.metadata);
+ else
+ await assertConnectorMaintainable(ctx, { agentId, userId: existing?.userId, visibility });
+ // An upsert keeps the row's creator and visibility (an agent's row may
+ // be a private copy)
+ await assertConnectorDeviceBindingAllowed(ctx, {
+ connector: {
+ userId: existing?.userId ?? ctx.userId,
+ visibility: existing?.visibility ?? visibility,
+ },
+ metadata: input.metadata,
+ previous: existing
+ ? { metadata: existing.metadata, visibility: existing.visibility }
+ : undefined,
+ });
};
// `isNew` lets clients tell a fresh row from an updated pre-existing one —
// client-side caches can't answer this reliably (the connector list may
@@ -465,14 +472,29 @@ const connectorCoreRouter = router({
id: string;
metadata?: Record<string, unknown> | null;
userId: string;
+ visibility: ConnectorVisibility;
}) => {
await assertWritable(existing);
- const updated = await ctx.connectorModel.update(existing.id, row);
+ // The row keeps its server-owned metadata (its Composio account, its
+ // mount): the client never authors it, and dropping the account here
+ // would leave its legacy plugin projection as the only holder, which
+ // publishes a private connection to the workspace again.
+ const metadata =
+ withServerOwnedMetadata(row.metadata ?? {}, existing.metadata) ?? row.metadata;
+ const updated = await ctx.connectorModel.update(existing.id, {
+ ...row,
+ metadata: metadata && Object.keys(metadata).length > 0 ? metadata : null,
+ });
return updated ? { id: existing.id, isNew: false } : undefined;
};
const add = async () => {
- const existing = await ctx.connectorModel.findScopedByIdentifier(input.identifier, agentId);
+ const existing = await ctx.connectorModel.findScopedByIdentifier(
+ input.identifier,
+ agentId,
+ undefined,
+ visibility,
+ );
if (existing) return reAdd(existing);
await assertWritable();
@@ -481,14 +503,17 @@ const connectorCoreRouter = router({
...row,
agentId,
identifier: input.identifier,
+ visibility,
});
return { id: created.id, isNew: true };
}
// A base row is claimed under the identifier lock every base-row writer
- // takes (an Agent Builder install among them), so concurrent adds create it once.
+ // takes (an Agent Builder install among them), so concurrent adds create
+ // it once. The claim holds the identifier within this row's visibility.
const claim = await ctx.connectorModel.createUnlessIdentifierHeld({
...row,
identifier: input.identifier,
+ visibility,
});
if ('holder' in claim) return reAdd(claim.holder);
return { id: claim.created.id, isNew: true };
@@ -540,9 +565,9 @@ const connectorCoreRouter = router({
// A patch may keep the stored credentials while repointing the server
// URL, which would send them elsewhere — creator/owner only.
await assertConnectorCredentialsManageable(ctx, target);
- await assertConnectorDeviceBindingAllowed(ctx, input.patch.metadata, target.metadata);
- const { credentials, ...patch } = input.patch;
+ const { credentials, visibility: requestedVisibility, ...patch } = input.patch;
+ const visibility = await resolveVisibilityChange(ctx, target, requestedVisibility);
const changesUrl =
patch.mcpServerUrl !== undefined && patch.mcpServerUrl !== target.mcpServerUrl;
if (
@@ -576,11 +601,36 @@ const connectorCoreRouter = router({
),
};
}
- // Preserve the server-owned `composio.linkedByUserId` from the stored row
- // and ignore whatever the client sent, so an edit can never spoof (or
- // silently clear) the connector's authorizer. Untouched when the patch
- // omits metadata.
- const metadata = withTrustedLinkedByUserId(patch.metadata, target.metadata);
+ // Checked against who will run the connector after this write
+ await assertConnectorDeviceBindingAllowed(ctx, {
+ connector: { userId: target.userId, visibility: visibility ?? target.visibility },
+ metadata: patch.metadata,
+ previous: { metadata: target.metadata, visibility: target.visibility },
+ });
+ // Keep the stored, server-owned `composio` block and mount and ignore
+ // whatever the client sent, so an edit can never repoint the row at
+ // another Composio account, spoof (or silently clear) the connector's
+ // authorizer, or mount the row on an agent past `mountToAgent`'s checks.
+ // Untouched when the patch omits metadata.
+ const metadata = withServerOwnedMetadata(patch.metadata, target.metadata);
+ // The destination slot is claimed under the identifier lock every
+ // base-row writer takes: two members sharing private connectors of one
+ // identifier at once never both land in the shared slot
+ if (visibility) {
+ const changed = await ctx.connectorModel.changeVisibilityUnlessHeld(
+ input.id,
+ target.identifier,
+ visibility,
+ );
+ if ('holder' in changed)
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message:
+ visibility === 'public'
+ ? `The workspace already shares a "${target.identifier}" connector`
+ : `You already have a private "${target.identifier}" connector`,
+ });
+ }
try {
await ctx.connectorModel.update(input.id, {
...patch,
@@ -626,7 +676,14 @@ const connectorCoreRouter = router({
await assertConnectorMaintainable(ctx, target);
const connectedAccountId = target.metadata?.composio?.connectedAccountId;
- if (connectedAccountId) {
+ // The account this row names may also be held by other rows: a
+ // teammate's private connector, or one the caller may not maintain. Then
+ // the remote account and its projection are not this row's to remove;
+ // the row itself still goes.
+ if (
+ connectedAccountId &&
+ !(await findComposioAccountConflict(ctx, target, connectedAccountId))
+ ) {
try {
await getComposioClient().connectedAccounts.delete(connectedAccountId);
} catch (error) {
@@ -639,7 +696,9 @@ const connectorCoreRouter = router({
// Personal Composio connections still carry the legacy plugin projection.
// Agent-scoped connections never create one, so do not remove a base
// plugin that may belong to a separate personal connection.
- if (!target.agentId) await ctx.pluginModel.delete(target.identifier);
+ if (!target.agentId) {
+ await removeComposioProjection(ctx.pluginModel, { ...target, connectedAccountId });
+ }
}
await removeByConnector(
@@ -711,72 +770,6 @@ const connectorCoreRouter = router({
}
}),
- /**
- * Execute a single connector tool by identifier (classic chat path). Resolves
- * the connector, hard-blocks disabled tools, refreshes the OAuth token if
- * needed, and calls the remote MCP server with the decrypted credentials.
- */
- callTool: connectorWriteProcedure
- .input(
- z.object({
- /** Resolve the identifier for this agent (agent-owned connector first). */
- agentId: z.string().optional(),
- args: z.string().optional(),
- /** An MCP App view's `tools/call`: only tools visible to the app run. */
- fromApp: z.boolean().optional(),
- fromEntrypoint: z.boolean().optional(),
- identifier: z.string().min(1),
- /** The account to call as, for a connector holding several. */
- linkId: z.string().optional(),
- /** With `fromApp`: the server the view came from (`getMcpServerFingerprint`). */
- server: z.string().optional(),
- toolName: z.string().min(1),
- /** The conversation the call runs in, reported as the call's session. */
- topicId: z.string().optional(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- try {
- return await callConnectorToolById(input, withRequestConnectorCallers(ctx));
- } catch (err: any) {
- if (err instanceof ConnectorToolCallError) {
- throw new TRPCError({ cause: err, code: err.code, message: err.message });
- }
- if (err instanceof TRPCError && getMCPConnectionErrorType(err.cause)) throw err;
- throw new TRPCError({
- cause: err,
- code: 'INTERNAL_SERVER_ERROR',
- message: `Connector tool call failed: ${err?.message ?? 'unknown error'}`,
- });
- }
- }),
-
- /**
- * Read the MCP Apps `ui://` resource a connector tool result renders with.
- */
- readUiResource: connectorProcedure
- .input(
- z.object({
- agentId: z.string().optional(),
- identifier: z.string().min(1),
- /** The server the result came from (`getMcpServerFingerprint`). */
- server: z.string().min(1),
- uri: z.string().startsWith('ui://'),
- /** The account the tool ran as, for a connector holding several. */
- linkId: z.string().optional(),
- }),
- )
- .query(async ({ input, ctx }) => {
- try {
- return await readConnectorUiResourceById(input, ctx);
- } catch (err: any) {
- if (err instanceof ConnectorToolCallError) {
- throw new TRPCError({ cause: err, code: err.code, message: err.message });
- }
- throw err;
- }
- }),
-
/**
* Reset all tool permissions for a connector back to 'auto' (fully open).
*/
@@ -996,8 +989,21 @@ const connectorCoreRouter = router({
// A connector installed for this identifier (an endpoint plus the tools
// it synced from its own server) supersedes the plugin row, whose
// manifest a reinstall leaves as it was. Projecting that manifest would
- // put the old tools and display fields back over the synced ones.
- const [installed] = await ctx.connectorModel.queryByIdentifiers([input.identifier]);
+ // put the old tools and display fields back over the synced ones. In a
+ // workspace that includes the caller's own private row, which
+ // `upsertConnectorEntry` would otherwise refresh in place.
+ const [shared] = await ctx.connectorModel.queryByIdentifiers([input.identifier]);
+ const installed =
+ shared && hasCallableMcpEndpoint(shared)
+ ? shared
+ : ctx.workspaceId
+ ? await ctx.connectorModel.findScopedByIdentifier(
+ input.identifier,
+ undefined,
+ undefined,
+ 'private',
+ )
+ : null;
if (installed && hasCallableMcpEndpoint(installed)) {
return { connectorId: installed.id, toolCount: 0 };
}
@@ -1039,4 +1045,8 @@ const connectorCoreRouter = router({
}),
});
-export const connectorRouter = mergeRouters(connectorCoreRouter, connectorAgentScopeRouter);
+export const connectorRouter = mergeRouters(
+ connectorCoreRouter,
+ connectorAgentScopeRouter,
+ connectorRunRouter,
+);
diff --git a/apps/server/src/routers/lambda/connector/run.ts b/apps/server/src/routers/lambda/connector/run.ts
new file mode 100644
index 00000000000..e4388c84c6d
--- /dev/null
+++ b/apps/server/src/routers/lambda/connector/run.ts
@@ -0,0 +1,292 @@
+import {
+ DESKTOP_STDIO_EXECUTION_KEY,
+ MARKETPLACE_INSTALL_COMPLETED_KEY,
+} from '@lobechat/const/plugin';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { ConnectorToolModel } from '@/database/models/connectorTool';
+import { getMCPConnectionErrorType } from '@/libs/mcp/utils';
+import { router } from '@/libs/trpc/lambda';
+import {
+ callConnectorToolById,
+ ConnectorToolCallError,
+ readConnectorUiResourceById,
+ resolveConnectorForRun,
+} from '@/server/services/connector/exec';
+import {
+ getConnectorLocalCallToken,
+ getResolvedConnectorLocalCallToken,
+} from '@/server/services/connector/localCallToken';
+import { loadConnectorPresentation } from '@/server/services/connector/presentation';
+
+import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
+import { withRequestConnectorCallers } from '../_helpers/connectorCallContext';
+import { toConnectorEditDetail } from '../_helpers/connectorEditDetail';
+import { connectorProcedure, connectorWriteProcedure } from './procedures';
+
+/**
+ * The fields of a row's metadata the client routes a call by: the two install
+ * marks (`@lobechat/const/plugin`), and where an HTTP server is reached from —
+ * `connectVia` sends one that looks public through the device
+ * (`connectorMcpEndpoint`), `boundDeviceId` pins it to a device
+ * (`connectorDeviceBinding`).
+ */
+const ROUTING_METADATA_KEYS = [
+ DESKTOP_STDIO_EXECUTION_KEY,
+ MARKETPLACE_INSTALL_COMPLETED_KEY,
+ 'boundDeviceId',
+ 'connectVia',
+];
+
+const pickRoutingMetadata = (metadata: Record<string, unknown> | null | undefined) =>
+ Object.fromEntries(
+ ROUTING_METADATA_KEYS.filter((key) => metadata?.[key] !== undefined).map((key) => [
+ key,
+ metadata![key],
+ ]),
+ );
+
+/**
+ * A conversation's use of a connector: calling its tools, reading the views
+ * they render with, which row it runs on, and the configuration a desktop
+ * needs to run one itself.
+ * Every procedure resolves the connector the way the conversation's run does
+ * (`resolveConnectorForRun`), so a private connector serves only the
+ * conversations that may use it.
+ */
+export const connectorRunRouter = router({
+ /**
+ * The connector rows a conversation's run turns into tool sets, each with its
+ * tool prefix (`toolIdentifier`): what a client-run chat offers the model and
+ * routes calls by. Only the server can tell a private agent's own topic from
+ * a group, a channel, a link-shared or another agent's one, and a private
+ * agent's own topic also runs its owner's personal rows, which no workspace
+ * list on the client holds. Shaped like `connector.list`: no credentials and
+ * no client secret; every row is one the caller may run.
+ */
+ listForRun: connectorProcedure
+ .input(z.object({ agentId: z.string().optional(), topicId: z.string().optional() }))
+ .query(async ({ input, ctx }) => {
+ if (input.agentId && !(await ctx.agentModel.existsById(input.agentId))) return [];
+ const connectors = await ctx.connectorModel.resolveToolSets({
+ agentId: input.agentId,
+ topicId: input.topicId,
+ });
+ const presentation = await loadConnectorPresentation(connectors, ctx);
+ // A personal connector's tool rows live in the personal scope
+ const wsId = ctx.workspaceId ?? undefined;
+ const toolModel = new ConnectorToolModel(ctx.serverDB, ctx.userId, wsId, { agentRun: true });
+ const tools = await toolModel.queryAllByConnectorIds(connectors.map((c) => c.id));
+
+ return connectors.map(({ credentials: _credentials, oidcConfig, ...connector }) => ({
+ ...connector,
+ ...presentation.get(connector.id),
+ oidcConfig: oidcConfig ? { ...oidcConfig, clientSecret: undefined } : oidcConfig,
+ tools: tools.filter((tool) => tool.userConnectorId === connector.id),
+ }));
+ }),
+
+ /**
+ * The edit-read of the connector a conversation's call runs on, for a desktop
+ * that runs a stdio connector itself. The server resolves the row exactly as
+ * `callTool` does (`connectorRunScope`, then priority), so the desktop runs
+ * the account the server offered the tool from, and a private connector only
+ * in a conversation that may use it — never on the client's guess.
+ */
+ getForRun: connectorWriteProcedure
+ .input(
+ z.object({
+ agentId: z.string().optional(),
+ identifier: z.string().min(1),
+ /** The conversation the call belongs to; see `callTool`. */
+ topicId: z.string().optional(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ const [connector] = await resolveConnectorForRun(input, ctx);
+ if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
+ // Creator/owner only, like the edit-read; not gated by the member policy,
+ // which must not stop the creator running their own connector.
+ assertWorkspaceRowManageable(ctx, connector.userId, 'connector');
+ // A private agent's run may resolve its owner's personal connector, whose
+ // tool rows live in the personal scope.
+ const wsId = ctx.workspaceId ?? undefined;
+ const toolModel = new ConnectorToolModel(ctx.serverDB, ctx.userId, wsId, { agentRun: true });
+ return toConnectorEditDetail(connector, await toolModel.queryByConnector(connector.id));
+ }),
+
+ /**
+ * The OAuth access token a device-routed connector's local desktop call
+ * sends (`getConnectorLocalCallToken`).
+ *
+ * With `run`, the token of the row `getForRun` returned for that call: the
+ * row is resolved again for the conversation, so a private agent's own topic
+ * reaches its owner's personal connector (which the workspace scope alone
+ * cannot read), and a conversation that may not use a private connector never
+ * gets its token. Without it (a connector's own settings), a row of the
+ * caller's scope by id.
+ */
+ getLocalCallToken: connectorWriteProcedure
+ .input(
+ z.object({
+ id: z.string().uuid(),
+ /** The account to call as, for a connector holding several; its primary otherwise. */
+ linkId: z.string().optional(),
+ run: z
+ .object({
+ agentId: z.string().optional(),
+ identifier: z.string().min(1),
+ /** The conversation the call belongs to; see `callTool`. */
+ topicId: z.string().optional(),
+ })
+ .optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ if (!input.run) return getConnectorLocalCallToken(ctx, input.id, input.linkId);
+
+ const [connector] = await resolveConnectorForRun(input.run, ctx);
+ // The call runs another row by now (or none): its token is not this one's
+ if (connector?.id !== input.id) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
+ }
+ return getResolvedConnectorLocalCallToken(ctx, connector, input.linkId);
+ }),
+
+ /**
+ * Which connector row a conversation's call of `identifier` runs on — the
+ * row `callTool` resolves. Only the server can tell a private agent's own
+ * topic from a group, channel or another agent's one, and the approval a
+ * view's call needs and the transport it takes must follow the row that
+ * executes, not the client's guess.
+ *
+ * Besides the id it returns what routing and approval read: the row's
+ * transport, its tools, its accounts and its install state (binding, source,
+ * status and the routing fields of its metadata), the fields a member's connector list
+ * already carries, never credentials or a stdio command, so any member who
+ * can call the tool may ask. A private agent's own topic may run its owner's personal
+ * connector, which no workspace list on the client holds; the client routes
+ * that row on this answer.
+ */
+ resolveForRun: connectorProcedure
+ .input(
+ z.object({
+ agentId: z.string().optional(),
+ identifier: z.string().min(1),
+ /** The conversation the call belongs to; see `callTool`. */
+ topicId: z.string().optional(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ const [connector] = await resolveConnectorForRun(input, ctx);
+ if (!connector) return null;
+ // A personal connector's tool rows live in the personal scope
+ const wsId = ctx.workspaceId ?? undefined;
+ const toolModel = new ConnectorToolModel(ctx.serverDB, ctx.userId, wsId, { agentRun: true });
+ // Its accounts, as a member's list shows them: a local call needs to know
+ // whether the model must name one (`takeLocalConnectorAccount`)
+ const presentation = (await loadConnectorPresentation([connector], ctx)).get(connector.id);
+ return {
+ agentId: connector.agentId,
+ id: connector.id,
+ identifier: connector.identifier,
+ isEnabled: connector.isEnabled,
+ links: presentation?.links ?? [],
+ mcpConnectionType: connector.mcpConnectionType,
+ mcpServerUrl: connector.mcpServerUrl,
+ // Whether an unfinished marketplace install may run, whether a stdio
+ // install keeps running on the desktop under a device gateway
+ // (`isMarketplaceInstallRunnable`, `keepsDesktopStdioExecution`), and
+ // whether an HTTP server runs on a device, and which one
+ metadata: pickRoutingMetadata(connector.metadata),
+ sourceType: connector.sourceType,
+ status: connector.status,
+ toolIdentifier: connector.toolIdentifier,
+ tools: await toolModel.queryByConnector(connector.id),
+ };
+ }),
+
+ /**
+ * Execute a single connector tool by identifier (classic chat path). Resolves
+ * the connector, hard-blocks disabled tools, refreshes the OAuth token if
+ * needed, and calls the remote MCP server with the decrypted credentials.
+ */
+ callTool: connectorWriteProcedure
+ .input(
+ z.object({
+ /** Resolve the identifier for this agent (agent-owned connector first). */
+ agentId: z.string().optional(),
+ args: z.string().optional(),
+ /** An MCP App view's `tools/call`: only tools visible to the app run. */
+ fromApp: z.boolean().optional(),
+ fromEntrypoint: z.boolean().optional(),
+ identifier: z.string().min(1),
+ /** The account to call as, for a connector holding several. */
+ linkId: z.string().optional(),
+ /** With `fromApp`: the server the view came from (`getMcpServerFingerprint`). */
+ server: z.string().optional(),
+ toolName: z.string().min(1),
+ /**
+ * The conversation the call runs in, reported as the call's session. A
+ * private agent's own topic also lets it use its owner's private
+ * connectors; without it the call resolves the workspace's shared
+ * connectors only.
+ */
+ topicId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ return await callConnectorToolById(input, {
+ ...withRequestConnectorCallers(ctx),
+ // A private agent's call may run on its owner's personal connector,
+ // whose tool rows live in the personal scope.
+ connectorToolModel: new ConnectorToolModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ { agentRun: true },
+ ),
+ });
+ } catch (err: any) {
+ if (err instanceof ConnectorToolCallError) {
+ throw new TRPCError({ cause: err, code: err.code, message: err.message });
+ }
+ if (err instanceof TRPCError && getMCPConnectionErrorType(err.cause)) throw err;
+ throw new TRPCError({
+ cause: err,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: `Connector tool call failed: ${err?.message ?? 'unknown error'}`,
+ });
+ }
+ }),
+
+ /**
+ * Read the MCP Apps `ui://` resource a connector tool result renders with.
+ */
+ readUiResource: connectorProcedure
+ .input(
+ z.object({
+ agentId: z.string().optional(),
+ identifier: z.string().min(1),
+ /** The account the tool ran as, for a connector holding several. */
+ linkId: z.string().optional(),
+ /** The server the result came from (`getMcpServerFingerprint`). */
+ server: z.string().min(1),
+ /** The conversation the result belongs to; see `callTool`. */
+ topicId: z.string().optional(),
+ uri: z.string().startsWith('ui://'),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ try {
+ return await readConnectorUiResourceById(input, ctx);
+ } catch (err: any) {
+ if (err instanceof ConnectorToolCallError) {
+ throw new TRPCError({ cause: err, code: err.code, message: err.message });
+ }
+ throw err;
+ }
+ }),
+});
diff --git a/apps/server/src/routers/lambda/plugin.ts b/apps/server/src/routers/lambda/plugin.ts
index 606dc760298..5ebcba14e59 100644
--- a/apps/server/src/routers/lambda/plugin.ts
+++ b/apps/server/src/routers/lambda/plugin.ts
@@ -9,6 +9,7 @@ import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';
+import { redactForeignComposioLinks } from './_helpers/composioProjection';
import { recordLegacyPluginWrite } from './_helpers/legacyPluginWriteMetrics';
const pluginProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
@@ -24,6 +25,23 @@ const pluginProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =
* Legacy `user_installed_plugins` rows. Current clients install MCP servers as
* connectors (`connector.create`) and only read, update and remove rows here.
*/
+/**
+ * `customParams.composio` (a Composio account and the member it runs as) is
+ * server-owned: only the Composio connect flow writes it. Every member reads
+ * the workspace's account ids from the projection, so a client-written block
+ * could forge a "legacy" mirror of a teammate's private connection under any
+ * identifier and run it. A create drops the client's block; an update keeps
+ * the stored one.
+ */
+const withServerComposio = (
+ clientParams: unknown,
+ stored?: { composio?: unknown } | null,
+): Record<string, unknown> | undefined => {
+ if (!clientParams || typeof clientParams !== 'object') return clientParams as undefined;
+ const { composio: _client, ...rest } = clientParams as Record<string, unknown>;
+ return stored?.composio === undefined ? rest : { ...rest, composio: stored.composio };
+};
+
export const pluginRouter = router({
/**
* @deprecated Kept unchanged for released clients that still install MCPs as
@@ -48,7 +66,7 @@ export const pluginRouter = router({
// if not exist, we should create the plugin
if (!result) {
const data = await ctx.pluginModel.create({
- customParams: input.customParams,
+ customParams: withServerComposio(input.customParams),
identifier: input.identifier,
manifest: input.manifest,
settings: input.settings,
@@ -82,7 +100,7 @@ export const pluginRouter = router({
recordLegacyPluginWrite('createPlugin', input.type, ctx.clientMetadata);
const data = await ctx.pluginModel.create({
- customParams: input.customParams,
+ customParams: withServerComposio(input.customParams),
identifier: input.identifier,
manifest: input.manifest,
type: input.type,
@@ -94,7 +112,7 @@ export const pluginRouter = router({
getPlugins: wsCompatProcedure.use(serverDatabase).query(async ({ ctx }): Promise<LobeTool[]> => {
const pluginModel = new PluginModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);
- return pluginModel.query();
+ return redactForeignComposioLinks(await pluginModel.query({ forClient: true }), ctx);
}),
removePlugin: pluginProcedure
@@ -124,7 +142,10 @@ export const pluginRouter = router({
assertWorkspaceRowManageable(ctx, target.userId, 'plugin');
return ctx.pluginModel.update(input.id, {
- customParams: input.customParams,
+ customParams:
+ input.customParams === undefined
+ ? undefined
+ : withServerComposio(input.customParams, target.customParams),
manifest: input.manifest,
settings: input.settings,
});
diff --git a/apps/server/src/routers/tools/composio.agentVisibility.test.ts b/apps/server/src/routers/tools/composio.agentVisibility.test.ts
new file mode 100644
index 00000000000..549aaf2065a
--- /dev/null
+++ b/apps/server/src/routers/tools/composio.agentVisibility.test.ts
@@ -0,0 +1,204 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import {
+ agents,
+ userConnectors,
+ userConnectorTools,
+ users,
+ workspaces,
+} from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { composioToolsRouter } from './composio';
+
+const mocks = vi.hoisted(() => ({
+ processToolCallResult: vi.fn(),
+ toolsExecute: vi.fn(),
+}));
+
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(async () => testDB),
+}));
+
+vi.mock('@/libs/composio', () => ({
+ getComposioClient: () => ({ tools: { execute: mocks.toolsExecute } }),
+ isComposioClientAvailable: () => true,
+ isComposioConnectedAccountNotFoundError: () => false,
+}));
+
+vi.mock('@/server/services/mcp', () => ({
+ MCPService: { processToolCallResult: mocks.processToolCallResult },
+}));
+
+const owner = 'cav-owner';
+const mate = 'cav-mate';
+const workspaceId = 'cav-ws';
+const agentId = 'cav-agent';
+let connectorId: string;
+
+const callerFor = (userId: string) =>
+ composioToolsRouter.createCaller({ userId, workspaceId } as any);
+
+const call = {
+ agentId,
+ identifier: 'gmail',
+ toolArgs: { to: '[email protected]' },
+ toolSlug: 'GMAIL_SEND_EMAIL',
+};
+
+/**
+ * A member runs a Composio tool as an agent through the manual
+ * `tools.composio.executeAction`, which takes the agent id from the client.
+ * The agent's own Composio row (`agent_id = agentId`) is a shared workspace
+ * row, so the agent's visibility is what keeps it from a teammate.
+ */
+describe('composioToolsRouter.executeAction — agent visibility (real models)', () => {
+ beforeEach(async () => {
+ testDB = await getTestDB();
+ vi.clearAllMocks();
+ mocks.toolsExecute.mockResolvedValue({ data: 'sent' });
+ mocks.processToolCallResult.mockResolvedValue({ content: 'sent', success: true });
+
+ await testDB.delete(users).where(inArray(users.id, [owner, mate]));
+ await testDB.insert(users).values([{ id: owner }, { id: mate }]);
+ await testDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'WS', primaryOwnerId: owner, slug: workspaceId });
+ // A workspace (public) agent, with a Composio account bound to it by its owner.
+ await testDB
+ .insert(agents)
+ .values({ id: agentId, userId: owner, visibility: 'public', workspaceId });
+ const [connector] = await testDB
+ .insert(userConnectors)
+ .values({
+ agentId,
+ identifier: 'gmail',
+ metadata: { composio: { connectedAccountId: 'acc-agent', linkedByUserId: owner } },
+ name: 'Gmail',
+ sourceType: 'marketplace',
+ status: 'connected',
+ userId: owner,
+ visibility: 'public',
+ workspaceId,
+ })
+ .returning();
+ connectorId = connector.id;
+ await testDB.insert(userConnectorTools).values({
+ crudType: 'write',
+ permission: 'auto',
+ toolName: 'GMAIL_SEND_EMAIL',
+ userConnectorId: connectorId,
+ userId: owner,
+ workspaceId,
+ });
+ });
+
+ afterEach(async () => {
+ await testDB.delete(users).where(inArray(users.id, [owner, mate]));
+ });
+
+ /**
+ * @example
+ * expect(executeAction({ agentId: privatizedAgent })).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ */
+ it("stops running an agent's Composio account for a teammate once the agent is made private", async () => {
+ // ROOT CAUSE:
+ //
+ // The route handed the client's agentId to the resolver unchecked. An agent's own rows are
+ // scoped by workspace only, so a teammate who kept the id of an agent made private ran its
+ // Composio account with any tool and arguments. Only an agent the caller can see resolves.
+
+ // While the agent is a workspace agent, a teammate may run it.
+ await callerFor(mate).executeAction(call);
+ expect(mocks.toolsExecute).toHaveBeenCalledTimes(1);
+ expect(mocks.toolsExecute).toHaveBeenLastCalledWith(
+ 'GMAIL_SEND_EMAIL',
+ expect.objectContaining({ connectedAccountId: 'acc-agent', userId: owner }),
+ );
+
+ await testDB.update(agents).set({ visibility: 'private' }).where(eq(agents.id, agentId));
+
+ await expect(callerFor(mate).executeAction(call)).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ // Naming a topic does not get around it either.
+ await expect(
+ callerFor(mate).executeAction({ ...call, topicId: 'cav-any-topic' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(mocks.toolsExecute).toHaveBeenCalledTimes(1);
+
+ // The owner still runs their own private agent.
+ await callerFor(owner).executeAction(call);
+ expect(mocks.toolsExecute).toHaveBeenCalledTimes(2);
+ expect(mocks.toolsExecute).toHaveBeenLastCalledWith(
+ 'GMAIL_SEND_EMAIL',
+ expect.objectContaining({ connectedAccountId: 'acc-agent', userId: owner }),
+ );
+ });
+
+ /**
+ * @example
+ * expect(executeAction({ agentId, toolSlug: unlistedTool })).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ * expect(composio.tools.execute).not.toHaveBeenCalled();
+ */
+ it("refuses a slug missing from the agent's Composio tool list, for a teammate and the owner", async () => {
+ // ROOT CAUSE:
+ //
+ // The per-tool gate blocked only a `disabled` row. A provider tool absent from the synced
+ // rows read as allowed, so a member who saw a workspace agent sent any Gmail action, with any
+ // arguments, under the owner's account.
+ for (const userId of [mate, owner]) {
+ await expect(
+ callerFor(userId).executeAction({ ...call, toolSlug: 'GMAIL_DELETE_MESSAGE' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ }
+ expect(mocks.toolsExecute).not.toHaveBeenCalled();
+
+ // A tool the connector lists still runs.
+ await callerFor(mate).executeAction(call);
+ expect(mocks.toolsExecute).toHaveBeenCalledTimes(1);
+ });
+
+ /**
+ * @example
+ * expect(executeAction({ agentId, toolSlug: disabledTool })).resolves.toMatchObject({ success: true });
+ * expect(composio.tools.execute).not.toHaveBeenCalled();
+ */
+ it("blocks a tool disabled on the agent's Composio connector, for a teammate and the owner", async () => {
+ // ROOT CAUSE:
+ //
+ // The manual route resolved the agent's account and called Composio as its owner without the
+ // per-tool gate the runtime applies (`ToolExecutionService`), so a member who saw a workspace
+ // agent ran a tool its owner had disabled, with any arguments. The route now reads the
+ // resolved connector's tool settings and returns the runtime's blocked-tool response.
+ await testDB
+ .update(userConnectorTools)
+ .set({ permission: 'disabled' })
+ .where(eq(userConnectorTools.userConnectorId, connectorId));
+
+ for (const userId of [mate, owner]) {
+ const result = await callerFor(userId).executeAction(call);
+ expect(result).toMatchObject({
+ content: expect.stringContaining('"GMAIL_SEND_EMAIL" has been disabled'),
+ success: true,
+ });
+ }
+ // Naming the conversation does not get around it either.
+ await callerFor(mate).executeAction({ ...call, topicId: 'cav-any-topic' });
+ expect(mocks.toolsExecute).not.toHaveBeenCalled();
+
+ // Re-enabled, the same call runs the agent's account again.
+ await testDB
+ .update(userConnectorTools)
+ .set({ permission: 'auto' })
+ .where(eq(userConnectorTools.userConnectorId, connectorId));
+ await callerFor(mate).executeAction(call);
+ expect(mocks.toolsExecute).toHaveBeenCalledWith(
+ 'GMAIL_SEND_EMAIL',
+ expect.objectContaining({ connectedAccountId: 'acc-agent', userId: owner }),
+ );
+ });
+});
diff --git a/apps/server/src/routers/tools/composio.legacyProjection.test.ts b/apps/server/src/routers/tools/composio.legacyProjection.test.ts
new file mode 100644
index 00000000000..5a51f5735b0
--- /dev/null
+++ b/apps/server/src/routers/tools/composio.legacyProjection.test.ts
@@ -0,0 +1,118 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { userConnectors, users, workspaces } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { PluginModel } from '@/database/models/plugin';
+
+import { composioToolsRouter } from './composio';
+
+const mocks = vi.hoisted(() => ({
+ processToolCallResult: vi.fn(),
+ toolsExecute: vi.fn(),
+}));
+
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(async () => testDB),
+}));
+
+vi.mock('@/libs/composio', () => ({
+ getComposioClient: () => ({ tools: { execute: mocks.toolsExecute } }),
+ isComposioClientAvailable: () => true,
+ isComposioConnectedAccountNotFoundError: () => false,
+}));
+
+vi.mock('@/server/services/mcp', () => ({
+ MCPService: { processToolCallResult: mocks.processToolCallResult },
+}));
+
+const owner = 'clp-owner';
+const mate = 'clp-mate';
+const workspaceId = 'clp-ws';
+
+const callerFor = (userId: string) =>
+ composioToolsRouter.createCaller({ userId, workspaceId } as any);
+
+/** A member's plugin projection row: any member can write one, under any app. */
+const fileProjection = (userId: string, identifier: string, account: string, linker: string) =>
+ new PluginModel(testDB, userId, workspaceId).create({
+ customParams: {
+ composio: { connectedAccountId: account, linkedByUserId: linker, status: 'ACTIVE' },
+ },
+ identifier,
+ type: 'plugin',
+ });
+
+/**
+ * The legacy plugin projection (`user_installed_plugins.customParams.composio`)
+ * is written by members, so `tools.composio.executeAction` may serve it only
+ * when no connector row in the workspace runs its account.
+ */
+describe('composioToolsRouter.executeAction — legacy projection (real models)', () => {
+ beforeEach(async () => {
+ testDB = await getTestDB();
+ vi.clearAllMocks();
+ mocks.toolsExecute.mockResolvedValue({ data: 'ok' });
+ mocks.processToolCallResult.mockResolvedValue({ content: 'ok', success: true });
+
+ await testDB.delete(users).where(inArray(users.id, [owner, mate]));
+ await testDB.insert(users).values([{ id: owner }, { id: mate }]);
+ await testDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'WS', primaryOwnerId: owner, slug: workspaceId });
+ // The owner's Gmail connection, made private.
+ await testDB.insert(userConnectors).values({
+ identifier: 'gmail',
+ metadata: { composio: { connectedAccountId: 'acc-owner', linkedByUserId: owner } },
+ name: 'Gmail',
+ sourceType: 'marketplace',
+ status: 'connected',
+ userId: owner,
+ visibility: 'private',
+ workspaceId,
+ });
+ });
+
+ afterEach(async () => {
+ await testDB.delete(users).where(inArray(users.id, [owner, mate]));
+ });
+
+ /**
+ * @example
+ * expect(executeAction({ identifier: 'google-calendar' })).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ */
+ it("does not run a teammate's private account filed under another app's projection", async () => {
+ // ROOT CAUSE:
+ //
+ // A projection counted as a mirror only of connector rows with its own identifier. A member
+ // copied the private Gmail account and its linker into a projection under `google-calendar`,
+ // the Gmail row did not claim it, and it ran as a legacy connection: the route forwards any
+ // toolSlug with that account and entity to Composio.
+ await fileProjection(mate, 'google-calendar', 'acc-owner', owner);
+
+ await expect(
+ callerFor(mate).executeAction({
+ identifier: 'google-calendar',
+ toolSlug: 'GMAIL_SEND_EMAIL',
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(mocks.toolsExecute).not.toHaveBeenCalled();
+ });
+
+ it('still runs a legacy connection no connector row holds', async () => {
+ await fileProjection(mate, 'google-calendar', 'acc-mate-legacy', mate);
+
+ await callerFor(mate).executeAction({
+ identifier: 'google-calendar',
+ toolSlug: 'GOOGLECALENDAR_LIST_EVENTS',
+ });
+
+ expect(mocks.toolsExecute).toHaveBeenCalledWith(
+ 'GOOGLECALENDAR_LIST_EVENTS',
+ expect.objectContaining({ connectedAccountId: 'acc-mate-legacy', userId: mate }),
+ );
+ });
+});
diff --git a/apps/server/src/routers/tools/composio.test.ts b/apps/server/src/routers/tools/composio.test.ts
index cac74ed940e..a435e6a5127 100644
--- a/apps/server/src/routers/tools/composio.test.ts
+++ b/apps/server/src/routers/tools/composio.test.ts
@@ -4,33 +4,72 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { composioToolsRouter } from './composio';
const mocks = vi.hoisted(() => ({
- connectorQueryByIdentifiers: vi.fn(),
+ agentExistsById: vi.fn(),
+ connectorForRow: vi.fn(),
+ connectorPickLegacyMirrors: vi.fn(),
+ connectorResolveByIdentifiers: vi.fn(),
+ connectorToolQueryByConnector: vi.fn(),
isComposioNotFound: vi.fn(),
markComposioUnavailable: vi.fn(),
- pluginFindById: vi.fn(),
+ pluginQueryMirrors: vi.fn(),
processToolCallResult: vi.fn(),
toolsExecute: vi.fn(),
}));
vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(async () => ({})) }));
+// The cloud role gate, mirrored: the OSS stub lets every role through
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');
+ const rank: Record<string, number> = { admin: 2, member: 1, owner: 3, viewer: 0 };
+ return {
+ requireWorkspaceRoleWhenScoped: (minRole: string) =>
+ mod.trpc.middleware(async (opts: any) => {
+ const { workspaceId, workspaceRole } = opts.ctx;
+ if (workspaceId && (rank[workspaceRole] ?? -1) < rank[minRole]) {
+ const { TRPCError } = await import('@trpc/server');
+ throw new TRPCError({ code: 'FORBIDDEN', message: `Requires ${minRole}` });
+ }
+ return opts.next();
+ }),
+ wsCompatProcedure: mod.trpc.procedure,
+ };
+});
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn().mockImplementation(function () {
+ return { existsById: mocks.agentExistsById };
+ }),
+}));
+
vi.mock('@/database/models/connector', () => ({
ConnectorModel: vi.fn().mockImplementation(function () {
- return {
+ const model: Record<string, unknown> = {
+ forRow: mocks.connectorForRow,
+ pickLegacyComposioMirrors: mocks.connectorPickLegacyMirrors,
markComposioConnectionUnavailable: mocks.markComposioUnavailable,
- queryByIdentifiers: mocks.connectorQueryByIdentifiers,
+ resolveByIdentifiers: mocks.connectorResolveByIdentifiers,
};
+ mocks.connectorForRow.mockReturnValue(model);
+ return model;
+ }),
+}));
+
+vi.mock('@/database/models/connectorTool', () => ({
+ ConnectorToolModel: vi.fn().mockImplementation(function () {
+ return { queryByConnector: mocks.connectorToolQueryByConnector };
}),
}));
vi.mock('@/database/models/plugin', () => ({
PluginModel: vi.fn().mockImplementation(function () {
- return { findById: mocks.pluginFindById };
+ return { queryComposioMirrors: mocks.pluginQueryMirrors };
}),
}));
vi.mock('@/libs/composio', () => ({
getComposioClient: () => ({ tools: { execute: mocks.toolsExecute } }),
+ isComposioClientAvailable: () => true,
isComposioConnectedAccountNotFoundError: mocks.isComposioNotFound,
}));
@@ -43,7 +82,13 @@ const input = { identifier: 'gmail', toolArgs: { to: '[email protected]' }, toolSlug: 'GMAIL
beforeEach(() => {
vi.clearAllMocks();
- mocks.connectorQueryByIdentifiers.mockResolvedValue([]);
+ mocks.agentExistsById.mockResolvedValue(true);
+ mocks.connectorResolveByIdentifiers.mockResolvedValue([]);
+ // The resolved connector lists the tool the call names
+ mocks.connectorToolQueryByConnector.mockResolvedValue([
+ { permission: 'auto', toolName: 'GMAIL_SEND_EMAIL' },
+ ]);
+ mocks.connectorPickLegacyMirrors.mockImplementation(async (mirrors: unknown[]) => mirrors);
mocks.isComposioNotFound.mockImplementation(function (error: unknown) {
return (
typeof error === 'object' &&
@@ -53,14 +98,14 @@ beforeEach(() => {
);
});
mocks.markComposioUnavailable.mockResolvedValue(false);
- mocks.pluginFindById.mockResolvedValue(undefined);
+ mocks.pluginQueryMirrors.mockResolvedValue([]);
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([
+ mocks.connectorResolveByIdentifiers.mockResolvedValue([
{ id: 'conn-gmail', metadata: { composio: { connectedAccountId: 'ca-connector' } } },
]);
@@ -70,7 +115,9 @@ describe('composioToolsRouter.executeAction', () => {
'GMAIL_SEND_EMAIL',
expect.objectContaining({ connectedAccountId: 'ca-connector', userId: 'user-1' }),
);
- expect(mocks.pluginFindById).not.toHaveBeenCalled();
+ // No conversation is named, so only the rows any run may use resolve.
+ expect(mocks.connectorResolveByIdentifiers).toHaveBeenCalledWith(['gmail'], {});
+ expect(mocks.pluginQueryMirrors).not.toHaveBeenCalled();
});
/**
@@ -81,7 +128,7 @@ describe('composioToolsRouter.executeAction', () => {
const notFound = Object.assign(new Error('connected account not found'), {
code: 'CONNECTED_ACCOUNT_NOT_FOUND',
});
- mocks.connectorQueryByIdentifiers.mockResolvedValue([
+ mocks.connectorResolveByIdentifiers.mockResolvedValue([
{ id: 'conn-gmail', metadata: { composio: { connectedAccountId: 'ca-connector' } } },
]);
mocks.toolsExecute.mockRejectedValue(notFound);
@@ -90,6 +137,9 @@ describe('composioToolsRouter.executeAction', () => {
await expect(caller().executeAction(input)).rejects.toMatchObject({
message: 'connected account not found',
});
+ expect(mocks.connectorForRow).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'conn-gmail' }),
+ );
expect(mocks.markComposioUnavailable).toHaveBeenCalledWith('conn-gmail', 'ca-connector');
});
@@ -102,7 +152,7 @@ describe('composioToolsRouter.executeAction', () => {
//
// Tool actions can return 404 for the target resource while their connected account is healthy.
// Only Composio's explicit connected-account-not-found error may update connector health here.
- mocks.connectorQueryByIdentifiers.mockResolvedValue([
+ mocks.connectorResolveByIdentifiers.mockResolvedValue([
{ id: 'conn-gmail', metadata: { composio: { connectedAccountId: 'ca-connector' } } },
]);
mocks.toolsExecute.mockRejectedValue(
@@ -116,10 +166,14 @@ describe('composioToolsRouter.executeAction', () => {
});
it('falls back to plugin customParams when no connector projection exists', async () => {
- mocks.connectorQueryByIdentifiers.mockResolvedValue([]);
- mocks.pluginFindById.mockResolvedValue({
- customParams: { composio: { connectedAccountId: 'ca-plugin' } },
- });
+ mocks.connectorResolveByIdentifiers.mockResolvedValue([]);
+ mocks.pluginQueryMirrors.mockResolvedValue([
+ {
+ customParams: { composio: { connectedAccountId: 'ca-plugin' } },
+ identifier: 'gmail',
+ userId: 'user-2',
+ },
+ ]);
await caller().executeAction(input);
@@ -129,11 +183,131 @@ describe('composioToolsRouter.executeAction', () => {
);
});
+ /**
+ * @example
+ * expect(executeAction()).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ */
+ it('does not run the plugin mirror of a connector the caller cannot see', async () => {
+ // ROOT CAUSE:
+ //
+ // The shared-row lookup misses a connector its creator made private, and the route read
+ // that miss as a pre-connector legacy connection. The workspace-wide plugin projection
+ // still mirrors the account, so any member ran it as the creator's Composio entity.
+ mocks.connectorResolveByIdentifiers.mockResolvedValue([]);
+ mocks.connectorPickLegacyMirrors.mockResolvedValue([]);
+ mocks.pluginQueryMirrors.mockResolvedValue([
+ {
+ customParams: { composio: { connectedAccountId: 'ca-private', linkedByUserId: 'user-2' } },
+ identifier: 'gmail',
+ userId: 'user-2',
+ },
+ ]);
+
+ await expect(caller().executeAction(input)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(mocks.pluginQueryMirrors).toHaveBeenCalledWith(['gmail']);
+ expect(mocks.connectorPickLegacyMirrors).toHaveBeenCalledWith([
+ expect.objectContaining({
+ connectedAccountId: 'ca-private',
+ identifier: 'gmail',
+ ownerUserId: 'user-2',
+ }),
+ ]);
+ expect(mocks.toolsExecute).not.toHaveBeenCalled();
+ });
+
+ it('resolves the account in the conversation the call came from', async () => {
+ // ROOT CAUSE:
+ //
+ // The client runtime ran every Composio call with no conversation named, so the server
+ // resolved the workspace's shared rows only. A private agent's own Composio connection,
+ // which the server runtime runs in that agent's direct topic, came back NOT_FOUND or ran
+ // the shared account of the same app. The scope proof (the caller's own private agent and
+ // its own direct topic) stays in SQL, in `connectorRunScope`.
+ mocks.connectorResolveByIdentifiers.mockResolvedValue([
+ { id: 'conn-private', metadata: { composio: { connectedAccountId: 'ca-private' } } },
+ ]);
+
+ await caller().executeAction({ ...input, agentId: 'agt-private', topicId: 'tpc-direct' });
+
+ expect(mocks.agentExistsById).toHaveBeenCalledWith('agt-private');
+ expect(mocks.connectorResolveByIdentifiers).toHaveBeenCalledWith(['gmail'], {
+ agentId: 'agt-private',
+ topicId: 'tpc-direct',
+ });
+ expect(mocks.toolsExecute).toHaveBeenCalledWith(
+ 'GMAIL_SEND_EMAIL',
+ expect.objectContaining({ connectedAccountId: 'ca-private' }),
+ );
+ });
+
+ /**
+ * @example
+ * expect(executeAction({ agentId: hiddenAgent })).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ */
+ it('refuses to run as an agent the caller cannot see', async () => {
+ // ROOT CAUSE:
+ //
+ // The route forwarded the client's agentId to the resolver unchecked, and an agent's own
+ // rows (`agent_id = agentId`) are scoped by workspace only. A teammate who kept the id of
+ // an agent made private since ran its agent-owned Composio account with any tool and
+ // arguments. Connector calls check the agent first (`resolveConnectorForRun`).
+ mocks.agentExistsById.mockResolvedValue(false);
+ mocks.connectorResolveByIdentifiers.mockResolvedValue([
+ { id: 'conn-agent', metadata: { composio: { connectedAccountId: 'ca-agent' } } },
+ ]);
+
+ await expect(
+ caller().executeAction({ ...input, agentId: 'agt-hidden', topicId: 'tpc-any' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(mocks.agentExistsById).toHaveBeenCalledWith('agt-hidden');
+ expect(mocks.connectorResolveByIdentifiers).not.toHaveBeenCalled();
+ expect(mocks.pluginQueryMirrors).not.toHaveBeenCalled();
+ expect(mocks.toolsExecute).not.toHaveBeenCalled();
+ });
+
+ /**
+ * @example
+ * expect(executeAction({ toolSlug: 'GMAIL_DELETE_ALL' })).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ */
+ it("refuses a slug the resolved connector's tool list does not hold", async () => {
+ // ROOT CAUSE:
+ //
+ // Only a `disabled` row was blocked: a slug with no tool row passed as allowed, so a member
+ // who could resolve a workspace agent's Composio account ran any provider action under its
+ // owner's account. The synced tool rows are the full list the runtime offers.
+ mocks.connectorResolveByIdentifiers.mockResolvedValue([
+ { id: 'conn-gmail', metadata: { composio: { connectedAccountId: 'ca-connector' } } },
+ ]);
+
+ await expect(
+ caller().executeAction({ ...input, toolSlug: 'GMAIL_DELETE_ALL' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(mocks.connectorToolQueryByConnector).toHaveBeenCalledWith('conn-gmail');
+ expect(mocks.toolsExecute).not.toHaveBeenCalled();
+ });
+
it('throws NOT_FOUND when neither source has a connection', async () => {
- mocks.connectorQueryByIdentifiers.mockResolvedValue([]);
- mocks.pluginFindById.mockResolvedValue(undefined);
+ mocks.connectorResolveByIdentifiers.mockResolvedValue([]);
await expect(caller().executeAction(input)).rejects.toMatchObject({ code: 'NOT_FOUND' });
expect(mocks.toolsExecute).not.toHaveBeenCalled();
});
});
+
+describe('executeAction role gate', () => {
+ it('refuses a workspace viewer before resolving any account', async () => {
+ // Regression: a viewer named a public agent and ran its owner's
+ // agent-scoped Composio connection (e.g. GMAIL_SEND_EMAIL).
+ const viewer = composioToolsRouter.createCaller({
+ userId: 'viewer-1',
+ workspaceId: 'ws-1',
+ workspaceRole: 'viewer',
+ } as any);
+
+ await expect(viewer.executeAction({ ...input, agentId: 'agt-public' })).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ expect(mocks.connectorResolveByIdentifiers).not.toHaveBeenCalled();
+ expect(mocks.toolsExecute).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/tools/composio.ts b/apps/server/src/routers/tools/composio.ts
index bfff6b846d2..a071c427425 100644
--- a/apps/server/src/routers/tools/composio.ts
+++ b/apps/server/src/routers/tools/composio.ts
@@ -1,12 +1,19 @@
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
-import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import {
+ requireWorkspaceRoleWhenScoped,
+ wsCompatProcedure,
+} from '@/business/server/trpc-middlewares/workspaceAuth';
+import { AgentModel } from '@/database/models/agent';
import { ConnectorModel } from '@/database/models/connector';
-import { PluginModel } from '@/database/models/plugin';
+import { ConnectorToolModel } from '@/database/models/connectorTool';
+import { ConnectorToolPermission } from '@/database/schemas';
import { getComposioClient, isComposioConnectedAccountNotFoundError } from '@/libs/composio';
+import { buildBlockedToolResponse } from '@/libs/mcp/connectorPermissionCheck';
import { publicProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { ComposioService } from '@/server/services/composio';
import { MCPService } from '@/server/services/mcp';
// wsCompatProcedure (not authedProcedure): when a request carries X-Workspace-Id
@@ -21,48 +28,105 @@ const composioProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)
// 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);
+ // Visibility-aware: decides whether the caller may run a call as an agent.
+ const agentModel = new AgentModel(ctx.serverDB, ctx.userId, wsId);
const connectorModel = new ConnectorModel(ctx.serverDB, ctx.userId, wsId);
- return opts.next({ ctx: { ...ctx, composioClient, connectorModel, pluginModel } });
+ // Run-scoped like the runtime's permission gate: it reads the tools of every
+ // row a run resolves, a private agent's owner's personal row included.
+ const connectorToolModel = new ConnectorToolModel(ctx.serverDB, ctx.userId, wsId, {
+ agentRun: true,
+ });
+ const composioService = new ComposioService({
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId: wsId,
+ });
+ return opts.next({
+ ctx: {
+ ...ctx,
+ agentModel,
+ composioClient,
+ composioService,
+ connectorModel,
+ connectorToolModel,
+ },
+ });
});
export const composioToolsRouter = router({
executeAction: composioProcedure
+ // Executes tools with side effects as the connection's linker (an agent's
+ // owner, for its agent-owned row): workspace viewers are read-only, as for
+ // MCP `callTool`.
+ .use(requireWorkspaceRoleWhenScoped('member'))
.input(
z.object({
+ /** The agent the call runs for (its agent-owned connection first). */
+ agentId: z.string().optional(),
identifier: z.string(),
toolArgs: z.record(z.string(), z.unknown()).optional(),
toolSlug: z.string(),
+ /**
+ * The conversation the call belongs to. A private agent's own topic
+ * lets it use its owner's private Composio connection, as the server
+ * runtime does; without it the call resolves the workspace's shared
+ * connections only.
+ */
+ topicId: z.string().optional(),
}),
)
.mutation(async ({ ctx, input }) => {
- // 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]);
- const connectorComposio = connector?.metadata?.composio;
- let connectedAccountId = connectorComposio?.connectedAccountId;
- // The Composio user entity that OWNS the account (linked it), NOT the
- // caller. In a workspace the resolved row may belong to another member;
- // passing the caller's id fails Composio's account/entity validation.
- // `linkedByUserId` tracks the true linker (diverges from the row creator
- // when a workspace owner reconnects a member's row); fall back to the row
- // creator for legacy rows without it.
- let ownerUserId: string | undefined = connectorComposio?.linkedByUserId ?? connector?.userId;
- if (!connectedAccountId) {
- const plugin = await ctx.pluginModel.findById(input.identifier);
- const pluginComposio = plugin?.customParams?.composio;
- connectedAccountId = pluginComposio?.connectedAccountId;
- ownerUserId = pluginComposio?.linkedByUserId ?? plugin?.userId;
- }
-
- if (!connectedAccountId) {
- throw new TRPCError({
+ const notFound = () =>
+ new TRPCError({
code: 'NOT_FOUND',
message: `No Composio connection found for "${input.identifier}".`,
});
+
+ // The agent comes from the client, and an agent's own rows
+ // (`agent_id = agentId`) are scoped by workspace only: a teammate who
+ // kept the id of an agent made private since would otherwise run its
+ // agent-owned Composio account. Only an agent the caller can see may be
+ // resolved, as a connector call checks (`resolveConnectorForRun`); any
+ // other id reads as not found.
+ if (input.agentId && !(await ctx.agentModel.existsById(input.agentId))) throw notFound();
+
+ // Resolve the connected account server-side, never from a client-supplied
+ // connectedAccountId (that would let a user drive another user's
+ // connection), and through the resolver the agent runtime uses, in the
+ // conversation the call came from: it only serves a connector that run
+ // may use (the workspace's shared ones, plus the owner's private ones in
+ // their private agent's own direct topic — proven in SQL, so naming a
+ // topic the caller does not own widens nothing), and never the plugin
+ // mirror of a connector row it left out. `ownerUserId` is the Composio
+ // entity that linked the account, not the caller.
+ const account = await ctx.composioService.resolveComposioAccount(input.identifier, {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ });
+ if (!account) throw notFound();
+ const { connectedAccountId, connector, ownerUserId } = account;
+
+ // The per-tool gate the runtime applies (`ToolExecutionService`): only a
+ // tool the connector this call runs lists, and has not disabled, reaches
+ // Composio, for the agent the call names as for any other. Its synced
+ // tool rows are the complete list the runtime offers the model
+ // (`getComposioManifests`), so a slug missing from them is not a tool of
+ // this connection: forwarding it would run any provider action under the
+ // owner's account. It reads that resolved row's tools, so the gate and
+ // the execution cannot pick different rows. A legacy plugin mirror has no
+ // connector row and no per-tool settings.
+ if (connector) {
+ const tools = await ctx.connectorToolModel.queryByConnector(connector.id);
+ const tool = tools.find((t) => t.toolName === input.toolSlug);
+ if (!tool) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: `"${input.toolSlug}" is not a tool of the "${input.identifier}" Composio connection.`,
+ });
+ }
+ if (tool.permission === ConnectorToolPermission.disabled) {
+ return buildBlockedToolResponse(input.toolSlug);
+ }
}
let result: unknown;
@@ -73,15 +137,14 @@ export const composioToolsRouter = router({
// Toolkit version resolves to "latest"; allow manual execution without a
// pinned version (Composio otherwise throws ComposioToolVersionRequiredError).
dangerouslySkipVersionCheck: true,
- userId: ownerUserId ?? ctx.userId,
+ userId: ownerUserId,
});
} catch (error) {
- if (connector?.id && isComposioConnectedAccountNotFoundError(error)) {
+ if (connector && isComposioConnectedAccountNotFoundError(error)) {
try {
- await ctx.connectorModel.markComposioConnectionUnavailable(
- connector.id,
- connectedAccountId,
- );
+ await ctx.connectorModel
+ .forRow(connector)
+ .markComposioConnectionUnavailable(connector.id, connectedAccountId);
} catch {
// Preserve the remote execution error if the secondary health write fails.
}
diff --git a/apps/server/src/routers/tools/mcp.test.ts b/apps/server/src/routers/tools/mcp.test.ts
index ec047df46a6..961d209531a 100644
--- a/apps/server/src/routers/tools/mcp.test.ts
+++ b/apps/server/src/routers/tools/mcp.test.ts
@@ -3,22 +3,40 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { mcpRouter } from './mcp';
-const { mockCallTool, mockGetStreamableManifest, mockMcpAppsEnabled, mockReadUiResource } =
- vi.hoisted(() => ({
- mockCallTool: vi.fn(),
- mockGetStreamableManifest: vi.fn(),
- mockMcpAppsEnabled: vi.fn(),
- mockReadUiResource: vi.fn(),
- }));
+const {
+ mockCallTool,
+ mockGetStreamableManifest,
+ mockMcpAppsEnabled,
+ mockReadUiResource,
+ mockResolveByIdentifiers,
+ mockQueryByConnector,
+} = vi.hoisted(() => ({
+ mockQueryByConnector: vi.fn().mockResolvedValue([]),
+ mockResolveByIdentifiers: vi.fn().mockResolvedValue([]),
+ mockCallTool: vi.fn(),
+ mockGetStreamableManifest: vi.fn(),
+ mockMcpAppsEnabled: vi.fn(),
+ mockReadUiResource: vi.fn(),
+}));
vi.mock('@/server/services/mcp/featureGate', () => ({ isMcpAppsEnabled: mockMcpAppsEnabled }));
vi.mock('./_helpers', () => ({ scheduleToolCallReport: vi.fn() }));
-// Not a connector: the call skips the connector permission gate
+// Not a connector unless a test says so: the call skips the permission gate
vi.mock('@/database/models/connector', () => ({
ConnectorModel: vi.fn(function () {
- return { queryByIdentifiers: vi.fn().mockResolvedValue([]) };
+ return { resolveByIdentifiers: mockResolveByIdentifiers };
+ }),
+}));
+vi.mock('@/database/models/connectorTool', () => ({
+ ConnectorToolModel: vi.fn(function () {
+ return { queryByConnector: mockQueryByConnector };
+ }),
+}));
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn(function () {
+ return { existsById: vi.fn().mockResolvedValue(true) };
}),
}));
@@ -87,6 +105,41 @@ describe('tools mcpRouter.callTool', () => {
);
});
+describe('tools mcpRouter.callTool permission gate', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockResolveByIdentifiers.mockResolvedValue([]);
+ mockQueryByConnector.mockResolvedValue([]);
+ });
+
+ it("blocks a view's call the conversation's ranked row disables", async () => {
+ // Regression: the gate read the first base row of the identifier, so the
+ // owner's private row that a private agent's own topic runs on — and its
+ // `disabled` setting — was never consulted.
+ mockMcpAppsEnabled.mockResolvedValue(true);
+ mockResolveByIdentifiers.mockResolvedValue([{ id: 'c-private', identifier: 'notes' }]);
+ mockQueryByConnector.mockResolvedValue([{ permission: 'disabled', toolName: 'delete_note' }]);
+ const caller = mcpRouter.createCaller({ serverDB: {}, userId: 'user-1' } as any);
+
+ const result = await caller.callTool({
+ agentId: 'agt-private',
+ args: '{}',
+ fromApp: true,
+ meta: { sessionId: 'tpc-own' },
+ params: { name: 'notes', type: 'http', url: 'https://mcp.example.com/mcp' },
+ toolName: 'delete_note',
+ });
+
+ expect(mockResolveByIdentifiers).toHaveBeenCalledWith(['notes'], {
+ agentId: 'agt-private',
+ topicId: 'tpc-own',
+ });
+ expect(mockQueryByConnector).toHaveBeenCalledWith('c-private');
+ expect(String(result.content)).toContain('has been disabled');
+ expect(mockCallTool).not.toHaveBeenCalled();
+ });
+});
+
describe('tools mcpRouter.getStreamableMcpServerManifest', () => {
it.each([true, false])("discovers under the caller's mcp_apps flag (%s)", async (enabled) => {
mockMcpAppsEnabled.mockResolvedValue(enabled);
diff --git a/apps/server/src/routers/tools/mcp.ts b/apps/server/src/routers/tools/mcp.ts
index 9a1563c9c28..53701c0f886 100644
--- a/apps/server/src/routers/tools/mcp.ts
+++ b/apps/server/src/routers/tools/mcp.ts
@@ -164,13 +164,27 @@ export const mcpRouter = router({
// this specific tool has been disabled by the user. Disabled tools are still
// present in the AI manifest (so the AI knows they exist) but are hard-blocked
// here at execution time so the MCP server is never actually called.
+ //
+ // The row is the one the conversation runs the identifier on, ranked as
+ // its runs rank them: a plugin call keeps the bare identifier, and the
+ // owner's private row shadows the shared one in their private agent's own
+ // topic. Only an agent the caller can see names the run.
const connectorId = input.params.name;
if (connectorId && ctx.userId) {
const wsId = ctx.workspaceId ?? undefined;
const connectorModel = new ConnectorModel(ctx.serverDB, ctx.userId, wsId);
- const [connector] = await connectorModel.queryByIdentifiers([connectorId]);
+ const agentModel = new AgentModel(ctx.serverDB, ctx.userId, wsId);
+ const agentId =
+ input.agentId && (await agentModel.existsById(input.agentId)) ? input.agentId : undefined;
+ const [connector] = await connectorModel.resolveByIdentifiers([connectorId], {
+ agentId,
+ topicId: agentId ? input.meta?.sessionId : undefined,
+ });
if (connector) {
- const connectorToolModel = new ConnectorToolModel(ctx.serverDB, ctx.userId, wsId);
+ // A personal row's tools live in the personal scope
+ const connectorToolModel = new ConnectorToolModel(ctx.serverDB, ctx.userId, wsId, {
+ agentRun: true,
+ });
const tools = await connectorToolModel.queryByConnector(connector.id);
const tool = tools.find((t) => t.toolName === input.toolName);
if (tool?.permission === ConnectorToolPermission.disabled) {
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builderEditingGroup.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builderEditingGroup.test.ts
index 477c9111c4e..c3c3d6f8680 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.builderEditingGroup.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builderEditingGroup.test.ts
@@ -2,6 +2,7 @@ import type * as ModelBankModule from 'model-bank';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
+import { toolSetsFrom } from './helpers/connectorToolSets';
const {
mockIsResourceAuthorOrAdmin,
@@ -90,6 +91,7 @@ vi.mock('@/database/models/connector', () => ({
return {
queryByIdentifiers: vi.fn().mockResolvedValue([]),
resolveByIdentifiers: vi.fn().mockResolvedValue([]),
+ resolveToolSets: toolSetsFrom(vi.fn().mockResolvedValue([])),
};
}),
}));
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builderEditingTarget.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builderEditingTarget.test.ts
index 45c390427b5..3913b00d13a 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.builderEditingTarget.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builderEditingTarget.test.ts
@@ -2,6 +2,7 @@ import type * as ModelBankModule from 'model-bank';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
+import { toolSetsFrom } from './helpers/connectorToolSets';
const {
mockIsResourceAuthorOrAdmin,
@@ -90,6 +91,7 @@ vi.mock('@/database/models/connector', () => ({
return {
queryByIdentifiers: vi.fn().mockResolvedValue([]),
resolveByIdentifiers: vi.fn().mockResolvedValue([]),
+ resolveToolSets: toolSetsFrom(vi.fn().mockResolvedValue([])),
};
}),
}));
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
index ac60233147d..c7ed0487042 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
@@ -11,6 +11,7 @@ import { AgentRuntimeService } from '@/server/services/agentRuntime';
import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';
import { AiAgentService } from '../index';
+import { toolSetsFrom } from './helpers/connectorToolSets';
const runtimeAgentConfig = (chatConfig: Record<string, unknown>, id: string, slug: string) => ({
chatConfig,
@@ -136,6 +137,7 @@ vi.mock('@/database/models/connector', () => ({
return {
queryByIdentifiers: vi.fn().mockResolvedValue([]),
resolveByIdentifiers: vi.fn().mockResolvedValue([]),
+ resolveToolSets: toolSetsFrom(vi.fn().mockResolvedValue([])),
};
}),
}));
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts
index e57ecae947f..10c238b9231 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts
@@ -2,6 +2,7 @@ import type * as ModelBankModule from 'model-bank';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
+import { toolSetsFrom } from './helpers/connectorToolSets';
const {
mockResolveAllConnectors,
@@ -74,6 +75,7 @@ vi.mock('@/database/models/connector', () => ({
return {
resolveAll: mockResolveAllConnectors,
resolveByIdentifiers: vi.fn().mockResolvedValue([]),
+ resolveToolSets: toolSetsFrom(vi.fn().mockResolvedValue([]), mockResolveAllConnectors),
};
}),
}));
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
index 6a820814629..02bb511118a 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
@@ -5,6 +5,7 @@ import type * as ModelBankModule from 'model-bank';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
+import { toolSetsFrom } from './helpers/connectorToolSets';
const {
mockCreateOperation,
@@ -97,6 +98,7 @@ vi.mock('@/database/models/connector', () => ({
return {
queryByIdentifiers: vi.fn().mockResolvedValue([]),
resolveByIdentifiers: vi.fn().mockResolvedValue([]),
+ resolveToolSets: toolSetsFrom(vi.fn().mockResolvedValue([])),
};
}),
}));
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.disableTools.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.disableTools.test.ts
index af719044f94..9d872f390f4 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.disableTools.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.disableTools.test.ts
@@ -2,6 +2,7 @@ import type * as ModelBankModule from 'model-bank';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
+import { toolSetsFrom } from './helpers/connectorToolSets';
const {
mockCreateOperation,
@@ -72,6 +73,7 @@ vi.mock('@/database/models/connector', () => ({
return {
queryByIdentifiers: vi.fn().mockResolvedValue([]),
resolveByIdentifiers: vi.fn().mockResolvedValue([]),
+ resolveToolSets: toolSetsFrom(vi.fn().mockResolvedValue([])),
};
}),
}));
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
index 6f3e09fff7c..061704efd5d 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
@@ -2,6 +2,7 @@ import type * as ModelBankModule from 'model-bank';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
+import { toolSetsFrom } from './helpers/connectorToolSets';
const sonnetModelOverrides = () => ({
'agent-1': { model: 'claude-sonnet-4-6', provider: 'anthropic' },
@@ -94,6 +95,7 @@ vi.mock('@/database/models/connector', () => ({
return {
queryByIdentifiers: vi.fn().mockResolvedValue([]),
resolveByIdentifiers: vi.fn().mockResolvedValue([]),
+ resolveToolSets: toolSetsFrom(vi.fn().mockResolvedValue([])),
};
}),
}));
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts
index 42233bd7ccf..82c9ea560c4 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts
@@ -3,6 +3,7 @@ import type * as ModelBankModule from 'model-bank';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
+import { toolSetsFrom } from './helpers/connectorToolSets';
// Agent preferences expose skill metadata; only a topic selection requests its body.
const {
@@ -118,6 +119,7 @@ vi.mock('@/database/models/connector', () => ({
ConnectorModel: vi.fn().mockImplementation(function () {
return {
resolveByIdentifiers: mockConnectorResolveByIdentifiers,
+ resolveToolSets: toolSetsFrom(mockConnectorResolveByIdentifiers),
};
}),
}));
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts
index b98ec6095d9..280f466427e 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts
@@ -3,6 +3,7 @@ import type * as ModelBankModule from 'model-bank';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
+import { toolSetsFrom } from './helpers/connectorToolSets';
const {
mockConnectorQueryByIdentifiers,
@@ -90,6 +91,7 @@ vi.mock('@/database/models/connector', () => ({
return {
queryByIdentifiers: mockConnectorQueryByIdentifiers,
resolveByIdentifiers: mockConnectorQueryByIdentifiers,
+ resolveToolSets: toolSetsFrom(mockConnectorQueryByIdentifiers),
};
}),
}));
diff --git a/apps/server/src/services/aiAgent/__tests__/helpers/connectorToolSets.ts b/apps/server/src/services/aiAgent/__tests__/helpers/connectorToolSets.ts
new file mode 100644
index 00000000000..5ff11c1cad1
--- /dev/null
+++ b/apps/server/src/services/aiAgent/__tests__/helpers/connectorToolSets.ts
@@ -0,0 +1,20 @@
+import { vi } from 'vitest';
+
+type Resolve = (...args: any[]) => unknown;
+
+/**
+ * A `ConnectorModel.resolveToolSets` mock answering from the per-identifier
+ * mocks a test already sets up (`resolveByIdentifiers` for named identifiers,
+ * `resolveAll` otherwise). Each row is one tool set keyed by its identifier,
+ * as a shared row is; a test about same-identifier rows sets `toolIdentifier`.
+ */
+export const toolSetsFrom = (byIdentifiers?: Resolve, all?: Resolve) =>
+ vi.fn(async (target: unknown, identifiers?: string[]) => {
+ const rows = (
+ identifiers ? await byIdentifiers?.(identifiers, target) : await all?.(target)
+ ) as { identifier: string; toolIdentifier?: string }[] | undefined;
+ return (rows ?? []).map((row) => ({
+ ...row,
+ toolIdentifier: row.toolIdentifier ?? row.identifier,
+ }));
+ });
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index be911343caa..93bf3d5f7b6 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -177,7 +177,7 @@ export class AiAgentService {
this.agentService = new AgentService(db, userId, wsId);
this.messageModel = new MessageModel(db, userId, wsId, undefined, messageModelOptions);
this.connectorModel = new ConnectorModel(db, userId, wsId);
- this.connectorToolModel = new ConnectorToolModel(db, userId, wsId);
+ this.connectorToolModel = new ConnectorToolModel(db, userId, wsId, { agentRun: true });
this.pluginModel = new PluginModel(db, userId, wsId);
this.taskModel = new TaskModel(db, userId, wsId);
this.threadModel = new ThreadModel(db, userId, wsId);
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorRows.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorRows.test.ts
new file mode 100644
index 00000000000..49e291b5774
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorRows.test.ts
@@ -0,0 +1,169 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { discoverTools } from '../toolDiscovery';
+
+vi.mock('@/business/client/model-bank/loadModels', () => ({
+ loadModels: vi.fn().mockResolvedValue([]),
+}));
+vi.mock('@/database/models/aiModel', () => ({
+ AiModelModel: class {
+ findByIdAndProvider = vi.fn().mockResolvedValue(undefined);
+ },
+}));
+vi.mock('@/database/models/aiProvider', () => ({
+ AiProviderModel: class {
+ findById = vi.fn().mockResolvedValue(undefined);
+ },
+}));
+// The background stale-tool refresh reaches for the request-scoped `after()`,
+// which does not exist in a bare unit-test runtime.
+vi.mock('@/server/services/connector/refresh', () => ({
+ buildLastSyncedAtMap: vi.fn().mockReturnValue(new Map()),
+ scheduleStaleConnectorToolsRefresh: vi.fn(),
+}));
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: { isConfigured: false, queryDeviceList: vi.fn().mockResolvedValue([]) },
+}));
+// Pin the gatekeeper so the share assertions do not depend on the developer's
+// encryption key: without it discovery falls back to resolving undecrypted.
+const gateKeeper = vi.hoisted(() => ({ decrypt: () => {} }));
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { initWithEnvKey: vi.fn().mockResolvedValue(gateKeeper) },
+}));
+
+/**
+ * One connector identifier, two rows a private agent's own topic may use: the
+ * workspace's shared GitHub and the owner's private one. They connect different
+ * accounts and were synced at different times, so each is its own tool set.
+ */
+const shared = {
+ credentials: null,
+ id: 'conn-shared',
+ identifier: 'github',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example/shared',
+ metadata: {},
+ name: 'GitHub',
+ status: 'connected',
+ toolIdentifier: 'github',
+ visibility: 'public',
+};
+const mine = {
+ ...shared,
+ id: 'conn-mine',
+ mcpServerUrl: 'https://mcp.example/mine',
+ toolIdentifier: 'github-abcd1234',
+ visibility: 'private',
+};
+const tool = (userConnectorId: string, toolName: string) => ({
+ description: toolName,
+ inputSchema: { properties: {}, type: 'object' },
+ permission: 'auto',
+ toolName,
+ userConnectorId,
+});
+
+const run = (
+ plugins: unknown[],
+ options: { chatConfig?: Record<string, unknown>; rows?: unknown[] } = {},
+) =>
+ discoverTools(
+ {
+ agentDocumentsService: { hasDocuments: vi.fn().mockResolvedValue(false) },
+ composioService: { getComposioManifests: vi.fn().mockResolvedValue([]) },
+ connectorModel: {
+ resolveAll: vi.fn().mockResolvedValue([]),
+ resolveByIdentifiers: vi.fn().mockResolvedValue([]),
+ resolveToolSets: vi.fn(async (_target: unknown, ids?: string[]) =>
+ !ids || ids.includes('github') ? (options.rows ?? [mine, shared]) : [],
+ ),
+ },
+ connectorToolModel: {
+ queryAllByConnectorIds: vi
+ .fn()
+ .mockResolvedValue([
+ tool('conn-shared', 'list_issues'),
+ tool('conn-mine', 'list_issues'),
+ tool('conn-mine', 'create_issue'),
+ ]),
+ queryByConnector: vi.fn().mockResolvedValue([]),
+ },
+ db: {} as never,
+ getMarketService: vi.fn().mockResolvedValue({
+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),
+ }),
+ messageModel: { update: vi.fn() },
+ pluginModel: { query: vi.fn().mockResolvedValue([]) },
+ userId: 'owner',
+ } as never,
+ {
+ agentConfig: { chatConfig: options.chatConfig ?? {}, plugins },
+ appContext: undefined,
+ canUseDevice: false,
+ model: 'test-model',
+ prompt: 'open an issue',
+ provider: 'test-provider',
+ resolvedAgentId: 'agent-private',
+ runFacts: {
+ deviceSystemInfo: vi.fn().mockResolvedValue(undefined),
+ userPreference: vi.fn().mockResolvedValue(undefined),
+ },
+ topicId: 'tpc-own',
+ } as never,
+ {
+ disabledPluginIds: plugins.flatMap((entry) =>
+ typeof entry === 'object' && (entry as { mode?: string }).mode === 'disabled'
+ ? [(entry as { identifier: string }).identifier]
+ : [],
+ ),
+ globalMemoryEnabled: false,
+ hasMentionedAgents: false,
+ isFixedDeviceTarget: false,
+ loadHistoryMessages: vi.fn().mockResolvedValue([]),
+ throwIfExecutionAborted: vi.fn(),
+ } as never,
+ );
+
+const toolNames = (result: { tools?: { function: { name: string } }[] }) =>
+ (result.tools ?? [])
+ .map((item) => item.function.name)
+ .filter((name) => name.startsWith('github'))
+ .sort();
+
+describe('discoverTools — same-identifier connector rows', () => {
+ it('makes each row its own tool set, each executing on its own row', async () => {
+ // A connector that is on is found on demand: both rows' tool sets are in
+ // the pool the activator resolves from, each under its own prefix
+ const result = await run(['github']);
+
+ const own = result.toolManifestMap['github-abcd1234'] as any;
+ expect(own.api.map((api: { name: string }) => api.name).sort()).toEqual([
+ 'create_issue',
+ 'list_issues',
+ ]);
+ expect(own.connector).toEqual({ id: 'conn-mine', identifier: 'github' });
+ expect(own.mcpParams).toMatchObject({ name: 'github', url: 'https://mcp.example/mine' });
+ expect((result.toolManifestMap.github as any).mcpParams.url).toBe('https://mcp.example/shared');
+ });
+
+ it('offers a connector with only a private row under its own prefix', async () => {
+ // The agent's switch names the connector; with no shared row its only
+ // tool set is the private row's, which the pool still carries
+ const result = await run(['github'], { rows: [mine] });
+
+ expect(result.toolManifestMap.github).toBeUndefined();
+ expect((result.toolManifestMap['github-abcd1234'] as any)?.connector).toEqual({
+ id: 'conn-mine',
+ identifier: 'github',
+ });
+ });
+
+ it("drops every row's tool set when the agent disables the connector", async () => {
+ const result = await run([{ identifier: 'github', mode: 'disabled' }]);
+
+ expect(toolNames(result.toolsResult)).toEqual([]);
+ expect(result.toolManifestMap['github-abcd1234']).toBeUndefined();
+ expect(result.toolManifestMap.github).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorTokenRefresh.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorTokenRefresh.test.ts
index a92de45440e..4742a2e4c52 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorTokenRefresh.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorTokenRefresh.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import { refreshExpiredLinkTokens } from '@/server/services/connector/tokens';
+import { toolSetsFrom } from '../../__tests__/helpers/connectorToolSets';
import { discoverTools } from '../toolDiscovery';
vi.mock('@/business/client/model-bank/loadModels', () => ({
@@ -99,6 +100,10 @@ interface RunOptions {
const connectorModel = {
resolveAll: vi.fn(),
resolveByIdentifiers: vi.fn(),
+ resolveToolSets: toolSetsFrom(
+ (ids: string[], target: unknown) => connectorModel.resolveByIdentifiers(ids, target),
+ (target: unknown) => connectorModel.resolveAll(target),
+ ),
};
const run = (options: RunOptions = {}) => {
@@ -180,8 +185,9 @@ describe('discoverTools — connector OAuth token refresh', () => {
const result = await run({ disabledPluginIds: [XMIND] });
expect(result.toolManifestMap[XMIND]).toBeUndefined();
- expect(connectorModel.resolveAll).toHaveBeenCalledWith(
+ expect(connectorModel.resolveToolSets).toHaveBeenCalledWith(
expect.anything(),
+ undefined,
expect.anything(),
expect.arrayContaining([XMIND]),
);
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts
index 38b2b8fffc6..27d352ed2b1 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts
@@ -4,6 +4,7 @@ import { describe, expect, it, vi } from 'vitest';
import { buildToolDiscoveryConfig } from '@/server/modules/AgentRuntime/executorHelpers';
import { scheduleStaleConnectorToolsRefresh } from '@/server/services/connector/refresh';
+import { toolSetsFrom } from '../../__tests__/helpers/connectorToolSets';
import { discoverTools } from '../toolDiscovery';
const explicitConnectorInput = (toolId: string) => ({
@@ -89,6 +90,10 @@ interface RunOptions {
const connectorModel = {
resolveAll: vi.fn(),
resolveByIdentifiers: vi.fn(),
+ resolveToolSets: toolSetsFrom(
+ (ids: string[], target: unknown) => connectorModel.resolveByIdentifiers(ids, target),
+ (target: unknown) => connectorModel.resolveAll(target),
+ ),
};
const run = (options: RunOptions = {}) => {
@@ -133,6 +138,7 @@ const run = (options: RunOptions = {}) => {
prompt: '470008 呢',
provider: 'test-provider',
resolvedAgentId: 'agent-1',
+ topicId: 'tpc-1',
runFacts: {
deviceSystemInfo: vi.fn().mockResolvedValue(undefined),
userPreference: vi.fn().mockResolvedValue(undefined),
@@ -302,8 +308,9 @@ describe('discoverTools — custom MCP connector discovery', () => {
expect(result.toolManifestMap[YINGMI]).toBeUndefined();
expect(result.toolSourceMap[YINGMI]).toBeUndefined();
expect(result.toolsResult.enabledToolIds).not.toContain(YINGMI);
- expect(connectorModel.resolveAll).toHaveBeenCalledWith(
+ expect(connectorModel.resolveToolSets).toHaveBeenCalledWith(
expect.anything(),
+ undefined,
gateKeeper,
expect.arrayContaining([YINGMI]),
);
@@ -459,10 +466,11 @@ describe('discoverTools — custom MCP connector discovery', () => {
// Resolved by identifier only — never the creator's whole connector list.
expect(connectorModel.resolveAll).not.toHaveBeenCalled();
- expect(connectorModel.resolveByIdentifiers).toHaveBeenCalledWith(
+ expect(connectorModel.resolveToolSets).toHaveBeenCalledWith(
+ { agentId: 'agent-1', topicId: 'tpc-1' },
[YINGMI],
- 'agent-1',
gateKeeper,
+ [],
);
expect(result.toolManifestMap[YINGMI]).toBeDefined();
expect(result.toolSourceMap[YINGMI]).toBe('mcp');
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.featureGate.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.featureGate.test.ts
index 02c01cd2c6f..08d79495516 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.featureGate.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.featureGate.test.ts
@@ -2,6 +2,7 @@ import { DashboardIdentifier, LegacyDashboardIdentifier } from '@lobechat/builti
import type * as ModelBankModule from 'model-bank';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { toolSetsFrom } from '../../__tests__/helpers/connectorToolSets';
import { AiAgentService } from '../../index';
// Feature-flagged builtin tools must leave a server run's tool pool while
@@ -87,6 +88,7 @@ vi.mock('@/database/models/connector', () => ({
return {
queryByIdentifiers: vi.fn().mockResolvedValue([]),
resolveByIdentifiers: mockResolveByIdentifiers,
+ resolveToolSets: toolSetsFrom(mockResolveByIdentifiers),
};
}),
}));
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.installedPlugins.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.installedPlugins.test.ts
index 9917d981722..1a1adeb52bc 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.installedPlugins.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.installedPlugins.test.ts
@@ -6,6 +6,7 @@ import { describe, expect, it, vi } from 'vitest';
import { buildToolDiscoveryConfig } from '@/server/modules/AgentRuntime/executorHelpers';
+import { toolSetsFrom } from '../../__tests__/helpers/connectorToolSets';
import { discoverTools } from '../toolDiscovery';
vi.mock('@/business/client/model-bank/loadModels', () => ({
@@ -86,7 +87,10 @@ const run = (options: RunOptions = {}) => {
{
agentDocumentsService: { hasDocuments: vi.fn().mockResolvedValue(false) },
composioService: { getComposioManifests: vi.fn().mockResolvedValue([]) },
- connectorModel: { resolveByIdentifiers: vi.fn().mockResolvedValue([]) },
+ connectorModel: {
+ resolveByIdentifiers: vi.fn().mockResolvedValue([]),
+ resolveToolSets: toolSetsFrom(),
+ },
connectorToolModel: {
queryAllByConnectorIds: vi.fn().mockResolvedValue([]),
queryByConnector: vi.fn().mockResolvedValue([]),
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.parallelReads.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.parallelReads.test.ts
index 5fac4bfbd45..8e18c01c9dc 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.parallelReads.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.parallelReads.test.ts
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createServerAgentToolsEngine } from '@/server/modules/Mecha';
+import { toolSetsFrom } from '../../__tests__/helpers/connectorToolSets';
import { AiAgentService } from '../../index';
// The share-gate filter now runs at the top of `discoverTools`, before
@@ -135,6 +136,7 @@ vi.mock('@/database/models/connector', () => ({
return {
resolveAll: reads.connectors,
resolveByIdentifiers: vi.fn().mockResolvedValue([]),
+ resolveToolSets: toolSetsFrom(vi.fn().mockResolvedValue([]), reads.connectors),
};
}),
}));
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts
index fc5ba03e83d..11ebd3571e9 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createServerAgentToolsEngine } from '@/server/modules/Mecha';
+import { toolSetsFrom } from '../../__tests__/helpers/connectorToolSets';
import { AiAgentService } from '../../index';
// The share-gate filter now runs at the top of `discoverTools`, before
@@ -99,6 +100,7 @@ vi.mock('@/database/models/connector', () => ({
return {
queryByIdentifiers: vi.fn().mockResolvedValue([]),
resolveByIdentifiers: mockResolveByIdentifiers,
+ resolveToolSets: toolSetsFrom(mockResolveByIdentifiers),
};
}),
}));
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.refresh.test.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.refresh.test.ts
new file mode 100644
index 00000000000..1330f937362
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.refresh.test.ts
@@ -0,0 +1,90 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ConnectorToolModel } from '@/database/models/connectorTool';
+import type * as RefreshModule from '@/server/services/connector/refresh';
+import { scheduleStaleConnectorToolsRefresh } from '@/server/services/connector/refresh';
+
+import { scheduleConnectorRefresh } from './connectors';
+
+vi.mock('@/server/services/connector/refresh', async (importOriginal) => ({
+ ...(await importOriginal<typeof RefreshModule>()),
+ scheduleStaleConnectorToolsRefresh: vi.fn(),
+}));
+
+const sharedRow = { id: 'shared', identifier: 'team-linear', userId: 'mate', workspaceId: 'ws-1' };
+const personalRow = { id: 'personal', identifier: 'my-gmail', userId: 'user-1', workspaceId: null };
+
+const depsFor = (workspaceId: string | undefined, personalModel: object) => {
+ const connectorModel = {
+ // `ConnectorModel.forRow`: a personal row of the caller in a workspace run
+ forRow: vi.fn((row: { workspaceId: string | null }) =>
+ workspaceId && row.workspaceId === null ? personalModel : connectorModel,
+ ),
+ };
+ return {
+ connectorModel,
+ connectorToolModel: { scope: 'run' },
+ db: {},
+ userId: 'user-1',
+ workspaceId,
+ } as any;
+};
+
+const schedule = (deps: any, connectors: object[]) =>
+ scheduleConnectorRefresh(deps, {
+ connectorGateKeeper: undefined,
+ connectorsMcp: connectors as any,
+ connectorTools: [],
+ discoverableConnectorsMcp: [],
+ discoverableConnectorTools: [],
+ });
+
+describe('scheduleConnectorRefresh', () => {
+ beforeEach(() => {
+ vi.mocked(scheduleStaleConnectorToolsRefresh).mockClear();
+ });
+
+ /**
+ * @example
+ * expect(refreshedRows).toContain(ownersPersonalConnector);
+ */
+ it("refreshes a private agent's personal connector through the personal scope", () => {
+ // ROOT CAUSE:
+ //
+ // A private agent's workspace run resolves its owner's personal HTTP connector, but the
+ // stale-tool refresh dropped every personal row because the run's workspace-scoped models
+ // cannot write it. A connector used only this way never refreshed its tool list.
+ const personalModel = { scope: 'personal' };
+ const deps = depsFor('ws-1', personalModel);
+
+ schedule(deps, [sharedRow, personalRow]);
+
+ const calls = vi.mocked(scheduleStaleConnectorToolsRefresh).mock.calls;
+ expect(calls).toHaveLength(2);
+ const [inRunScope, , runContext] = calls[0];
+ expect(inRunScope.map((c) => c.id)).toEqual(['shared']);
+ expect(runContext).toMatchObject({
+ connectorModel: deps.connectorModel,
+ connectorToolModel: deps.connectorToolModel,
+ userId: 'user-1',
+ });
+ const [personal, , personalContext] = calls[1];
+ expect(personal.map((c) => c.id)).toEqual(['personal']);
+ expect(personalContext.connectorModel).toBe(personalModel);
+ expect(personalContext.connectorToolModel).toBeInstanceOf(ConnectorToolModel);
+ expect(personalContext).toMatchObject({ userId: 'user-1' });
+ });
+
+ it('refreshes every row with the run context outside a workspace', () => {
+ const deps = depsFor(undefined, { scope: 'personal' });
+
+ schedule(deps, [personalRow]);
+
+ const calls = vi.mocked(scheduleStaleConnectorToolsRefresh).mock.calls;
+ expect(calls).toHaveLength(1);
+ expect(calls[0][0].map((c) => c.id)).toEqual(['personal']);
+ expect(calls[0][2]).toMatchObject({ connectorModel: deps.connectorModel });
+ expect(deps.connectorModel.forRow).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.ts
index 78cb25c16f6..b4d4270eea9 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.ts
@@ -2,15 +2,21 @@ import type { LobeToolManifest } from '@lobechat/context-engine';
import debug from 'debug';
import pMap from 'p-map';
-import { ConnectorModel, type DecryptedConnector } from '@/database/models/connector';
+import {
+ ConnectorModel,
+ type ConnectorRunTarget,
+ type DecryptedConnector,
+} from '@/database/models/connector';
import { ConnectorToolModel } from '@/database/models/connectorTool';
import type { UserConnectorToolItem } from '@/database/schemas';
import { patchManifestWithPermissions } from '@/libs/mcp/connectorPermissionCheck';
import type { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import {
buildLastSyncedAtMap,
+ connectorSyncContextForRow,
scheduleStaleConnectorToolsRefresh,
} from '@/server/services/connector/refresh';
+import type { ConnectorToolSyncContext } from '@/server/services/connector/sync';
import {
buildConnectorOwnershipPrompt,
collectBorrowedConnectors,
@@ -100,18 +106,37 @@ export const scheduleConnectorRefresh = (
const refreshConnectorModel = params.connectorGateKeeper
? new ConnectorModel(deps.db, deps.userId, deps.workspaceId, params.connectorGateKeeper)
: deps.connectorModel;
+ const runContext = {
+ connectorModel: refreshConnectorModel,
+ connectorToolModel: deps.connectorToolModel,
+ };
// Discoverable (unpinned) connectors are refreshed too: the model can
// activate them, so a stale list would offer removed APIs and hide new ones.
- scheduleStaleConnectorToolsRefresh(
- [...params.connectorsMcp, ...params.discoverableConnectorsMcp],
- buildLastSyncedAtMap([...params.connectorTools, ...params.discoverableConnectorTools]),
- {
- connectorModel: refreshConnectorModel,
- connectorToolModel: deps.connectorToolModel,
+ const connectors = [...params.connectorsMcp, ...params.discoverableConnectorsMcp];
+ const lastSyncedAt = buildLastSyncedAtMap([
+ ...params.connectorTools,
+ ...params.discoverableConnectorTools,
+ ]);
+ // A private agent's workspace run can resolve its owner's personal
+ // connectors. Their rows live in the personal scope, which this
+ // workspace-scoped context cannot write, so they refresh through it
+ // (`connectorSyncContextForRow`); otherwise a connector the owner only uses
+ // here would keep its install-time tool list.
+ const personal = deps.workspaceId ? connectors.filter((c) => c.workspaceId === null) : [];
+ const groups: [DecryptedConnector[], ConnectorToolSyncContext | undefined][] = [
+ [connectors.filter((c) => !personal.includes(c)), runContext],
+ ];
+ if (personal.length > 0) {
+ groups.push([personal, connectorSyncContextForRow(runContext, personal[0], deps.db)]);
+ }
+ for (const [group, context] of groups) {
+ if (!context) continue;
+ scheduleStaleConnectorToolsRefresh(group, lastSyncedAt, {
+ ...context,
// Lists under this user's mcp_apps flag, so view-only tools are found too
userId: deps.userId,
- },
- );
+ });
+ }
} catch (err) {
log('execAgent: failed to schedule connector tool refresh (ignored): %O', err);
}
@@ -136,7 +161,7 @@ interface PermissionPatchTargets<P> {
*/
export const patchConnectorPermissions = async <P extends { identifier: string }>(
deps: ToolDiscoveryDeps,
- resolvedAgentId: string,
+ runTarget: ConnectorRunTarget,
targets: PermissionPatchTargets<P>,
): Promise<PermissionPatchTargets<P>> => {
let { composioManifests, lobehubSkillManifests, pluginsWithoutConnectors } = targets;
@@ -156,11 +181,13 @@ export const patchConnectorPermissions = async <P extends { identifier: string }
];
const connectorEntries =
allIdentifiers.length > 0
- ? await deps.connectorModel.resolveByIdentifiers(allIdentifiers, resolvedAgentId)
+ ? await deps.connectorModel.resolveByIdentifiers(allIdentifiers, runTarget)
: [];
if (connectorEntries.length > 0) {
- const toolModel = new ConnectorToolModel(deps.db, deps.userId, deps.workspaceId);
+ const toolModel = new ConnectorToolModel(deps.db, deps.userId, deps.workspaceId, {
+ agentRun: true,
+ });
const connectorToolsMap = new Map<string, Map<string, string>>();
await pMap(
connectorEntries,
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts
index b46d68cf353..70f805a3457 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts
@@ -22,6 +22,7 @@ import {
collectBorrowedConnectors,
} from '@/server/utils/connectorAttribution';
+import { toolSetsFrom } from '../../__tests__/helpers/connectorToolSets';
import { discoverTools } from '.';
vi.mock('@/business/client/model-bank/loadModels', () => ({
@@ -160,6 +161,9 @@ const run = (options: RunOptions = {}) => {
connectorModel: {
resolveAll: vi.fn().mockResolvedValue([]),
resolveByIdentifiers: vi.fn(async (ids: string[]) => options.connectorResolve?.(ids) ?? []),
+ resolveToolSets: toolSetsFrom(
+ async (ids: string[]) => options.connectorResolve?.(ids) ?? [],
+ ),
},
connectorToolModel: {
queryAllByConnectorIds: vi.fn().mockResolvedValue([]),
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
index a48ab693227..d3ba1fc3fe2 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
@@ -30,7 +30,7 @@ import {
resolveInvocationToolIds,
} from '@lobechat/mecha';
import type { BuiltinToolResolveContext, FrozenCredentialFacts } from '@lobechat/types';
-import { getActivePluginIds, resolveToolMode } from '@lobechat/types';
+import { getActivePluginIds, manifestBaseIdentifier, resolveToolMode } from '@lobechat/types';
import debug from 'debug';
import { loadModels } from '@/business/client/model-bank/loadModels';
@@ -350,13 +350,17 @@ export const discoverTools = async (
// 5a-1b. Model awareness: tell the model whose connected account each
// borrowed tool runs on (see `buildOwnershipNote`).
+ // Each row is named by the tool prefix the model calls it by
connectorOwnershipNote = await buildOwnershipNote(
deps,
[
- ...connectors.map((c) => connectorsMcp.find((mcp) => mcp.id === c.id) ?? c),
+ ...connectors.map((c) => ({
+ ...(connectorsMcp.find((mcp) => mcp.id === c.id) ?? c),
+ identifier: c.toolIdentifier,
+ })),
// A connector that is on is found on demand, so it is read with the
// discoverable ones; the model still needs to know whose account it is.
- ...discoverableConnectorsMcp,
+ ...discoverableConnectorsMcp.map((c) => ({ ...c, identifier: c.toolIdentifier })),
],
!!shareGate,
);
@@ -383,8 +387,9 @@ export const discoverTools = async (
// instead would let a disabled / not-yet-synced connector evict the plugin
// while contributing no tools — leaving the runtime with nothing to call.
// Unpinned connectors supersede a leftover plugin row the same way.
+ // Base identifiers: any row's tool set of a connector replaces its plugin
const connectorIdentifierSet = new Set(
- [...connectorManifests, ...discoverableConnectorManifests].map((m) => m.identifier),
+ [...connectorManifests, ...discoverableConnectorManifests].map(manifestBaseIdentifier),
);
// Filter out plugin entries that are now handled by real MCP connectors.
@@ -420,11 +425,15 @@ export const discoverTools = async (
// 5d-1. Patch Lobehub/Composio manifests AND community-MCP plugin manifests
// with connector tool permissions (see `patchConnectorPermissions`).
({ composioManifests, lobehubSkillManifests, pluginsWithoutConnectors } =
- await patchConnectorPermissions(deps, resolvedAgentId, {
- composioManifests,
- lobehubSkillManifests,
- pluginsWithoutConnectors,
- }));
+ await patchConnectorPermissions(
+ deps,
+ { agentId: resolvedAgentId, topicId: ctx.topicId },
+ {
+ composioManifests,
+ lobehubSkillManifests,
+ pluginsWithoutConnectors,
+ },
+ ));
await throwIfExecutionAborted('tool discovery');
@@ -468,7 +477,9 @@ export const discoverTools = async (
...lobehubSkillManifests,
...composioManifests,
]
- .map((item) => item.identifier)
+ // The agent's switches name the connector, not a row's tool prefix: the
+ // tools engine expands a connector to every row's tool set
+ .map((item) => manifestBaseIdentifier(item))
.filter((id) => !disabledPluginIdSet.has(id));
agentPlugins = applyConnectorActivation(agentPlugins, connectorIds, connectorActivation);
if (agentConfig.chatConfig?.toolMode === 'custom') {
@@ -547,10 +558,19 @@ export const discoverTools = async (
// excluded from their manifests too — otherwise the disabled tool stays
// discoverable/activatable via these additionalManifests even though
// `installedPlugins` above already dropped it.
- const dropDisabledManifests = <T extends { identifier: string }>(manifests: T[]): T[] =>
+ // A connector row's tool set is disabled with its connector
+ const dropDisabledManifests = <
+ T extends { connector?: { identifier: string } | null; identifier: string },
+ >(
+ manifests: T[],
+ ): T[] =>
disabledPluginIdSet.size === 0
? manifests
- : manifests.filter((m) => !disabledPluginIdSet.has(m.identifier));
+ : manifests.filter(
+ (m) =>
+ !disabledPluginIdSet.has(m.identifier) &&
+ !disabledPluginIdSet.has(manifestBaseIdentifier(m)),
+ );
const activeLobehubSkillManifests = dropDisabledManifests(lobehubSkillManifests);
const activeComposioManifests = dropDisabledManifests(composioManifests);
const activeConnectorManifests = dropDisabledManifests(connectorManifests);
@@ -727,9 +747,10 @@ export const discoverTools = async (
...installedPlugins
.filter((plugin) => plugin.customParams?.mcp?.type === 'stdio')
.map((plugin) => plugin.identifier),
+ // The tool prefix the call names (a private row's differs)
...[...connectorsMcp, ...discoverableConnectorsMcp]
.filter((connector) => connector.mcpConnectionType === 'stdio')
- .map((connector) => connector.identifier),
+ .map((connector) => connector.toolIdentifier),
],
}),
);
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts
index ec0297bc610..3e7272c9cde 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts
@@ -15,6 +15,7 @@ import type { UserConnectorToolItem } from '@/database/schemas';
import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import {
+ connectorLinksContextForRow,
loadConnectorLinksMap,
pickPrimaryLink,
withLinkCredentials,
@@ -124,20 +125,21 @@ const CONNECTOR_REFRESH_CONCURRENCY = 5;
* expired OAuth tokens first. Rotated credentials are persisted encrypted,
* which needs the gatekeeper; without one, keep the stored tokens.
*/
-const refreshConnectorTokens = async (
+const refreshConnectorTokens = async <T extends DecryptedConnector>(
deps: ToolDiscoveryDeps,
gateKeeper: KeyVaultsGateKeeper | undefined,
- connectors: DecryptedConnector[],
+ connectors: T[],
onTimeout: () => void,
anonymous = false,
-): Promise<DecryptedConnector[]> => {
+): Promise<T[]> => {
if (!gateKeeper || connectors.length === 0) return connectors;
const model = new ConnectorModel(deps.db, deps.userId, deps.workspaceId, gateKeeper);
const linksContext = { connectorModel: model };
const map = await loadConnectorLinksMap(connectors, linksContext);
return pMap(
connectors,
- async (connector) => {
+ // Every row keeps what it was resolved with (its tool prefix among them)
+ async (connector): Promise<T> => {
const links = map.get(connector.id) ?? [];
const choices = links.map(({ id, name, userId }, index) => ({
id,
@@ -147,18 +149,29 @@ const refreshConnectorTokens = async (
if (links.length > 1) return { ...connector, credentials: null, links: choices };
const primary = pickPrimaryLink(links);
if (primary) {
- const [fresh] = await refreshExpiredLinkTokens(connector, [primary], model, { onTimeout });
- return { ...withLinkCredentials(connector, fresh), links: choices };
+ // A private agent's personal connector refreshes in its own scope
+ const rowContext = connectorLinksContextForRow(linksContext, connector);
+ const [fresh] = await refreshExpiredLinkTokens(
+ connector,
+ [primary],
+ rowContext.connectorModel,
+ { onTimeout },
+ );
+ return { ...connector, ...withLinkCredentials(connector, fresh), links: choices };
}
- return (await refreshExpiredConnectorTokens([connector], model, { onTimeout }))[0];
+ const [fresh] = await refreshExpiredConnectorTokens([connector], model, { onTimeout });
+ return { ...connector, ...fresh };
},
{ concurrency: CONNECTOR_REFRESH_CONCURRENCY },
);
};
+/** A connector row the run resolved, with its tool prefix (`resolveToolSets`). */
+type RunConnector = DecryptedConnector & { toolIdentifier: string };
+
/** Drop unfinished marketplace installs (see `isMarketplaceInstallRunnable`). */
-const filterInstalledMarketplaceConnectors = (
- connectors: DecryptedConnector[],
+const filterInstalledMarketplaceConnectors = <T extends DecryptedConnector>(
+ connectors: T[],
installedIds: Set<string>,
) =>
connectors.filter((connector) =>
@@ -194,10 +207,12 @@ const readConnectors = async (
installedPluginIds,
);
const [resolved, installedIds] = await Promise.all([
+ // One tool set per row: a private agent's own topic keeps the owner's
+ // private and personal rows beside the shared one of an identifier
candidateIds.length > 0
- ? deps.connectorModel.resolveByIdentifiers(
+ ? deps.connectorModel.resolveToolSets(
+ { agentId: resolvedAgentId, topicId: ctx.topicId },
candidateIds,
- resolvedAgentId,
connectorGateKeeper,
)
: [],
@@ -266,7 +281,7 @@ const readDiscoverableConnectors = async (
onRefreshTimeout: () => void,
installedPluginIds: Promise<Set<string>>,
): Promise<{
- connectorsMcp: DecryptedConnector[];
+ connectorsMcp: RunConnector[];
manifests: LobeToolManifest[];
tools: UserConnectorToolItem[];
}> => {
@@ -281,13 +296,14 @@ const readDiscoverableConnectors = async (
? [...discoverableIds].filter((identifier) => !candidates.has(identifier))
: undefined;
if (unresolvedIds?.length === 0) return none;
+ // One tool set per row, in the run's conversation (see `readConnectors`)
const [resolved, installedIds] = await Promise.all([
- unresolvedIds
- ? deps.connectorModel.resolveByIdentifiers(unresolvedIds, ctx.resolvedAgentId, gateKeeper)
- : deps.connectorModel.resolveAll(ctx.resolvedAgentId, gateKeeper, [
- ...candidates,
- ...(ctx.disabledPluginIds ?? []),
- ]),
+ deps.connectorModel.resolveToolSets(
+ { agentId: ctx.resolvedAgentId, topicId: ctx.topicId },
+ unresolvedIds,
+ gateKeeper,
+ unresolvedIds ? [] : [...candidates, ...(ctx.disabledPluginIds ?? [])],
+ ),
installedPluginIds,
]);
const connectorsMcp = filterInstalledMarketplaceConnectors(resolved, installedIds).filter(
@@ -529,7 +545,7 @@ export const startToolReads = (deps: ToolDiscoveryDeps, ctx: ToolReadsContext) =
? Promise.resolve<LobeToolManifest[]>([])
: traceDiscoveryStage('composio', () =>
deps.composioService.getComposioManifests(
- ctx.resolvedAgentId,
+ { agentId: ctx.resolvedAgentId, topicId: ctx.topicId },
ctx.shareGrantedExtensionIds && { identifiers: [...ctx.shareGrantedExtensionIds] },
),
)
diff --git a/apps/server/src/services/channel/README.md b/apps/server/src/services/channel/README.md
index 8feaed766e1..1c4dda915fe 100644
--- a/apps/server/src/services/channel/README.md
+++ b/apps/server/src/services/channel/README.md
@@ -8,7 +8,7 @@ replies never trigger another classification.
## Enable
-Configure a TypeSafe API key through the deployment's \`TYPESAFE_API_KEY\` environment variable,
+Configure a TypeSafe API key through the deployment's \`TYPESAFE\_API\_KEY\` environment variable,
or in the sender's provider settings (workspace provider settings in workspace scope).
Routing is enabled by default. Configure its switch and decision model in Settings → Service Models → Advanced → Channels:
diff --git a/apps/server/src/services/composio/index.test.ts b/apps/server/src/services/composio/index.test.ts
index 0c01cb15b7d..d7bb3134037 100644
--- a/apps/server/src/services/composio/index.test.ts
+++ b/apps/server/src/services/composio/index.test.ts
@@ -3,13 +3,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ComposioService } from './index';
const mocks = vi.hoisted(() => ({
+ connectorPickLegacyMirrors: vi.fn(),
connectorQuery: vi.fn(),
connectorQueryByIdentifiers: vi.fn(),
connectorToolQueryAll: vi.fn(),
isClientAvailable: vi.fn(),
isComposioNotFound: vi.fn(),
markComposioUnavailable: vi.fn(),
- pluginFindById: vi.fn(),
pluginQuery: vi.fn(),
toolsExecute: vi.fn(),
}));
@@ -22,6 +22,10 @@ vi.mock('@/database/models/connector', () => ({
// own connectorAgentScope tests).
resolveAll: mocks.connectorQuery,
resolveByIdentifiers: mocks.connectorQueryByIdentifiers,
+ // Health writes follow the resolved row's own scope; the scoped model is
+ // an implementation detail here, the call itself is what the test asserts.
+ forRow: () => ({ markComposioConnectionUnavailable: mocks.markComposioUnavailable }),
+ pickLegacyComposioMirrors: mocks.connectorPickLegacyMirrors,
markComposioConnectionUnavailable: mocks.markComposioUnavailable,
};
}),
@@ -37,10 +41,7 @@ vi.mock('@/database/models/connectorTool', () => ({
vi.mock('@/database/models/plugin', () => ({
PluginModel: vi.fn().mockImplementation(function () {
- return {
- findById: mocks.pluginFindById,
- query: mocks.pluginQuery,
- };
+ return { queryComposioMirrors: mocks.pluginQuery };
}),
}));
@@ -52,6 +53,26 @@ vi.mock('@/libs/composio', () => ({
const service = () => new ComposioService({ db: {} as any, userId: 'user-1' });
+/** Legacy plugin-projection rows; the query filters by identifier like the SQL does. */
+const mockPlugins = (rows: Record<string, any>[]) =>
+ mocks.pluginQuery.mockImplementation(async (identifiers?: string[]) =>
+ rows.filter((row) => !identifiers || identifiers.includes(row.identifier)),
+ );
+
+const pluginRow = (
+ identifier: string,
+ composio: Record<string, unknown> = {},
+ overrides: Record<string, any> = {},
+) => ({
+ customParams: {
+ composio: { connectedAccountId: `ca-${identifier}`, status: 'ACTIVE', ...composio },
+ },
+ identifier,
+ manifest: { api: [{ name: `${identifier.toUpperCase()}_TOOL` }], meta: {} },
+ userId: 'owner-plugin',
+ ...overrides,
+});
+
const activeConnectorRow = (overrides: Record<string, any> = {}) => ({
id: 'conn-gmail',
identifier: 'gmail',
@@ -76,11 +97,11 @@ beforeEach(() => {
);
});
mocks.markComposioUnavailable.mockResolvedValue(false);
+ mocks.connectorPickLegacyMirrors.mockImplementation(async (mirrors: unknown[]) => mirrors);
mocks.connectorQuery.mockResolvedValue([]);
mocks.connectorQueryByIdentifiers.mockResolvedValue([]);
mocks.connectorToolQueryAll.mockResolvedValue([]);
- mocks.pluginQuery.mockResolvedValue([]);
- mocks.pluginFindById.mockResolvedValue(undefined);
+ mockPlugins([]);
});
describe('ComposioService.getComposioManifests', () => {
@@ -111,13 +132,7 @@ describe('ComposioService.getComposioManifests', () => {
mocks.connectorToolQueryAll.mockResolvedValue([
{ description: 'Send', toolName: 'GMAIL_SEND_EMAIL', userConnectorId: 'conn-gmail' },
]);
- mocks.pluginQuery.mockResolvedValue([
- {
- customParams: { composio: { status: 'ACTIVE' } },
- identifier: 'slack',
- manifest: { api: [{ name: 'SLACK_POST' }] },
- },
- ]);
+ mockPlugins([pluginRow('slack')]);
const manifests = await service().getComposioManifests('agent-1', {
identifiers: ['gmail', 'not-composio'],
@@ -141,15 +156,17 @@ describe('ComposioService.getComposioManifests', () => {
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' },
+ mockPlugins([
+ pluginRow(
+ 'slack',
+ {},
+ {
+ manifest: {
+ api: [{ description: 'post', name: 'SLACK_POST', parameters: { type: 'object' } }],
+ meta: { avatar: '☁️', title: 'Slack' },
+ },
},
- },
+ ),
]);
const manifests = await service().getComposioManifests();
@@ -159,24 +176,56 @@ describe('ComposioService.getComposioManifests', () => {
expect(manifests[0].api[0].name).toBe('SLACK_POST');
});
+ it('does not fall back to the plugin projection when a connector row exists but the run cannot see it', async () => {
+ // A shared Composio connector switched to private: runtime resolution leaves
+ // it out, and the mirrored plugin row must not serve it instead.
+ mocks.connectorQuery.mockResolvedValue([]);
+ mocks.connectorPickLegacyMirrors.mockResolvedValue([]);
+ mockPlugins([pluginRow('gmail', { linkedByUserId: 'creator' })]);
+
+ const manifests = await service().getComposioManifests();
+
+ expect(manifests).toEqual([]);
+ expect(mocks.connectorPickLegacyMirrors).toHaveBeenCalledWith([
+ expect.objectContaining({
+ connectedAccountId: 'ca-gmail',
+ identifier: 'gmail',
+ ownerUserId: 'creator',
+ }),
+ ]);
+ });
+
+ it('advertises a legacy connection next to a projection row a connector claims', async () => {
+ // A teammate's private Composio connection leaves its own projection row
+ // for the same app. Only that row is the connector's mirror; the
+ // workspace's legacy connection stays available to everyone else.
+ const claimed = pluginRow(
+ 'gmail',
+ { connectedAccountId: 'ca-teammate-private' },
+ { manifest: { api: [{ name: 'GMAIL_PRIVATE' }], meta: {} }, userId: 'teammate' },
+ );
+ const legacy = pluginRow('gmail', { connectedAccountId: 'ca-legacy' });
+ mockPlugins([claimed, legacy]);
+ mocks.connectorPickLegacyMirrors.mockImplementation(async (mirrors: any[]) =>
+ mirrors.filter((mirror) => mirror.plugin !== claimed),
+ );
+
+ const manifests = await service().getComposioManifests();
+
+ expect(manifests).toHaveLength(1);
+ expect(manifests[0].api[0].name).toBe('GMAIL_TOOL');
+ });
+
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([
+ mockPlugins([
// Same identifier as the connector → must be dropped (connector wins).
- {
- customParams: { composio: { status: 'ACTIVE' } },
- identifier: 'gmail',
- manifest: { api: [{ name: 'GMAIL_OLD' }], meta: {} },
- },
+ pluginRow('gmail', {}, { manifest: { api: [{ name: 'GMAIL_OLD' }], meta: {} } }),
// Distinct identifier → included via fallback.
- {
- customParams: { composio: { status: 'ACTIVE' } },
- identifier: 'slack',
- manifest: { api: [{ name: 'SLACK_POST' }], meta: {} },
- },
+ pluginRow('slack', {}, { manifest: { api: [{ name: 'SLACK_POST' }], meta: {} } }),
]);
const manifests = await service().getComposioManifests();
@@ -253,7 +302,7 @@ describe('ComposioService.executeComposioTool', () => {
expect.objectContaining({ connectedAccountId: 'ca-connector', userId: 'user-1' }),
);
// connector hit → plugin fallback not consulted
- expect(mocks.pluginFindById).not.toHaveBeenCalled();
+ expect(mocks.pluginQuery).not.toHaveBeenCalled();
});
/**
@@ -345,10 +394,7 @@ describe('ComposioService.executeComposioTool', () => {
it('falls back to plugin customParams when the connector has no account', async () => {
mocks.connectorQueryByIdentifiers.mockResolvedValue([]);
- mocks.pluginFindById.mockResolvedValue({
- customParams: { composio: { connectedAccountId: 'ca-plugin' } },
- userId: 'owner-plugin',
- });
+ mockPlugins([pluginRow('gmail', { connectedAccountId: 'ca-plugin' })]);
mocks.toolsExecute.mockResolvedValue({ data: 'sent' });
const result = await service().executeComposioTool(params);
@@ -360,9 +406,35 @@ describe('ComposioService.executeComposioTool', () => {
);
});
+ it('runs the legacy connection, not a projection row a connector claims', async () => {
+ mocks.connectorQueryByIdentifiers.mockResolvedValue([]);
+ const claimed = pluginRow(
+ 'gmail',
+ { connectedAccountId: 'ca-teammate-private', linkedByUserId: 'teammate' },
+ { userId: 'teammate' },
+ );
+ mockPlugins([
+ claimed,
+ pluginRow('gmail', { connectedAccountId: 'ca-pending', status: 'PENDING' }),
+ pluginRow('gmail', { connectedAccountId: 'ca-legacy', linkedByUserId: 'linker' }),
+ ]);
+ mocks.connectorPickLegacyMirrors.mockImplementation(async (mirrors: any[]) =>
+ mirrors.filter((mirror) => mirror.plugin !== claimed),
+ );
+ mocks.toolsExecute.mockResolvedValue({ data: 'sent' });
+
+ const result = await service().executeComposioTool(params);
+
+ expect(result.success).toBe(true);
+ // An active legacy connection wins over a pending one.
+ expect(mocks.toolsExecute).toHaveBeenCalledWith(
+ 'GMAIL_SEND_EMAIL',
+ expect.objectContaining({ connectedAccountId: 'ca-legacy', userId: 'linker' }),
+ );
+ });
+
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);
diff --git a/apps/server/src/services/composio/index.ts b/apps/server/src/services/composio/index.ts
index 275e7a1886f..0894e19ad8d 100644
--- a/apps/server/src/services/composio/index.ts
+++ b/apps/server/src/services/composio/index.ts
@@ -1,12 +1,12 @@
import { COMPOSIO_APP_TYPES } from '@lobechat/const';
import type { LobeToolManifest } from '@lobechat/context-engine';
import type { LobeChatDatabase } from '@lobechat/database';
+import type { ResolvedConnectorRef } from '@lobechat/types';
import debug from 'debug';
-import { ConnectorModel } from '@/database/models/connector';
+import { ConnectorModel, type ConnectorRunTarget } 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,
@@ -14,9 +14,9 @@ import {
} from '@/libs/composio';
import { type ToolExecutionResult } from '@/server/services/toolExecution/types';
-const log = debug('lobe-server:composio-service');
+import { selectLegacyComposioMirrors, VALID_COMPOSIO_IDENTIFIERS } from './legacyMirrors';
-const VALID_COMPOSIO_IDENTIFIERS = new Set(COMPOSIO_APP_TYPES.map((type) => type.identifier));
+const log = debug('lobe-server:composio-service');
export interface ComposioToolExecuteParams {
/**
@@ -28,6 +28,11 @@ export interface ComposioToolExecuteParams {
args: Record<string, any>;
identifier: string;
toolSlug: string;
+ /**
+ * The topic the run writes into. A private agent's own topic lets it use its
+ * owner's private Composio connection (see `ConnectorRunTarget`).
+ */
+ topicId?: string;
}
export interface ComposioServiceOptions {
@@ -66,7 +71,7 @@ export class ComposioService {
// connector model's resolve* methods.
this.pluginModel = new PluginModel(db, userId, workspaceId);
this.connectorModel = new ConnectorModel(db, userId, workspaceId);
- this.connectorToolModel = new ConnectorToolModel(db, userId, workspaceId);
+ this.connectorToolModel = new ConnectorToolModel(db, userId, workspaceId, { agentRun: true });
}
log(
@@ -79,9 +84,9 @@ export class ComposioService {
}
async executeComposioTool(params: ComposioToolExecuteParams): Promise<ToolExecutionResult> {
- const { identifier, toolSlug, args, agentId } = params;
+ const { identifier, toolSlug, args, agentId, topicId } = params;
let resolvedConnectedAccountId: string | undefined;
- let resolvedConnectorId: string | undefined;
+ let resolvedConnector: ResolvedConnectorRef | undefined;
log('executeComposioTool: %s/%s with args: %O', identifier, toolSlug, args);
@@ -116,7 +121,7 @@ export class ComposioService {
}
try {
- const account = await this.resolveComposioAccount(identifier, agentId);
+ const account = await this.resolveComposioAccount(identifier, { agentId, topicId });
if (!account) {
return {
content: `Composio configuration not found for server "${identifier}"`,
@@ -130,7 +135,7 @@ export class ComposioService {
const { connectedAccountId, ownerUserId } = account;
resolvedConnectedAccountId = connectedAccountId;
- resolvedConnectorId = account.connectorId;
+ resolvedConnector = account.connector;
log(
'executeComposioTool: calling Composio API with connectedAccountId=%s, ownerUserId=%s',
@@ -179,15 +184,17 @@ export class ComposioService {
const err = error as Error;
if (
resolvedConnectedAccountId &&
- resolvedConnectorId &&
+ resolvedConnector &&
this.connectorModel &&
isComposioConnectedAccountNotFoundError(error)
) {
try {
- await this.connectorModel.markComposioConnectionUnavailable(
- resolvedConnectorId,
- resolvedConnectedAccountId,
- );
+ // The row may live in another scope than this service's (a private
+ // agent resolving its owner's personal row): write the health state
+ // through the row's own model, or the update silently matches nothing.
+ await this.connectorModel
+ .forRow(resolvedConnector)
+ .markComposioConnectionUnavailable(resolvedConnector.id, resolvedConnectedAccountId);
} catch (healthError) {
// Persisting connector health must not replace the original remote tool error.
log('executeComposioTool: failed to persist connector health: %O', healthError);
@@ -222,37 +229,46 @@ export class ComposioService {
* actually linked the current account) and falls back to the row creator
* (`userId`) for rows written before that field existed — the two diverge when
* a workspace owner reconnects a member-created connector.
+ *
+ * Every path that runs a Composio account resolves it here (the agent
+ * runtime and the manual `tools.composio.executeAction`), so a connector the
+ * caller may not use is not served from its plugin mirror on any of them.
*/
- private async resolveComposioAccount(
+ async resolveComposioAccount(
identifier: string,
- agentId?: string,
+ target: ConnectorRunTarget,
): Promise<
- { connectedAccountId: string; connectorId?: string; ownerUserId: string } | undefined
+ | {
+ connectedAccountId: string;
+ connector?: ResolvedConnectorRef;
+ ownerUserId: string;
+ }
+ | undefined
> {
if (this.connectorModel) {
- const [connector] = await this.connectorModel.resolveByIdentifiers([identifier], agentId);
+ const [connector] = await this.connectorModel.resolveByIdentifiers([identifier], target);
const composio = connector?.metadata?.composio;
if (composio?.connectedAccountId) {
return {
connectedAccountId: composio.connectedAccountId,
- connectorId: connector.id,
+ connector: {
+ id: connector.id,
+ userId: connector.userId,
+ workspaceId: connector.workspaceId,
+ },
ownerUserId: composio.linkedByUserId ?? connector.userId ?? this.userId!,
};
}
}
- if (this.pluginModel) {
- const plugin = await this.pluginModel.findById(identifier);
- const composio = plugin?.customParams?.composio;
- if (composio?.connectedAccountId) {
- return {
- connectedAccountId: composio.connectedAccountId,
- ownerUserId: composio.linkedByUserId ?? plugin?.userId ?? this.userId!,
- };
- }
- }
+ if (!this.pluginModel) return undefined;
- return undefined;
+ const [mirror] = await selectLegacyComposioMirrors(
+ await this.pluginModel.queryComposioMirrors([identifier]),
+ this.connectorModel,
+ );
+ if (!mirror) return undefined;
+ return { connectedAccountId: mirror.connectedAccountId, ownerUserId: mirror.ownerUserId };
}
/**
@@ -261,7 +277,7 @@ export class ComposioService {
* grant.
*/
async getComposioManifests(
- agentId?: string,
+ target: ConnectorRunTarget = {},
options?: { identifiers?: string[] },
): Promise<LobeToolManifest[]> {
const manifests: LobeToolManifest[] = [];
@@ -277,8 +293,8 @@ export class ComposioService {
if (this.connectorModel && this.connectorToolModel) {
try {
const connectors = identifiers
- ? await this.connectorModel.resolveByIdentifiers(identifiers, agentId)
- : await this.connectorModel.resolveAll(agentId);
+ ? await this.connectorModel.resolveByIdentifiers(identifiers, target)
+ : await this.connectorModel.resolveAll(target);
const composioConnectors = connectors.filter(
(c) =>
VALID_COMPOSIO_IDENTIFIERS.has(c.identifier) &&
@@ -290,7 +306,7 @@ export class ComposioService {
const tools = await this.connectorToolModel.queryAllByConnectorIds(
composioConnectors.map((c) => c.id),
);
- const toolsByConnector = new Map<string, UserConnectorToolItem[]>();
+ const toolsByConnector = new Map<string, typeof tools>();
for (const tool of tools) {
const list = toolsByConnector.get(tool.userConnectorId) ?? [];
list.push(tool);
@@ -335,20 +351,20 @@ export class ComposioService {
// 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.
+ // created before dual-write, so no migration is needed. The same legacy
+ // connection resolveComposioAccount runs: an active projection row no
+ // connector row stands behind, one per app.
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) &&
- (!identifiers || identifiers.includes(plugin.identifier)),
+ const plugins = (await this.pluginModel.queryComposioMirrors(identifiers)).filter(
+ (plugin) => !coveredIdentifiers.has(plugin.identifier),
);
+ const mirrors = await selectLegacyComposioMirrors(plugins, this.connectorModel);
- for (const plugin of composioPlugins) {
- if (!plugin.manifest) continue;
+ for (const { plugin } of mirrors) {
+ if (plugin.customParams?.composio?.status !== 'ACTIVE') continue;
+ if (coveredIdentifiers.has(plugin.identifier) || !plugin.manifest) continue;
+ coveredIdentifiers.add(plugin.identifier);
const appType = COMPOSIO_APP_TYPES.find((t) => t.identifier === plugin.identifier);
manifests.push({
diff --git a/apps/server/src/services/composio/legacyMirrors.ts b/apps/server/src/services/composio/legacyMirrors.ts
new file mode 100644
index 00000000000..c1862078618
--- /dev/null
+++ b/apps/server/src/services/composio/legacyMirrors.ts
@@ -0,0 +1,53 @@
+import { COMPOSIO_APP_TYPES } from '@lobechat/const';
+import type { CustomPluginParams } from '@lobechat/types';
+
+import type { ComposioPluginMirror, ConnectorModel } from '@/database/models/connector';
+
+export const VALID_COMPOSIO_IDENTIFIERS = new Set(
+ COMPOSIO_APP_TYPES.map((type) => type.identifier),
+);
+
+/**
+ * The legacy plugin projection rows (`user_installed_plugins.customParams.composio`)
+ * a run may use, active ones first.
+ *
+ * A workspace keeps one projection row per member for the same app, and a
+ * row can mirror a connector this run did not resolve (a private connector
+ * read by another member, another agent's row): using it would resurrect the
+ * very connection the run may not use. Only a legacy connection — no
+ * connector row behind its account — is served from the projection
+ * (see `ConnectorModel.pickLegacyComposioMirrors`).
+ *
+ * Shared by every reader of the projection (tool manifests, account
+ * resolution, connected-service facts), so they agree on what is connected.
+ */
+export const selectLegacyComposioMirrors = async <
+ T extends {
+ customParams?: CustomPluginParams | null;
+ identifier: string;
+ userId: string;
+ },
+>(
+ plugins: T[],
+ connectorModel: Pick<ConnectorModel, 'pickLegacyComposioMirrors'> | undefined,
+): Promise<(ComposioPluginMirror & { plugin: T })[]> => {
+ const mirrors = plugins.flatMap((plugin) => {
+ const composio = plugin.customParams?.composio;
+ if (!VALID_COMPOSIO_IDENTIFIERS.has(plugin.identifier) || !composio?.connectedAccountId) {
+ return [];
+ }
+ return [
+ {
+ connectedAccountId: composio.connectedAccountId,
+ identifier: plugin.identifier,
+ ownerUserId: composio.linkedByUserId ?? plugin.userId,
+ plugin,
+ },
+ ];
+ });
+
+ const legacy = connectorModel ? await connectorModel.pickLegacyComposioMirrors(mirrors) : mirrors;
+ const isActive = (mirror: (typeof legacy)[number]) =>
+ mirror.plugin.customParams?.composio?.status === 'ACTIVE';
+ return [...legacy.filter(isActive), ...legacy.filter((mirror) => !isActive(mirror))];
+};
diff --git a/apps/server/src/services/connector/exec.boundDevice.test.ts b/apps/server/src/services/connector/exec.boundDevice.test.ts
index 4a2b50052c2..e0082df0a32 100644
--- a/apps/server/src/services/connector/exec.boundDevice.test.ts
+++ b/apps/server/src/services/connector/exec.boundDevice.test.ts
@@ -50,6 +50,10 @@ const makeCtx = (connector: any, links: any[] = []) =>
({
agentModel: { existsById: vi.fn().mockResolvedValue(true) },
connectorModel: {
+ // A personal row of a personal-scope call is in the run's own scope
+ forRow() {
+ return this;
+ },
getLinkModel: () => ({ listByConnectorIds: vi.fn().mockResolvedValue(links) }),
queryByIdentifiers: vi.fn().mockResolvedValue([connector]),
},
diff --git a/apps/server/src/services/connector/exec.test.ts b/apps/server/src/services/connector/exec.test.ts
index c5936a44989..8c5a41586ec 100644
--- a/apps/server/src/services/connector/exec.test.ts
+++ b/apps/server/src/services/connector/exec.test.ts
@@ -7,7 +7,7 @@ import { mcpService } from '@/server/services/mcp';
import type * as ContentProcessorModule from '@/server/services/mcp/contentProcessor';
import { callConnectorToolById, readConnectorUiResourceById } from './exec';
-import { scheduleStaleConnectorToolsRefresh } from './refresh';
+import { connectorSyncContextForRow, scheduleStaleConnectorToolsRefresh } from './refresh';
import { ensureFreshConnectorToken } from './tokens';
vi.mock('@/server/services/mcp', () => ({
@@ -32,6 +32,8 @@ vi.mock('./tokens', () => ({ ensureFreshConnectorToken: vi.fn(async (c) => c) })
// verify the call site wires it up and stays isolated from it.
vi.mock('./refresh', () => ({
buildLastSyncedAtMap: vi.fn(() => new Map()),
+ // The run's own context unless a test hands a personal row its own scope
+ connectorSyncContextForRow: vi.fn((ctx: unknown) => ctx),
scheduleStaleConnectorToolsRefresh: vi.fn(),
}));
@@ -60,6 +62,10 @@ const makeCtx = (connectors: any[], tools: any[], { agentVisible = true } = {})
getLinkModel: () => ({ listByConnectorIds: async () => [] }),
queryByIdentifiers: vi.fn().mockResolvedValue(connectors),
resolveByIdentifiers: vi.fn().mockResolvedValue(connectors),
+ // Every row its own tool set, keyed by its tool prefix
+ resolveToolSets: vi.fn(async () =>
+ connectors.map((row) => ({ ...row, toolIdentifier: row.toolIdentifier ?? row.identifier })),
+ ),
},
connectorToolModel: { queryByConnector: vi.fn().mockResolvedValue(tools) },
}) as any;
@@ -479,6 +485,28 @@ describe('callConnectorToolById', () => {
});
});
+ it("refreshes a personal row a workspace run resolved through the row's own scope", async () => {
+ // A private agent's workspace run resolves its owner's personal connector;
+ // the run's workspace-scoped models cannot write its tool rows.
+ const personalContext = { connectorModel: {}, connectorToolModel: {} } as any;
+ vi.mocked(connectorSyncContextForRow).mockReturnValueOnce(personalContext);
+ vi.mocked(mcpService.callTool).mockResolvedValue({ success: true });
+ const ctx = { ...makeCtx([connector], [tool()]), serverDB: {} as any, userId: 'user-1' };
+
+ await callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx);
+
+ expect(connectorSyncContextForRow).toHaveBeenCalledWith(
+ ctx,
+ expect.objectContaining({ id: 'c1' }),
+ ctx.serverDB,
+ );
+ expect(scheduleStaleConnectorToolsRefresh).toHaveBeenCalledWith(
+ [expect.objectContaining({ id: 'c1' })],
+ expect.anything(),
+ { ...personalContext, userId: 'user-1' },
+ );
+ });
+
it('still returns the tool result when the background refresh scheduler throws', async () => {
// The refresh is a pure optimization; a failure in it must never break the
// tool call the user actually asked for.
@@ -539,7 +567,10 @@ describe('readConnectorUiResourceById', () => {
ctx,
);
- expect(ensureFreshConnectorToken).toHaveBeenCalledWith(connector, ctx.connectorModel);
+ expect(ensureFreshConnectorToken).toHaveBeenCalledWith(
+ expect.objectContaining(connector),
+ ctx.connectorModel,
+ );
expect(mcpService.readUiResource).toHaveBeenCalledWith(
expect.objectContaining({ url: 'https://mcp.example.com' }),
'ui://app',
@@ -583,7 +614,12 @@ describe('readConnectorUiResourceById', () => {
ctx,
);
- expect(ctx.connectorModel.resolveByIdentifiers).toHaveBeenCalledWith(['my-conn'], 'agt_1');
+ expect(ctx.connectorModel.resolveToolSets).toHaveBeenCalledWith(
+ {
+ agentId: 'agt_1',
+ },
+ ['my-conn'],
+ );
expect(ctx.connectorModel.queryByIdentifiers).not.toHaveBeenCalled();
});
@@ -611,9 +647,80 @@ describe('callConnectorToolById agent resolution', () => {
);
expect(ctx.agentModel.existsById).toHaveBeenCalledWith('agt_1');
- expect(ctx.connectorModel.resolveByIdentifiers).toHaveBeenCalledWith(['my-conn'], 'agt_1');
+ expect(ctx.connectorModel.resolveToolSets).toHaveBeenCalledWith(
+ {
+ agentId: 'agt_1',
+ },
+ ['my-conn'],
+ );
expect(ctx.connectorModel.queryByIdentifiers).not.toHaveBeenCalled();
});
+
+ // A private agent's own private connectors resolve only with the proof that
+ // the call belongs to that agent's own topic.
+ it("resolves within the call's topic so a private agent reaches its own connectors", async () => {
+ vi.mocked(mcpService.callTool).mockResolvedValue({ success: true } as any);
+ const ctx = makeCtx([connector], [tool()]);
+
+ await callConnectorToolById(
+ { agentId: 'agt_1', identifier: 'my-conn', toolName: 'do_thing', topicId: 'tpc_1' },
+ ctx,
+ );
+
+ expect(ctx.connectorModel.resolveToolSets).toHaveBeenCalledWith(
+ {
+ agentId: 'agt_1',
+ topicId: 'tpc_1',
+ },
+ ['my-conn'],
+ );
+ });
+});
+
+// A private agent's own topic resolves the shared row and the owner's private
+// row of one identifier as two tool sets; a call runs the row its prefix names.
+describe('callConnectorToolById with same-identifier rows', () => {
+ const shared = { ...connector, id: 'conn-shared', mcpServerUrl: 'https://shared.example/mcp' };
+ const mine = {
+ ...connector,
+ id: 'conn-mine',
+ mcpServerUrl: 'https://mine.example/mcp',
+ toolIdentifier: 'my-conn-abcd1234',
+ visibility: 'private',
+ };
+
+ it.each([
+ ['my-conn-abcd1234', 'https://mine.example/mcp'],
+ ['my-conn', 'https://shared.example/mcp'],
+ ])('runs %s on its own row', async (identifier, url) => {
+ vi.mocked(mcpService.callTool).mockResolvedValue({ success: true } as any);
+ const ctx = makeCtx([mine, shared], [tool()]);
+
+ await callConnectorToolById(
+ { agentId: 'agt_1', identifier, toolName: 'do_thing', topicId: 'tpc_1' },
+ ctx,
+ );
+
+ expect(vi.mocked(mcpService.callTool).mock.calls[0][0]).toMatchObject({
+ clientParams: expect.objectContaining({ url }),
+ });
+ });
+
+ it('finds nothing for a prefix no row of the run has', async () => {
+ const ctx = makeCtx([shared], [tool()]);
+
+ await expect(
+ callConnectorToolById(
+ {
+ agentId: 'agt_1',
+ identifier: 'my-conn-abcd1234',
+ toolName: 'do_thing',
+ topicId: 'tpc_1',
+ },
+ ctx,
+ ),
+ ).rejects.toHaveProperty('code', 'NOT_FOUND');
+ });
});
// Connector rows are scoped by workspace only: another member's private agent
@@ -630,7 +737,7 @@ describe('agent-scoped connectors of an agent the caller cannot see', () => {
).rejects.toHaveProperty('code', 'NOT_FOUND');
expect(ctx.agentModel.existsById).toHaveBeenCalledWith('agt_private');
- expect(ctx.connectorModel.resolveByIdentifiers).not.toHaveBeenCalled();
+ expect(ctx.connectorModel.resolveToolSets).not.toHaveBeenCalled();
expect(ensureFreshConnectorToken).not.toHaveBeenCalled();
expect(mcpService.callTool).not.toHaveBeenCalled();
});
@@ -646,7 +753,7 @@ describe('agent-scoped connectors of an agent the caller cannot see', () => {
),
).rejects.toHaveProperty('code', 'NOT_FOUND');
- expect(ctx.connectorModel.resolveByIdentifiers).not.toHaveBeenCalled();
+ expect(ctx.connectorModel.resolveToolSets).not.toHaveBeenCalled();
expect(mcpService.readUiResource).not.toHaveBeenCalled();
});
});
diff --git a/apps/server/src/services/connector/exec.ts b/apps/server/src/services/connector/exec.ts
index bb0e403557a..a6f798cf43b 100644
--- a/apps/server/src/services/connector/exec.ts
+++ b/apps/server/src/services/connector/exec.ts
@@ -1,7 +1,11 @@
import { hasCallableMcpEndpoint, isMarketplaceInstallRunnable } from '@lobechat/const';
import { getMcpServerFingerprint, isSyncedMcpToolVisibleTo } from '@lobechat/const/mcpApp';
import type { LobeChatDatabase } from '@lobechat/database';
-import { getDisabledPluginIds, needsConnectorReauthorization } from '@lobechat/types';
+import {
+ connectorIdentifierCandidates,
+ getDisabledPluginIds,
+ needsConnectorReauthorization,
+} from '@lobechat/types';
import {
connectorDeviceBinding,
connectorMcpEndpoint,
@@ -30,7 +34,11 @@ import {
} from '@/server/services/toolExecution/mcpAuthError';
import { ConnectorLinkSelectionError, resolveLinkedCall } from './links';
-import { buildLastSyncedAtMap, scheduleStaleConnectorToolsRefresh } from './refresh';
+import {
+ buildLastSyncedAtMap,
+ connectorSyncContextForRow,
+ scheduleStaleConnectorToolsRefresh,
+} from './refresh';
import { buildConnectorMcpParams, type ConnectorToolSyncContext } from './sync';
import { ensureFreshConnectorToken } from './tokens';
@@ -107,21 +115,47 @@ export interface ConnectorExecContext extends ConnectorToolSyncContext {
/**
* The connector an identifier names. With an agent, resolve the way that agent's
* runs do (agent-owned > mounted > free base row); without one, keep the base
- * lookup the classic chat path has always used.
+ * lookup the classic chat path has always used (the workspace's shared rows).
*
- * Connector rows are scoped by workspace only, so in a workspace another
- * member's private agent would resolve to its connectors and their
+ * Agent-owned and mounted rows are scoped by workspace only, so in a workspace
+ * another member's private agent would resolve to its connectors and their
* credentials. Only an agent the caller can see may be resolved; any other id
- * reads as not found.
+ * reads as not found. A private agent's own private connectors also need the
+ * call's `topicId` to be that agent's own topic (see `ConnectorRunTarget`).
+ *
+ * The one resolution every connector call runs on, including a desktop that
+ * runs a stdio connector itself (`connector.getForRun`): which row serves a
+ * conversation is decided here, never by the client.
*/
-const findConnector = async (
- params: { agentId?: string; identifier: string },
- ctx: ConnectorExecContext,
+export const resolveConnectorForRun = async (
+ params: {
+ agentId?: string;
+ /**
+ * The tool prefix the call names (`connectorToolIdentifier`): a private or
+ * personal row is a tool set of its own beside the shared row of its
+ * connector, and only the row the prefix belongs to answers.
+ */
+ identifier: string;
+ topicId?: string;
+ },
+ ctx: Pick<ConnectorExecContext, 'agentModel' | 'connectorModel'>,
) => {
- if (!params.agentId) return ctx.connectorModel.queryByIdentifiers([params.identifier]);
+ // Without an agent only shared rows resolve, each under its identifier
+ if (!params.agentId)
+ return (await ctx.connectorModel.queryByIdentifiers([params.identifier])).map((row) => ({
+ ...row,
+ toolIdentifier: row.identifier,
+ }));
if (!(await ctx.agentModel.existsById(params.agentId))) return [];
- return ctx.connectorModel.resolveByIdentifiers([params.identifier], params.agentId);
+ const rows = await ctx.connectorModel.resolveToolSets(
+ { agentId: params.agentId, topicId: params.topicId },
+ connectorIdentifierCandidates(params.identifier),
+ );
+ const matches = rows.filter((row) => row.toolIdentifier === params.identifier);
+ // Prefixes are collision-free within a run (`connectorToolIdentifier`); an
+ // ambiguous one runs nothing rather than a guess at whose account
+ return matches.length === 1 ? matches : [];
};
/**
@@ -192,18 +226,23 @@ export const callConnectorToolById = async (
/** With `fromApp`: the server the view came from; its calls reach no other. */
server?: string;
toolName: string;
- /** The conversation the call runs in, reported as the call's session. */
+ /**
+ * The conversation the call runs in, reported as the call's session. It also
+ * decides whether a private agent's private connectors resolve; see
+ * {@link resolveConnectorForRun}.
+ */
topicId?: string;
},
ctx: ConnectorExecContext,
): Promise<unknown> => {
- const [connector] = await findConnector(params, ctx);
+ const [connector] = await resolveConnectorForRun(params, ctx);
+ // The agent's configuration names the connector, not the row's tool prefix
if (
params.fromEntrypoint &&
params.agentId &&
getDisabledPluginIds(
(await ctx.agentModel.getAgentConfigById(params.agentId))?.plugins ?? undefined,
- ).includes(params.identifier)
+ ).includes(connector?.identifier ?? params.identifier)
)
throw new ConnectorToolCallError('FORBIDDEN', 'This app is disabled for the agent');
if (!connector) {
@@ -258,19 +297,24 @@ export const callConnectorToolById = async (
// throttled, and deferred — reuses the `tools` rows already loaded above.
// Wrapped defensively: this is a pure optimization and must never break the
// tool call, even if the scheduler itself throws.
+ // A personal row a private agent's workspace run resolved refreshes through
+ // its own scope (`connectorSyncContextForRow`).
try {
- scheduleStaleConnectorToolsRefresh(
- [
- {
- id: connector.id,
- mcpConnectionType: connector.mcpConnectionType,
- mcpServerUrl: connector.mcpServerUrl,
- metadata: connector.metadata,
- },
- ],
- buildLastSyncedAtMap(tools),
- ctx,
- );
+ const refreshContext = connectorSyncContextForRow(ctx, connector, ctx.serverDB);
+ if (refreshContext) {
+ scheduleStaleConnectorToolsRefresh(
+ [
+ {
+ id: connector.id,
+ mcpConnectionType: connector.mcpConnectionType,
+ mcpServerUrl: connector.mcpServerUrl,
+ metadata: connector.metadata,
+ },
+ ],
+ buildLastSyncedAtMap(tools),
+ { ...refreshContext, userId: ctx.userId },
+ );
+ }
} catch {
// Background tool-list refresh is best-effort — never fail the tool call.
}
@@ -535,14 +579,21 @@ const runConnectorToolOnBoundDevice = async (
*/
export const readConnectorUiResourceById = async (
/** `server`: the server the result came from; the view is read from no other. */
- params: { agentId?: string; identifier: string; server: string; uri: string; linkId?: string },
+ params: {
+ agentId?: string;
+ identifier: string;
+ linkId?: string;
+ server: string;
+ topicId?: string;
+ uri: string;
+ },
ctx: ConnectorExecContext,
) => {
if (!(await isMcpAppsEnabled(ctx.userId))) {
throw new ConnectorToolCallError('FORBIDDEN', 'Interactive views are turned off');
}
- const [connector] = await findConnector(params, ctx);
+ const [connector] = await resolveConnectorForRun(params, ctx);
if (!connector) {
throw new ConnectorToolCallError('NOT_FOUND', 'Connector not found');
}
diff --git a/apps/server/src/services/connector/links.test.ts b/apps/server/src/services/connector/links.test.ts
index b3da0f0a53c..5ed42d71194 100644
--- a/apps/server/src/services/connector/links.test.ts
+++ b/apps/server/src/services/connector/links.test.ts
@@ -137,6 +137,80 @@ describe('resolveLinkedCall', () => {
});
});
+/**
+ * A private agent's workspace run can resolve its owner's personal connector
+ * (`workspace_id IS NULL`). The run's workspace-scoped models can neither list
+ * nor write its accounts, so they are read and refreshed in its own scope.
+ */
+describe("a personal connector's accounts in a workspace run", () => {
+ const personal = { ...connector, userId: 'owner', workspaceId: null } as DecryptedConnector;
+ const shared = {
+ ...connector,
+ id: 's',
+ userId: 'owner',
+ workspaceId: 'ws',
+ } as DecryptedConnector;
+ const setup = () => {
+ const personalLinks = { listByConnectorIds: vi.fn().mockResolvedValue([links[0]]) };
+ const personalModel = {
+ forRow() {
+ return this;
+ },
+ getLinkModel: () => personalLinks,
+ };
+ const workspaceLinks = {
+ listByConnectorIds: vi
+ .fn()
+ .mockResolvedValue([{ ...links[1], id: 'lnk_s', userConnectorId: 's' }]),
+ };
+ const workspaceModel = {
+ forRow: vi.fn((row: { workspaceId: string | null }) =>
+ row.workspaceId === null ? personalModel : workspaceModel,
+ ),
+ };
+ return {
+ ctx: {
+ connectorLinkModel: workspaceLinks as unknown as ConnectorLinkModel,
+ connectorModel: workspaceModel as never,
+ },
+ personalLinks,
+ personalModel,
+ workspaceLinks,
+ };
+ };
+
+ it('lists each row in its own scope', async () => {
+ const { ctx, personalLinks, workspaceLinks } = setup();
+
+ const map = await loadConnectorLinksMap([personal, shared], ctx);
+
+ expect(personalLinks.listByConnectorIds).toHaveBeenCalledWith(['c']);
+ expect(workspaceLinks.listByConnectorIds).toHaveBeenCalledWith(['s']);
+ expect(map.get('c')?.map((link) => link.id)).toEqual(['lnk_a']);
+ expect(map.get('s')?.map((link) => link.id)).toEqual(['lnk_s']);
+ });
+
+ it("resolves a personal row's primary account through the personal scope", async () => {
+ const { ctx, personalModel, workspaceLinks } = setup();
+
+ const result = await resolveConnectorAccount(personal, ctx);
+
+ expect(result).toMatchObject({ accountCount: 1, linkId: 'lnk_a' });
+ expect(workspaceLinks.listByConnectorIds).not.toHaveBeenCalled();
+ expect(ensureFreshLinkToken).toHaveBeenLastCalledWith(personal, links[0], personalModel);
+ });
+
+ it('calls as, and refreshes through, the personal scope', async () => {
+ const { ctx, personalModel, workspaceLinks } = setup();
+
+ const result = await resolveLinkedCall({ connector: personal }, ctx);
+
+ expect(result).toMatchObject({ linkId: 'lnk_a' });
+ expect(workspaceLinks.listByConnectorIds).not.toHaveBeenCalled();
+ expect(ensureFreshLinkToken).toHaveBeenLastCalledWith(personal, links[0], personalModel);
+ });
+});
+
describe('resolveConnectorAccount', () => {
it('calls as the primary account, with its refreshed credentials, and says which one', async () => {
const result = await resolveConnectorAccount(connector, context());
diff --git a/apps/server/src/services/connector/links.ts b/apps/server/src/services/connector/links.ts
index b183e5ac19f..2c180d0b9e5 100644
--- a/apps/server/src/services/connector/links.ts
+++ b/apps/server/src/services/connector/links.ts
@@ -16,6 +16,22 @@ export interface ConnectorLinksContext {
export const getConnectorLinkModel = (ctx: ConnectorLinksContext) =>
ctx.connectorLinkModel ?? ctx.connectorModel.getLinkModel();
+/**
+ * The links context of a connector row's own scope. A private agent's
+ * workspace run can resolve its owner's personal connector (`workspace_id IS
+ * NULL`), whose accounts the run's workspace-scoped models can neither list
+ * nor write (`ConnectorModel.forRow`). Every other row is in the run's scope.
+ */
+export const connectorLinksContextForRow = (
+ ctx: ConnectorLinksContext,
+ row: Pick<DecryptedConnector, 'userId' | 'workspaceId'>,
+): ConnectorLinksContext => {
+ // Only a personal row can lie outside the run's scope
+ if (row.workspaceId !== null) return ctx;
+ const connectorModel = ctx.connectorModel.forRow(row);
+ return connectorModel === ctx.connectorModel ? ctx : { connectorModel };
+};
+
/**
* Accounts exist only for OAuth connectors: an authorization needs the
* connector's OAuth client, and replacing OAuth with static credentials
@@ -34,11 +50,22 @@ export const loadConnectorLinksMap = async (
const map = new Map<string, DecryptedConnectorLink[]>();
const candidates = connectors.filter(mayHaveLinks);
if (!candidates.length) return map;
- const model = getConnectorLinkModel(ctx);
- for (const link of await model.listByConnectorIds(candidates.map((c) => c.id))) {
- const links = map.get(link.userConnectorId) ?? [];
- links.push(link);
- map.set(link.userConnectorId, links);
+ // Each row's accounts are listed in its own scope: the run's, or the
+ // caller's personal one (`connectorLinksContextForRow`)
+ const groups = new Map<ConnectorLinksContext, DecryptedConnector[]>();
+ let personal: ConnectorLinksContext | undefined;
+ for (const connector of candidates) {
+ let rowContext = connectorLinksContextForRow(ctx, connector);
+ if (rowContext !== ctx) rowContext = personal ??= rowContext;
+ groups.set(rowContext, [...(groups.get(rowContext) ?? []), connector]);
+ }
+ for (const [rowContext, rows] of groups) {
+ const model = getConnectorLinkModel(rowContext);
+ for (const link of await model.listByConnectorIds(rows.map((c) => c.id))) {
+ const links = map.get(link.userConnectorId) ?? [];
+ links.push(link);
+ map.set(link.userConnectorId, links);
+ }
}
return map;
};
@@ -80,15 +107,17 @@ export const resolveConnectorAccount = async (
link?: DecryptedConnectorLink;
linkId?: string;
}> => {
- const links = (await loadConnectorLinksMap([connector], ctx)).get(connector.id) ?? [];
+ // Read and refreshed in the row's own scope (a personal row in a workspace run)
+ const rowContext = connectorLinksContextForRow(ctx, connector);
+ const links = (await loadConnectorLinksMap([connector], rowContext)).get(connector.id) ?? [];
const link = linkId ? links.find((l) => l.id === linkId) : pickPrimaryLink(links);
if (linkId && !link) throw new ConnectorAccountGoneError();
if (!link)
return {
accountCount: links.length,
- connector: await ensureFreshConnectorToken(connector, ctx.connectorModel),
+ connector: await ensureFreshConnectorToken(connector, rowContext.connectorModel),
};
- const fresh = await ensureFreshLinkToken(connector, link, ctx.connectorModel);
+ const fresh = await ensureFreshLinkToken(connector, link, rowContext.connectorModel);
return {
accountCount: links.length,
connector: withLinkCredentials(connector, fresh),
@@ -117,7 +146,8 @@ export const resolveLinkedCall = async (
linkName?: string;
}> => {
const { connector } = params;
- const links = (await loadConnectorLinksMap([connector], ctx)).get(connector.id) ?? [];
+ const rowContext = connectorLinksContextForRow(ctx, connector);
+ const links = (await loadConnectorLinksMap([connector], rowContext)).get(connector.id) ?? [];
if (!links.length) {
if (
params.linkId ||
@@ -161,7 +191,7 @@ export const resolveLinkedCall = async (
throw new ConnectorLinkSelectionError(
`The selected account no longer exists. Current accounts: ${choices}`,
);
- const fresh = await ensureFreshLinkToken(connector, link, ctx.connectorModel);
+ const fresh = await ensureFreshLinkToken(connector, link, rowContext.connectorModel);
return {
connector: withLinkCredentials(connector, fresh),
argsStr: split.argsStr,
diff --git a/apps/server/src/services/connector/localCallToken.test.ts b/apps/server/src/services/connector/localCallToken.test.ts
index 71fb7c3c9ad..b053b809517 100644
--- a/apps/server/src/services/connector/localCallToken.test.ts
+++ b/apps/server/src/services/connector/localCallToken.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { getConnectorLocalCallToken } from './localCallToken';
+import { getConnectorLocalCallToken, getResolvedConnectorLocalCallToken } from './localCallToken';
import { ensureFreshLinkToken } from './tokens';
vi.mock('./tokens', () => ({ ensureFreshLinkToken: vi.fn(async (_connector, link) => link) }));
@@ -39,6 +39,9 @@ const call = (
) => {
const connectorModel = {
findById: vi.fn().mockResolvedValue(connector),
+ forRow() {
+ return this;
+ },
getLinkModel: () => ({ listByConnectorIds: vi.fn().mockResolvedValue(links) }),
};
return getConnectorLocalCallToken(
@@ -116,3 +119,47 @@ describe('getConnectorLocalCallToken', () => {
await expect(call(undefined)).rejects.toMatchObject({ code: 'NOT_FOUND' });
});
});
+
+describe('getResolvedConnectorLocalCallToken', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("reads and refreshes a resolved row's accounts through its own scope, without reading it by id", async () => {
+ // A private agent's own topic runs its owner's personal connector, which
+ // the workspace scope can neither read by id nor list the accounts of.
+ const link = account('lnk_a', 'access');
+ const personalLinkModel = { listByConnectorIds: vi.fn().mockResolvedValue([link]) };
+ const personalModel = {
+ forRow() {
+ return this;
+ },
+ getLinkModel: () => personalLinkModel,
+ };
+ const workspaceLinkModel = { listByConnectorIds: vi.fn().mockResolvedValue([]) };
+ const connectorModel = { findById: vi.fn(), forRow: vi.fn(() => personalModel) };
+ const personal = { ...oauthConnector, workspaceId: null };
+
+ await expect(
+ getResolvedConnectorLocalCallToken(
+ {
+ connectorLinkModel: workspaceLinkModel as never,
+ connectorModel: connectorModel as never,
+ userId: 'u1',
+ },
+ personal as never,
+ ),
+ ).resolves.toEqual({ accessToken: 'access', type: 'oauth2' });
+ expect(connectorModel.findById).not.toHaveBeenCalled();
+ expect(connectorModel.forRow).toHaveBeenCalledWith(personal);
+ expect(workspaceLinkModel.listByConnectorIds).not.toHaveBeenCalled();
+ expect(ensureFreshLinkToken).toHaveBeenCalledWith(personal, link, personalModel);
+ });
+
+ it('refuses a resolved row someone else connected', async () => {
+ await expect(
+ getResolvedConnectorLocalCallToken(
+ { connectorModel: {} as never, userId: 'workspace-owner' },
+ oauthConnector as never,
+ ),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+});
diff --git a/apps/server/src/services/connector/localCallToken.ts b/apps/server/src/services/connector/localCallToken.ts
index 0dec4dce3b1..e969450a9c6 100644
--- a/apps/server/src/services/connector/localCallToken.ts
+++ b/apps/server/src/services/connector/localCallToken.ts
@@ -2,11 +2,18 @@ import { needsConnectorReauthorization } from '@lobechat/types';
import { connectorMcpEndpoint, isDeviceOnlyMcpEndpoint } from '@lobechat/utils/mcpEndpoint';
import { TRPCError } from '@trpc/server';
-import type { ConnectorModel } from '@/database/models/connector';
+import type { ConnectorModel, DecryptedConnector } from '@/database/models/connector';
+import type { ConnectorLinkModel } from '@/database/models/connectorLink';
-import { loadConnectorLinksMap, pickPrimaryLink } from './links';
+import { connectorLinksContextForRow, loadConnectorLinksMap, pickPrimaryLink } from './links';
import { ensureFreshLinkToken } from './tokens';
+interface LocalCallTokenContext {
+ connectorLinkModel?: ConnectorLinkModel;
+ connectorModel: ConnectorModel;
+ userId: string;
+}
+
/**
* The current OAuth access token of an HTTP connector the creator's desktop app
* calls itself: one only their machine reaches (localhost / LAN, or set to
@@ -20,14 +27,18 @@ import { ensureFreshLinkToken } from './tokens';
* forwards to the user's device for the same call. `linkId` picks the account
* of a connector holding several, its primary account otherwise. `null` when
* the connector has no OAuth account or runs elsewhere.
+ *
+ * `connector` is a row the caller already resolved, such as the one a
+ * conversation's call runs on: a private agent's own topic may run its owner's
+ * personal connector, which the workspace scope's `findById` cannot read. Its
+ * accounts are read, and refreshed, through that row's own scope
+ * (`connectorLinksContextForRow`).
*/
-export const getConnectorLocalCallToken = async (
- ctx: { connectorModel: ConnectorModel; userId: string },
- id: string,
+export const getResolvedConnectorLocalCallToken = async (
+ ctx: LocalCallTokenContext,
+ connector: DecryptedConnector,
linkId?: string,
): Promise<{ accessToken: string; type: 'oauth2' } | null> => {
- const connector = await ctx.connectorModel.findById(id);
- if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
if (connector.userId !== ctx.userId) {
throw new TRPCError({
code: 'FORBIDDEN',
@@ -39,7 +50,8 @@ export const getConnectorLocalCallToken = async (
if (endpoint.type === 'stdio' || !connector.mcpServerUrl || !isDeviceOnlyMcpEndpoint(endpoint))
return null;
- const links = (await loadConnectorLinksMap([connector], ctx)).get(connector.id) ?? [];
+ const linksContext = connectorLinksContextForRow(ctx, connector);
+ const links = (await loadConnectorLinksMap([connector], linksContext)).get(connector.id) ?? [];
const link = linkId ? links.find((item) => item.id === linkId) : pickPrimaryLink(links);
if (!link) {
if (linkId) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector account not found' });
@@ -52,7 +64,7 @@ export const getConnectorLocalCallToken = async (
});
}
- const fresh = await ensureFreshLinkToken(connector, link, ctx.connectorModel);
+ const fresh = await ensureFreshLinkToken(connector, link, linksContext.connectorModel);
if (needsConnectorReauthorization(fresh.credentials)) {
throw new TRPCError({
code: 'PRECONDITION_FAILED',
@@ -63,3 +75,14 @@ export const getConnectorLocalCallToken = async (
? { accessToken: fresh.credentials.accessToken, type: 'oauth2' }
: null;
};
+
+/** {@link getResolvedConnectorLocalCallToken} of a row in the caller's own scope, by id. */
+export const getConnectorLocalCallToken = async (
+ ctx: LocalCallTokenContext,
+ id: string,
+ linkId?: string,
+): Promise<{ accessToken: string; type: 'oauth2' } | null> => {
+ const connector = await ctx.connectorModel.findById(id);
+ if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
+ return getResolvedConnectorLocalCallToken(ctx, connector, linkId);
+};
diff --git a/apps/server/src/services/connector/refresh.test.ts b/apps/server/src/services/connector/refresh.test.ts
index 4c278cfcf25..eb99ecff204 100644
--- a/apps/server/src/services/connector/refresh.test.ts
+++ b/apps/server/src/services/connector/refresh.test.ts
@@ -1,11 +1,13 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { ConnectorToolModel } from '@/database/models/connectorTool';
import { deviceGateway } from '@/server/services/deviceGateway';
import { after } from '@/server/utils/scheduleAfterResponse';
import {
buildLastSyncedAtMap,
CONNECTOR_TOOLS_REFRESH_TTL_MS,
+ connectorSyncContextForRow,
scheduleStaleConnectorToolsRefresh,
} from './refresh';
import { syncConnectorToolsById } from './sync';
@@ -69,6 +71,50 @@ describe('buildLastSyncedAtMap', () => {
});
});
+describe('connectorSyncContextForRow', () => {
+ const db = {} as any;
+ const runContext = (forRow: (row: unknown) => unknown) =>
+ ({ connectorModel: { forRow }, connectorToolModel: { scope: 'run' } }) as any;
+
+ it("keeps the run's own context for a row in the run's scope", () => {
+ const ctx = runContext(function (this: unknown) {
+ return ctx.connectorModel;
+ });
+ const row = { userId: 'user-1', workspaceId: 'ws-1' };
+
+ expect(connectorSyncContextForRow(ctx, row, db)).toBe(ctx);
+ });
+
+ /**
+ * @example
+ * expect(connectorSyncContextForRow(workspaceRun, ownersPersonalRow, db).connectorModel).toBe(personalModel);
+ */
+ it("writes the owner's personal row through the personal scope", () => {
+ // ROOT CAUSE:
+ //
+ // A private agent's workspace run resolves its owner's personal connector, but its stale-tool
+ // refresh used the run's workspace-scoped models, which cannot find or write that row, so the
+ // tool list stayed at its install-time state.
+ const personalModel = { scope: 'personal' };
+ const ctx = runContext(() => personalModel);
+ const row = { userId: 'user-1', workspaceId: null };
+
+ const result = connectorSyncContextForRow(ctx, row, db);
+
+ expect(result?.connectorModel).toBe(personalModel);
+ expect(result?.connectorToolModel).toBeInstanceOf(ConnectorToolModel);
+ expect(result?.connectorToolModel).not.toBe(ctx.connectorToolModel);
+ });
+
+ it('has no context for a personal row without a database to reach it', () => {
+ const ctx = runContext(() => ({ scope: 'personal' }));
+
+ expect(
+ connectorSyncContextForRow(ctx, { userId: 'user-1', workspaceId: null }, undefined),
+ ).toBe(undefined);
+ });
+});
+
describe('scheduleStaleConnectorToolsRefresh — eligibility', () => {
it('schedules a refresh for an HTTP connector whose tools are stale', async () => {
const id = nextId();
diff --git a/apps/server/src/services/connector/refresh.ts b/apps/server/src/services/connector/refresh.ts
index 5c300523943..6ea2d9e10d1 100644
--- a/apps/server/src/services/connector/refresh.ts
+++ b/apps/server/src/services/connector/refresh.ts
@@ -1,6 +1,8 @@
+import type { LobeChatDatabase } from '@lobechat/database';
import { connectorMcpEndpoint, shouldConnectViaDevice } from '@lobechat/utils/mcpEndpoint';
import debug from 'debug';
+import { ConnectorToolModel } from '@/database/models/connectorTool';
import { ConnectorMcpConnectionType } from '@/database/schemas';
import { deviceGateway } from '@/server/services/deviceGateway';
import { after } from '@/server/utils/scheduleAfterResponse';
@@ -42,6 +44,25 @@ const pruneAttempts = (now: number): void => {
}
};
+/**
+ * The sync context that can write a resolved connector's rows. A private
+ * agent's workspace run can resolve its owner's personal connector, whose
+ * connector and tool rows live in the personal scope the run's
+ * workspace-scoped models cannot write (`ConnectorModel.forRow`), so its tool
+ * list is refreshed through that scope. Every other row is in the run's own
+ * scope. `undefined` when the personal scope can't be reached (no database).
+ */
+export const connectorSyncContextForRow = (
+ ctx: ConnectorToolSyncContext,
+ row: { userId: string; workspaceId: string | null },
+ db: LobeChatDatabase | undefined,
+): ConnectorToolSyncContext | undefined => {
+ const connectorModel = ctx.connectorModel.forRow(row);
+ if (connectorModel === ctx.connectorModel) return ctx;
+ if (!db) return undefined;
+ return { connectorModel, connectorToolModel: new ConnectorToolModel(db, row.userId) };
+};
+
export interface StaleRefreshConnector {
id: string;
mcpConnectionType: ConnectorMcpConnectionType | string | null;
diff --git a/apps/server/src/services/connector/sync.test.ts b/apps/server/src/services/connector/sync.test.ts
index 04bc22d4d17..c5e70cd5e80 100644
--- a/apps/server/src/services/connector/sync.test.ts
+++ b/apps/server/src/services/connector/sync.test.ts
@@ -680,6 +680,10 @@ describe('events capability synchronization', () => {
userId: 'owner',
workspaceId: null,
}) as any,
+ // A personal row is read in its own scope (here: this model)
+ forRow() {
+ return this;
+ },
update,
updateStatus: vi.fn(),
} as any,
diff --git a/apps/server/src/services/connector/tokens.test.ts b/apps/server/src/services/connector/tokens.test.ts
index e8054dbd938..4d73aa472d6 100644
--- a/apps/server/src/services/connector/tokens.test.ts
+++ b/apps/server/src/services/connector/tokens.test.ts
@@ -49,6 +49,8 @@ function store(kind: 'link' | 'legacy' = 'legacy') {
let queue = Promise.resolve();
const instance = () => {
const model = {
+ // Every row here is in the model's own scope
+ forRow: () => model,
getLinkModel: () => ({
listByConnectorIds: async () => [
kind === 'legacy' ? { ...link, credentials: row.credentials, status: row.status } : link,
@@ -98,6 +100,21 @@ afterEach(() => {
});
describe('OAuth refresh coordination', () => {
+ it("refreshes a row outside the run's scope through the row's own model", async () => {
+ // Regression: a private agent's workspace run resolved its owner's personal
+ // connector; the workspace-scoped model could not write the rotated token.
+ const db = store();
+ const personal = db.instance();
+ const runModel = { forRow: vi.fn(() => personal), update: vi.fn() };
+
+ const fresh = await ensureFreshConnectorToken(db.read(), runModel as unknown as ConnectorModel);
+
+ expect(runModel.forRow).toHaveBeenCalledWith(expect.objectContaining({ id: 'connector' }));
+ expect(runModel.update).not.toHaveBeenCalled();
+ expect(fresh.credentials).toMatchObject({ accessToken: 'fresh' });
+ expect(db.read().credentials).toMatchObject({ accessToken: 'fresh' });
+ });
+
it('makes one request across two instances and both ways of reading a legacy account', async () => {
const db = store();
const stale = db.read();
diff --git a/apps/server/src/services/connector/tokens.ts b/apps/server/src/services/connector/tokens.ts
index af014cbfd3c..5c080a222bf 100644
--- a/apps/server/src/services/connector/tokens.ts
+++ b/apps/server/src/services/connector/tokens.ts
@@ -257,14 +257,21 @@ const runClaimedRefresh = async (
});
};
+/**
+ * Every refresh reads and writes the row through its own scope
+ * (`ConnectorModel.forRow`): a private agent's workspace run can resolve its
+ * owner's personal connector, whose token the run's workspace-scoped model can
+ * neither find nor update — a rotated refresh token would be dropped.
+ */
const refreshSlot = async (
connector: DecryptedConnector,
credentials: DecryptedConnector['credentials'],
- model: ConnectorModel,
+ runModel: ConnectorModel,
linkId?: string,
waitUntil = Date.now() + REFRESH_ATTEMPT_TTL_MS,
): Promise<RefreshSlot | undefined> => {
if (!isRefreshDue(credentials)) return;
+ const model = runModel.forRow(connector);
try {
while (true) {
const decision = await claimRefresh(connector, credentials, model, linkId);
diff --git a/apps/server/src/services/toolExecution/builtin.ts b/apps/server/src/services/toolExecution/builtin.ts
index ab82c23b58e..cb4817aec12 100644
--- a/apps/server/src/services/toolExecution/builtin.ts
+++ b/apps/server/src/services/toolExecution/builtin.ts
@@ -272,6 +272,7 @@ export class BuiltinToolsExecutor implements IToolExecutor {
args,
identifier,
toolSlug: apiName,
+ topicId: context.topicId,
});
}
diff --git a/apps/server/src/services/toolExecution/index.connectorLinks.test.ts b/apps/server/src/services/toolExecution/index.connectorLinks.test.ts
index b6408a97fd3..fe3c3b3c33a 100644
--- a/apps/server/src/services/toolExecution/index.connectorLinks.test.ts
+++ b/apps/server/src/services/toolExecution/index.connectorLinks.test.ts
@@ -6,7 +6,14 @@ import { deviceGateway } from '@/server/services/deviceGateway';
import { ToolExecutionService } from './index';
-const mocks = vi.hoisted(() => ({ find: vi.fn(), links: vi.fn(), call: vi.fn(), tools: vi.fn() }));
+const mocks = vi.hoisted(() => ({
+ call: vi.fn(),
+ find: vi.fn(),
+ links: vi.fn(),
+ resolveTarget: vi.fn(),
+ toolModelOptions: vi.fn(),
+ tools: vi.fn(),
+}));
vi.mock('@/database/models/connector', () => ({
ConnectorModel: vi.fn(function () {
return {
@@ -14,16 +21,23 @@ vi.mock('@/database/models/connector', () => ({
// Any row by id: the marker alone must never pick the connector
findById: mocks.find,
// The connector the call's identifier resolves to for the run
- resolveByIdentifiers: async () => {
+ resolveByIdentifiers: async (_identifiers: string[], target: unknown) => {
+ mocks.resolveTarget(target);
const row = await mocks.find();
return row ? [row] : [];
},
+ resolveToolSets: async (target: unknown) => {
+ mocks.resolveTarget(target);
+ const row = await mocks.find();
+ return row ? [{ ...row, toolIdentifier: row.toolIdentifier ?? row.identifier }] : [];
+ },
getLinkModel: () => ({ listByConnectorIds: mocks.links }),
};
}),
}));
vi.mock('@/database/models/connectorTool', () => ({
- ConnectorToolModel: vi.fn(function () {
+ ConnectorToolModel: vi.fn(function (_db, _userId, _workspaceId, options) {
+ mocks.toolModelOptions(options);
return { queryByConnector: mocks.tools };
}),
}));
@@ -96,6 +110,22 @@ beforeEach(() => {
});
});
describe('live connector account resolution at dispatch', () => {
+ it("resolves the connector in the run's conversation, reading a personal row's tools", async () => {
+ // Regression: discovery advertised a private agent's own private connector
+ // (resolved with the topic), but dispatch re-resolved without it, found no
+ // row or a shared sibling, and failed every call with a connector mismatch.
+ const result = await service.executeTool(
+ payload,
+ context('https://mcp.example', { agentId: 'agt-private', topicId: 'tpc-own' }),
+ );
+
+ expect(result.success).toBe(true);
+ // Every resolution (the permission gate's and the dispatch's) names the topic
+ expect(mocks.resolveTarget.mock.calls.length).toBeGreaterThan(0);
+ for (const [target] of mocks.resolveTarget.mock.calls)
+ expect(target).toEqual({ agentId: 'agt-private', topicId: 'tpc-own' });
+ expect(mocks.toolModelOptions).toHaveBeenCalledWith({ agentRun: true });
+ });
it('resolves the selected token and strips the selector before HTTP execution', async () => {
const result = await service.executeTool(payload, context('https://mcp.example'));
expect(result.success).toBe(true);
@@ -247,3 +277,56 @@ describe('live connector account resolution at dispatch', () => {
});
});
});
+
+// A single-account connector's manifest carries its endpoint and credentials
+// from discovery: a row that has left the conversation's scope since must not
+// keep running from that copy.
+describe('connector row revalidation at dispatch', () => {
+ const single = (url: string) =>
+ ({
+ userId: 'me',
+ serverDB: {},
+ toolManifestMap: {
+ multi: {
+ connector: { id: 'c', identifier: 'multi' },
+ mcpParams: { auth: { accessToken: 'discovery-token' }, type: 'http', url },
+ },
+ },
+ }) as any;
+
+ it('refuses a call whose row the run no longer resolves', async () => {
+ // Regression: made private mid-conversation, the shared row stopped
+ // resolving, yet the discovery-time params kept running its account.
+ mocks.find.mockResolvedValue(undefined);
+
+ const result = await service.executeTool(
+ { ...payload, arguments: '{"x":1}' },
+ single('https://mcp.example'),
+ );
+
+ expect(result.success).toBe(false);
+ expect(mocks.call).not.toHaveBeenCalled();
+ });
+
+ it('refuses a call whose prefix now names another row', async () => {
+ mocks.find.mockResolvedValue({ id: 'other', identifier: 'multi', isEnabled: true });
+
+ const result = await service.executeTool(
+ { ...payload, arguments: '{"x":1}' },
+ single('https://mcp.example'),
+ );
+
+ expect(result.success).toBe(false);
+ expect(mocks.call).not.toHaveBeenCalled();
+ });
+
+ it('runs a call whose row still resolves', async () => {
+ const result = await service.executeTool(
+ { ...payload, arguments: '{"x":1}' },
+ single('https://mcp.example'),
+ );
+
+ expect(result.success).toBe(true);
+ expect(mocks.call).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.ts
index af886b02e47..6f45945dcd3 100644
--- a/apps/server/src/services/toolExecution/index.ts
+++ b/apps/server/src/services/toolExecution/index.ts
@@ -1,6 +1,10 @@
import { BRANDING_NAME } from '@lobechat/business-const';
import { DEFAULT_TOOL_RESULT_MAX_LENGTH, truncateToolResult } from '@lobechat/prompts/toolResult';
-import { type ChatToolPayload, type DeviceClient } from '@lobechat/types';
+import {
+ type ChatToolPayload,
+ connectorIdentifierCandidates,
+ type DeviceClient,
+} from '@lobechat/types';
import { isDeviceOnlyMcpEndpoint, shouldConnectViaDevice } from '@lobechat/utils/mcpEndpoint';
import debug from 'debug';
@@ -189,7 +193,7 @@ export class ToolExecutionService {
identifier,
apiName,
context.workspaceId,
- context.agentId,
+ { agentId: context.agentId, topicId: context.topicId },
);
if (permission === ConnectorToolPermission.disabled) {
log('Tool %s:%s is disabled by user — blocking execution', identifier, apiName);
@@ -348,7 +352,13 @@ export class ToolExecutionService {
}
const marker = (manifest as { connectorLinks?: { connectorId: string; param: string } })
.connectorLinks;
- if (marker) {
+ // A connector row's manifest (`manifest.connector`) was built at
+ // discovery with that row's endpoint and credentials. The row may since
+ // have left this conversation's scope (made private, disabled, deleted):
+ // every call resolves it again, in the run's conversation, and runs only
+ // while the tool prefix still names that same row.
+ const rowRef = (manifest as { connector?: { id: string } }).connector;
+ if (rowRef || marker) {
if (!context.serverDB || !context.userId)
throw new Error(
'Connector account resolution requires an authenticated execution context',
@@ -364,51 +374,58 @@ export class ToolExecutionService {
// The marker rides in a manifest, and a plugin row can carry any
// manifest. Only the connector this call's identifier resolves to for
// the run (the one the permission gate checked) may lend its accounts,
- // and only to a tool it serves and has not disabled.
- const [connector] = await connectorModel.resolveByIdentifiers(
- [identifier],
- context.agentId,
- );
- if (!connector || connector.id !== marker.connectorId || !connector.isEnabled)
+ // and only to a tool it serves and has not disabled. It resolves in the
+ // run's conversation, as discovery did: a private agent's own topic
+ // admits its owner's private and personal rows, each a tool set of its
+ // own, so the row is the one this tool prefix names.
+ const connector = (
+ await connectorModel.resolveToolSets(
+ { agentId: context.agentId, topicId: context.topicId },
+ connectorIdentifierCandidates(identifier),
+ )
+ ).find((row) => row.toolIdentifier === identifier);
+ const expectedId = marker?.connectorId ?? rowRef?.id;
+ if (!connector || connector.id !== expectedId || !connector.isEnabled)
throw new Error(
'Connector is no longer available. Ask the user to connect an account in Settings > Connectors.',
);
- const tool = (
- await new ConnectorToolModel(
- context.serverDB,
- context.userId,
- workspaceId,
- ).queryByConnector(connector.id)
- ).find((item) => item.toolName === apiName);
- if (!tool) throw new Error(`Connector '${identifier}' has no tool named '${apiName}'.`);
- if (tool.permission === ConnectorToolPermission.disabled)
- return buildBlockedToolResponse(apiName);
- const currentEndpoint = buildConnectorMcpParams({ ...connector, credentials: null });
- if (
- context.agentShareVisitor &&
- !context.agentShareVisitor.canUseDevice &&
- isDeviceOnlyMcpEndpoint(currentEndpoint)
- ) {
- const message = `MCP server '${identifier}' runs on the agent owner's own machine and is not available in shared conversations.`;
- return {
- content: message,
- error: { code: 'SHARE_GATE_BLOCKED', message },
- success: false,
- };
+ if (marker) {
+ const tool = // A run model reads the tools of the owner's personal row too
+ (
+ await new ConnectorToolModel(context.serverDB, context.userId, workspaceId, {
+ agentRun: true,
+ }).queryByConnector(connector.id)
+ ).find((item) => item.toolName === apiName);
+ if (!tool) throw new Error(`Connector '${identifier}' has no tool named '${apiName}'.`);
+ if (tool.permission === ConnectorToolPermission.disabled)
+ return buildBlockedToolResponse(apiName);
+ const currentEndpoint = buildConnectorMcpParams({ ...connector, credentials: null });
+ if (
+ context.agentShareVisitor &&
+ !context.agentShareVisitor.canUseDevice &&
+ isDeviceOnlyMcpEndpoint(currentEndpoint)
+ ) {
+ const message = `MCP server '${identifier}' runs on the agent owner's own machine and is not available in shared conversations.`;
+ return {
+ content: message,
+ error: { code: 'SHARE_GATE_BLOCKED', message },
+ success: false,
+ };
+ }
+ const resolved = await resolveLinkedCall(
+ {
+ connector,
+ argsStr: args,
+ param: marker.param,
+ isShareVisitor: !!context.agentShareVisitor,
+ },
+ { connectorModel },
+ );
+ args = resolved.argsStr;
+ payload = { ...payload, arguments: args };
+ linkName = resolved.linkName;
+ mcpParams = buildConnectorMcpParams(resolved.connector);
}
- const resolved = await resolveLinkedCall(
- {
- connector,
- argsStr: args,
- param: marker.param,
- isShareVisitor: !!context.agentShareVisitor,
- },
- { connectorModel },
- );
- args = resolved.argsStr;
- payload = { ...payload, arguments: args };
- linkName = resolved.linkName;
- mcpParams = buildConnectorMcpParams(resolved.connector);
}
// Check if this is a cloud MCP endpoint
if (mcpParams.type === 'cloud') {
@@ -697,9 +714,11 @@ export class ToolExecutionService {
payload: ChatToolPayload,
context: ToolExecutionContext,
- _mcpParams: CloudMCPParams,
+ mcpParams: CloudMCPParams,
): Promise<ToolExecutionResult> {
- const { identifier, apiName, arguments: args } = payload;
+ const { apiName, arguments: args } = payload;
+ // The gateway knows the connector, not a private row's tool prefix
+ const identifier = mcpParams.name || payload.identifier;
log('Executing Cloud MCP tool: %s:%s via cloud gateway', identifier, apiName);
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pluginResolution.privateConnector.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pluginResolution.privateConnector.test.ts
new file mode 100644
index 00000000000..e33ac3dab90
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pluginResolution.privateConnector.test.ts
@@ -0,0 +1,94 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { ConnectorModel } from '@/database/models/connector';
+import { agents, userConnectors, users, workspaces } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { resolvePluginIdentifier } from '../pluginResolution';
+
+const owner = 'pr-owner';
+const mate = 'pr-mate';
+const workspaceId = 'pr-ws';
+const privateAgent = 'pr-agent-private';
+const workspaceAgent = 'pr-agent-workspace';
+
+// No installed-plugin projection: the connector row is the only source
+const pluginModel = { findById: async () => undefined, query: async () => [] } as any;
+
+let serverDB: LobeChatDatabase;
+
+const resolve = (userId: string, agentId: string) =>
+ resolvePluginIdentifier(
+ 'acme-notes',
+ { connectorModel: new ConnectorModel(serverDB, userId, workspaceId), pluginModel },
+ { agentId },
+ );
+
+beforeEach(async () => {
+ serverDB = await getTestDB();
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: owner }, { id: mate }]);
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'WS', primaryOwnerId: owner, slug: 'pr-ws' });
+ await serverDB.insert(agents).values([
+ { id: privateAgent, userId: owner, visibility: 'private', workspaceId },
+ { id: workspaceAgent, userId: owner, visibility: 'public', workspaceId },
+ ]);
+ // The owner's connected private custom MCP connector
+ await serverDB.insert(userConnectors).values({
+ identifier: 'acme-notes',
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://notes.example.com/mcp',
+ name: 'Acme Notes',
+ sourceType: 'custom',
+ status: 'connected',
+ userId: owner,
+ visibility: 'private',
+ workspaceId,
+ });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('resolvePluginIdentifier with a private connector', () => {
+ it("lets the owner pin their private connector on their private agent's config", async () => {
+ // Regression: validation resolved connectors the way a topic-free run does,
+ // which keeps every private row out, so Agent Builder and installPlugin
+ // refused the connector the agent runs in its own conversation.
+ expect(await resolve(owner, privateAgent)).toEqual({ source: 'connector', status: 'loadable' });
+ });
+
+ it('keeps it unknown to a workspace agent and to a teammate', async () => {
+ expect(await resolve(owner, workspaceAgent)).toMatchObject({ status: 'unknown' });
+ expect(await resolve(mate, privateAgent)).toMatchObject({ status: 'unknown' });
+ });
+
+ it('accepts the identifier while the shared row is usable beside a disconnected private one', async () => {
+ // Regression: validation kept only the private row (it ranks first), which
+ // is disconnected, and refused the identifier as PluginNotConnected though
+ // the connected shared row runs as its own tool set.
+ await serverDB
+ .update(userConnectors)
+ .set({ status: 'disconnected' })
+ .where(eq(userConnectors.visibility, 'private'));
+ await serverDB.insert(userConnectors).values({
+ identifier: 'acme-notes',
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://notes.example.com/shared',
+ name: 'Acme Notes',
+ sourceType: 'custom',
+ status: 'connected',
+ userId: mate,
+ visibility: 'public',
+ workspaceId,
+ });
+
+ expect(await resolve(owner, privateAgent)).toEqual({ source: 'connector', status: 'loadable' });
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/pluginResolution.ts b/apps/server/src/services/toolExecution/serverRuntimes/pluginResolution.ts
index 898a75a59bb..155d00cee8c 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/pluginResolution.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/pluginResolution.ts
@@ -36,7 +36,7 @@ export type PluginResolution =
| { status: 'unknown'; suggestions: string[] };
export interface PluginResolverDeps {
- connectorModel: Pick<ConnectorModel, 'resolveAll'>;
+ connectorModel: Pick<ConnectorModel, 'queryAvailableForAgent'>;
pluginModel: Pick<PluginModel, 'findById' | 'query'>;
}
@@ -70,9 +70,18 @@ export const resolvePluginIdentifier = async (
// A connector shadows a same-named installed plugin, but only once it is
// enabled and connected — a disabled or disconnected row contributes no tools.
- const connectors = await deps.connectorModel.resolveAll(options.agentId);
- const connector = connectors.find((c) => c.identifier === identifier);
- if (connector) return connectorResolution(connector);
+ // Checked against what the target agent loads in its own conversation, so an
+ // owner's private connector counts on their private agent: no topic is
+ // involved in editing a configuration.
+ // An MCP connector may have several rows the agent loads, each its own tool
+ // set (the shared one and its owner's private one): any usable one serves.
+ const connectors = await deps.connectorModel.queryAvailableForAgent(options.agentId);
+ const matching = connectors.filter((c) => c.identifier === identifier);
+ if (matching.length > 0)
+ return (
+ matching.map(connectorResolution).find((resolution) => resolution.status === 'loadable') ??
+ connectorResolution(matching[0])
+ );
const installed = await deps.pluginModel.findById(identifier);
if (installed) {
@@ -247,9 +256,11 @@ export const resolveOrInstallMarketPlugin = async (
]);
const run = runnable.find((c) => c.identifier === identifier);
if (run?.agentId === options.agentId) return resolveExisting();
- const own = configurable.find((c) => c.identifier === identifier);
- if (own && own.id !== run?.id)
- return { installedNow: false, resolution: connectorResolution(own) };
+ // Beside (or instead of) the shared row, the owner's own rows are tool
+ // sets of their own: answer from every row the agent loads (any usable one
+ // serves) rather than install a shared row over them.
+ if (configurable.some((c) => c.identifier === identifier && c.id !== run?.id))
+ return resolveExisting();
}
let manifest: unknown;
diff --git a/apps/server/src/services/widget/__tests__/credentials.test.ts b/apps/server/src/services/widget/__tests__/credentials.test.ts
index a66ff5883d1..ceec4719746 100644
--- a/apps/server/src/services/widget/__tests__/credentials.test.ts
+++ b/apps/server/src/services/widget/__tests__/credentials.test.ts
@@ -108,7 +108,7 @@ describe('resolveWidgetEnv', () => {
);
expect(env).toEqual({ GITHUB_TOKEN: 'agent-tok' });
- expect(model.resolveByIdentifiers).toHaveBeenCalledWith(['github'], 'agt_1');
+ expect(model.resolveByIdentifiers).toHaveBeenCalledWith(['github'], { agentId: 'agt_1' });
});
it('never lets a personal credential reach a workspace widget', async () => {
diff --git a/apps/server/src/services/widget/credentials.ts b/apps/server/src/services/widget/credentials.ts
index 5429aa45ddc..b76735d361e 100644
--- a/apps/server/src/services/widget/credentials.ts
+++ b/apps/server/src/services/widget/credentials.ts
@@ -272,7 +272,11 @@ export const resolveWidgetEnv = async (
...new Set(requirements.map((r) => r.connector).filter((c): c is string => !!c)),
];
const resolved = identifiers.length
- ? await connectorModel.resolveByIdentifiers(identifiers, scope.agentId ?? undefined)
+ ? // No topic: a widget renders for whoever views it, so it only ever
+ // resolves shared connectors, never a member's private one.
+ await connectorModel.resolveByIdentifiers(identifiers, {
+ agentId: scope.agentId ?? undefined,
+ })
: [];
const byIdentifier = new Map<string, DecryptedConnector>();
@@ -326,6 +330,7 @@ export const resolveWidgetEnv = async (
let connector = byIdentifier.get(requirement.connector);
if (connector) {
const link = accountOf.get(connector.id);
+ // The refresh writes through the row's own scope (`tokens.refreshSlot`)
connector = link
? withLinkCredentials(connector, await ensureFreshLinkToken(connector, link, model))
: await ensureFreshConnectorToken(connector, model);
diff --git a/apps/server/src/utils/__tests__/connectorAttribution.test.ts b/apps/server/src/utils/__tests__/connectorAttribution.test.ts
index 2a9cfb7f343..b548b766947 100644
--- a/apps/server/src/utils/__tests__/connectorAttribution.test.ts
+++ b/apps/server/src/utils/__tests__/connectorAttribution.test.ts
@@ -7,7 +7,7 @@ import {
collectBorrowedConnectors,
resolveConnectorAuthorizerId,
resolveUserDisplayMap,
- withTrustedLinkedByUserId,
+ withServerOwnedMetadata,
} from '../connectorAttribution';
vi.mock('@/database/models/user', () => ({
@@ -138,52 +138,81 @@ describe('buildConnectorOwnershipPrompt', () => {
});
});
-describe('withTrustedLinkedByUserId', () => {
- it('drops a client-supplied linkedByUserId on create (no server row)', () => {
- const result = withTrustedLinkedByUserId(
+describe('withServerOwnedMetadata', () => {
+ it('drops a client-supplied composio block on create (no server row)', () => {
+ const result = withServerOwnedMetadata(
{ composio: { connectedAccountId: 'acc_1', linkedByUserId: 'victim' }, other: 1 },
undefined,
);
- // linkedByUserId stripped; all other metadata preserved.
- expect(result).toEqual({ composio: { connectedAccountId: 'acc_1' }, other: 1 });
+ // The whole block goes; all other metadata is preserved.
+ expect(result).toEqual({ other: 1 });
});
it('leaves metadata untouched when the client sends no composio block on create', () => {
const meta = { headers: { a: 'b' } };
- expect(withTrustedLinkedByUserId(meta, undefined)).toBe(meta);
+ expect(withServerOwnedMetadata(meta, undefined)).toBe(meta);
});
- it('forces linkedByUserId back to the stored server value on update (ignores spoof)', () => {
- const result = withTrustedLinkedByUserId(
- { composio: { connectedAccountId: 'acc_1', linkedByUserId: 'victim' } },
- { composio: { linkedByUserId: 'real-owner' } },
+ it("keeps the stored block on update, ignoring the client's account and linker", () => {
+ // Regression: only `linkedByUserId` was trusted, so an edit could point a
+ // row at a teammate's account id read from the shared connections.
+ const result = withServerOwnedMetadata(
+ { composio: { connectedAccountId: 'acc_mate', linkedByUserId: 'victim' }, other: 1 },
+ { composio: { connectedAccountId: 'acc_1', linkedByUserId: 'real-owner' } },
);
expect(result).toEqual({
composio: { connectedAccountId: 'acc_1', linkedByUserId: 'real-owner' },
+ other: 1,
});
});
- it('drops the client value on update when the server row has no linkedByUserId', () => {
- const result = withTrustedLinkedByUserId(
- { composio: { linkedByUserId: 'victim' } },
- { composio: { connectedAccountId: 'acc_1' } },
+ it('drops the client block on update when the stored row has none', () => {
+ const result = withServerOwnedMetadata(
+ { composio: { connectedAccountId: 'acc_mate' }, other: 1 },
+ { other: 0 },
);
- expect(result).toEqual({ composio: {} });
+ expect(result).toEqual({ other: 1 });
});
- it('injects the trusted server value even when the client omits the composio block', () => {
- const result = withTrustedLinkedByUserId(
+ it('carries the stored block over when the client omits it', () => {
+ const result = withServerOwnedMetadata(
{ other: 1 },
- { composio: { linkedByUserId: 'owner' } },
+ { composio: { connectedAccountId: 'acc_1', linkedByUserId: 'owner' } },
);
- expect(result).toEqual({ composio: { linkedByUserId: 'owner' }, other: 1 });
+ expect(result).toEqual({
+ composio: { connectedAccountId: 'acc_1', linkedByUserId: 'owner' },
+ other: 1,
+ });
});
it('passes through undefined (untouched) and null (clear)', () => {
expect(
- withTrustedLinkedByUserId(undefined, { composio: { linkedByUserId: 'x' } }),
+ withServerOwnedMetadata(undefined, { composio: { linkedByUserId: 'x' } }),
).toBeUndefined();
- expect(withTrustedLinkedByUserId(null, { composio: { linkedByUserId: 'x' } })).toBeNull();
+ expect(withServerOwnedMetadata(null, { composio: { linkedByUserId: 'x' } })).toBeNull();
+ });
+
+ // Regression: a member added a shared connector naming a teammate's private
+ // agent as its mount, under the identifier of the owner's private connector.
+ // The mount outranked the owner's row, so the agent's tool calls went to the
+ // member's server.
+ it('drops a client-supplied mount on create', () => {
+ expect(
+ withServerOwnedMetadata({ mountedByAgentId: 'agt-victim', other: 1 }, undefined),
+ ).toEqual({ other: 1 });
+ });
+
+ it("keeps the stored mount on update, ignoring the client's", () => {
+ expect(
+ withServerOwnedMetadata({ mountedByAgentId: 'agt-victim' }, { mountedByAgentId: 'agt-mine' }),
+ ).toEqual({ mountedByAgentId: 'agt-mine' });
+ // Setting one on an unmounted row, or clearing a stored one, goes through
+ // mountToAgent / unmountFromAgent.
+ expect(withServerOwnedMetadata({ mountedByAgentId: 'agt-victim' }, { other: 0 })).toEqual({});
+ expect(withServerOwnedMetadata({ other: 1 }, { mountedByAgentId: 'agt-mine' })).toEqual({
+ mountedByAgentId: 'agt-mine',
+ other: 1,
+ });
});
});
diff --git a/apps/server/src/utils/connectorAttribution.ts b/apps/server/src/utils/connectorAttribution.ts
index ecba4197a1d..f8dc7ef34ce 100644
--- a/apps/server/src/utils/connectorAttribution.ts
+++ b/apps/server/src/utils/connectorAttribution.ts
@@ -29,38 +29,59 @@ export const resolveConnectorAuthorizerId = (connector: ConnectorAttributionRow)
};
/**
- * `linkedByUserId` marks the member whose credentials a Composio tool runs under
- * — it is server-owned, written only by the OAuth connect path
- * (`upsertComposioConnector`). The generic connector create/update accepts
- * free-form `metadata`, so without a guard a member could set
- * `metadata.composio.linkedByUserId` to another user's id and spoof both the
- * attribution tag and the runtime ownership note (and shift the Composio
- * execution entity). This forces the field to the TRUSTED value — the existing
- * DB row's `linkedByUserId` on update, or dropped on create (no server value
- * yet) — ignoring whatever the client supplied. All other metadata is preserved.
+ * The keys of a connector's `metadata` that only server paths write:
+ *
+ * - `composio` is written only by the Composio connect paths
+ * (`upsertComposioConnector`, the plugin bootstrap sync). It names the
+ * account a tool runs (`connectedAccountId`) and the member whose credentials
+ * it runs under (`linkedByUserId`), and the rows naming an account decide who
+ * may refresh or delete it (`findComposioAccountConflict`).
+ * - `mountedByAgentId` locks a base row onto one agent, and at run time that
+ * mount outranks the agent owner's own private row of the same identifier
+ * (`ConnectorModel.pickByPriority`). Only `mountToAgent` sets it, after
+ * checking that the caller created the agent and may hand it the row.
+ * `unmountFromAgent` and the agent lifecycle helpers clear it.
+ */
+const SERVER_OWNED_METADATA_KEYS = ['composio', 'mountedByAgentId'] as const;
+
+/**
+ * The generic connector create/update accepts free-form `metadata`, and every
+ * member reads the account ids of the workspace's shared connections and the
+ * ids of the agents they can see. Without a guard a member could:
+ * - name a teammate's Composio account on a row of their own, spoofing the
+ * attribution tag and the runtime ownership note, or, on a private row nobody
+ * else can see, claiming the account so its real owner can no longer refresh
+ * or remove it;
+ * - mount a shared connector of their own on a teammate's private agent, under
+ * the identifier of the owner's private connector, so the agent's tool calls
+ * (and their arguments) go to the member's server instead.
+ *
+ * This replaces whatever the client sent for each {@link SERVER_OWNED_METADATA_KEYS}
+ * key with the TRUSTED value: the stored row's on update, none on create, where
+ * there is no stored row. All other metadata is preserved.
*
* `serverMetadata` is the persisted row's metadata (pass `undefined` on create).
- * Returns the client metadata untouched when neither side has anything Composio.
+ * Returns the client metadata untouched when neither side has a server-owned key.
*/
-export const withTrustedLinkedByUserId = (
+export const withServerOwnedMetadata = (
clientMetadata: Record<string, unknown> | null | undefined,
serverMetadata: Record<string, unknown> | null | undefined,
): Record<string, unknown> | null | undefined => {
// undefined → "leave metadata untouched"; null → "clear it". Nothing to guard.
if (!clientMetadata) return clientMetadata;
- const serverLinked = (serverMetadata as { composio?: { linkedByUserId?: string } } | null)
- ?.composio?.linkedByUserId;
- const clientComposio = (clientMetadata as { composio?: Record<string, unknown> }).composio;
-
- // No composio block from the client and no trusted server value → nothing to do.
- if (!clientComposio && serverLinked === undefined) return clientMetadata;
+ const guarded = SERVER_OWNED_METADATA_KEYS.filter(
+ (key) => key in clientMetadata || serverMetadata?.[key] !== undefined,
+ );
+ if (guarded.length === 0) return clientMetadata;
- const composio: Record<string, unknown> = { ...clientComposio };
- if (serverLinked === undefined) delete composio.linkedByUserId;
- else composio.linkedByUserId = serverLinked;
-
- return { ...clientMetadata, composio };
+ const result = { ...clientMetadata };
+ for (const key of guarded) {
+ const trusted = serverMetadata?.[key];
+ if (trusted === undefined) delete result[key];
+ else result[key] = trusted;
+ }
+ return result;
};
export interface UserDisplayInfo {
diff --git a/docs/usage/agent/connectors.mdx b/docs/usage/agent/connectors.mdx
index dc3c8167bf9..b2522b98368 100644
--- a/docs/usage/agent/connectors.mdx
+++ b/docs/usage/agent/connectors.mdx
@@ -16,13 +16,13 @@ Add the tools and skills your agent needs, then choose whether to pin them, use
## What can you connect?
-| Type | Purpose | Examples |
-| ----------------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------------------- |
-| LobeHub built-in capabilities | Manage tasks, create content, and work in LobeHub | Task Tools, Documents, Message, Image Generation, Artifacts, and more |
-| Third-party services | Access authorized resources and use exposed actions | GitHub, Linear, Gmail, Slack, and more |
-| Community skills | Specialized instructions, workflows, and supporting resources | Skills tab in the Skill Store |
-| Community MCP integrations | Access external tools through the Model Context Protocol | MCP tab in the Skill Store |
-| Your own skills | Use skills you created or obtained elsewhere | GitHub, URL, and ZIP imports |
+| Type | Purpose | Examples |
+| ----------------------------- | ------------------------------------------------------------- | --------------------------------------------------------------------- |
+| LobeHub built-in capabilities | Manage tasks, create content, and work in LobeHub | Task Tools, Documents, Message, Image Generation, Artifacts, and more |
+| Third-party services | Access authorized resources and use exposed actions | GitHub, Linear, Gmail, Slack, and more |
+| Community skills | Specialized instructions, workflows, and supporting resources | Skills tab in the Skill Store |
+| Community MCP integrations | Access external tools through the Model Context Protocol | MCP tab in the Skill Store |
+| Your own skills | Use skills you created or obtained elsewhere | GitHub, URL, and ZIP imports |
Availability depends on the client, deployment settings, permissions, and execution environment. Installing a skill does not automatically grant access to external accounts or local files.
@@ -73,6 +73,7 @@ LobeHub built-in capabilities cover task management, documents, messaging, image
Check tool access and permissions before use. After creation, inspect the saved task, executing agent, inputs, and output requirements. To run recurring work, configure and enable a schedule, then check the timezone, next run, and status. A deadline alone does not trigger execution or notifications. See [Scheduled Tasks](/docs/usage/agent/scheduled-task). Before deletion, identify the target and whether subtasks are included.
<a id="delivery-checks-and-acceptance" />
+
<a id="acceptance" />
#### Acceptance
diff --git a/docs/usage/agent/connectors.zh-CN.mdx b/docs/usage/agent/connectors.zh-CN.mdx
index d2013ca9f3d..a413a9d5440 100644
--- a/docs/usage/agent/connectors.zh-CN.mdx
+++ b/docs/usage/agent/connectors.zh-CN.mdx
@@ -16,13 +16,13 @@ tags:
## 可以连接什么
-| 类型 | 作用 | 示例 |
-| ----------------- | ------------------------------------------ | -------------------------------------------- |
-| LobeHub 内置能力 | 在 LobeHub 中管理任务、创作内容和执行操作 | 任务工具、文档、消息、图片生成、Artifacts 等 |
-| 第三方服务 | 访问授权账户资源,执行连接器支持的操作 | GitHub、Linear、Gmail、Slack 等 |
-| 社区 Skills | 领域指令、工作流程及配套资源 | 技能商店的 Skills 标签 |
-| 社区 MCP | 通过 Model Context Protocol 接入工具 | 技能商店的 MCP 标签 |
-| 自己导入的 Skills | 使用自己编写或从其他来源取得的技能 | GitHub、URL、ZIP 导入 |
+| 类型 | 作用 | 示例 |
+| ------------ | ------------------------------ | --------------------------- |
+| LobeHub 内置能力 | 在 LobeHub 中管理任务、创作内容和执行操作 | 任务工具、文档、消息、图片生成、Artifacts 等 |
+| 第三方服务 | 访问授权账户资源,执行连接器支持的操作 | GitHub、Linear、Gmail、Slack 等 |
+| 社区 Skills | 领域指令、工作流程及配套资源 | 技能商店的 Skills 标签 |
+| 社区 MCP | 通过 Model Context Protocol 接入工具 | 技能商店的 MCP 标签 |
+| 自己导入的 Skills | 使用自己编写或从其他来源取得的技能 | GitHub、URL、ZIP 导入 |
可见项目取决于客户端、部署设置、账户权限和执行环境。安装技能不会自动授予第三方账户或本机文件访问权限。
@@ -48,11 +48,11 @@ tags:
### 固定、自动与禁用
-| 模式 | 含义 | 适用情况 |
-| -------------- | -------------------------------------------------- | ---------------------- |
-| 固定/固定启用 | 设为当前助理的默认加载项,仍受运行环境与权限限制 | 经常使用的工具和技能 |
-| 自动 | 允许助理按任务需要发现和激活,不是每次加载全部内容 | 偶尔使用的工具和技能 |
-| 禁用 | 当前助理不使用该工具或技能 | 暂时不需要或不希望使用 |
+| 模式 | 含义 | 适用情况 |
+| ------- | ------------------------- | ----------- |
+| 固定/固定启用 | 设为当前助理的默认加载项,仍受运行环境与权限限制 | 经常使用的工具和技能 |
+| 自动 | 允许助理按任务需要发现和激活,不是每次加载全部内容 | 偶尔使用的工具和技能 |
+| 禁用 | 当前助理不使用该工具或技能 | 暂时不需要或不希望使用 |
在条目的操作菜单中选择模式。「自动」分组开关控制自动激活,不是批量安装或卸载。取消固定不等于卸载,禁用不等于撤销账户授权;部分系统工具的选项不同。
@@ -66,13 +66,14 @@ LobeHub 内置工具可以管理任务、文档和消息,生成图片,执行
### 任务工具(Task Tools)
-**用途:**通过对话创建和管理任务、子任务、依赖、执行助理、状态和评论。你也可以设置验收要求、开始执行任务,改动会显示在[任务界面](/zh/docs/usage/getting-started/task)中。
+\*\* 用途:\*\* 通过对话创建和管理任务、子任务、依赖、执行助理、状态和评论。你也可以设置验收要求、开始执行任务,改动会显示在[任务界面](/zh/docs/usage/getting-started/task)中。
**试着说:**「创建新品发布任务,拆成文案、设计和最终检查;最终检查依赖前两个任务完成。」
使用前确认工具与权限可用;创建后检查保存的任务、执行助理、输入和结果要求。如需定期执行,先配置并启用计划,再核对时区、下次执行时间和状态。仅设置截止时间不会触发执行或通知,详见[定时任务](/zh/docs/usage/agent/scheduled-task)。删除前确认目标及子任务范围。
<a id="delivery-checks-and-acceptance" />
+
<a id="acceptance" />
#### 验收(Acceptance)
@@ -112,97 +113,97 @@ lh task edit T-1 --status completed
### 文档(Documents)
-**用途:**创建和维护助理长期保存的文档,适合报告、笔记、项目背景和参考资料。
+\*\* 用途:\*\* 创建和维护助理长期保存的文档,适合报告、笔记、项目背景和参考资料。
-**启用后可以:**创建、读取、重命名、复制和删除文档;替换全文或精确修改局部;列出文档并调整加载规则。文档可以属于助理,也可以关联当前话题。
+\*\* 启用后可以:\*\* 创建、读取、重命名、复制和删除文档;替换全文或精确修改局部;列出文档并调整加载规则。文档可以属于助理,也可以关联当前话题。
**试着说:**「创建一份竞品调研文档,保留来源;以后只更新价格和产品变化部分。」
-**注意:**上传的 PDF、图片等源文件可以通过资源库或知识库读取。文档面板、范围和历史见[助理文档库](/zh/docs/usage/agent/agent-documents)。
+\*\* 注意:\*\* 上传的 PDF、图片等源文件可以通过资源库或知识库读取。文档面板、范围和历史见[助理文档库](/zh/docs/usage/agent/agent-documents)。
<a id="message" />
### 消息(Message)
-**用途:**操作已配置的消息渠道,并管理相关 Bot 和连接。
+\*\* 用途:\*\* 操作已配置的消息渠道,并管理相关 Bot 和连接。
-**启用后可以:**在渠道支持的范围内发送、读取、编辑和管理消息,查看或管理 Bot 连接和消息路由。
+\*\* 启用后可以:\*\* 在渠道支持的范围内发送、读取、编辑和管理消息,查看或管理 Bot 连接和消息路由。
**试着说:**「把确认后的项目摘要发送到已连接的团队频道,发送前让我检查。」
-**注意:**先配置平台与有效连接。可读取的历史记录、编辑和删除操作因平台而异。Bot 接入与下表中的 Slack、WhatsApp 服务连接器是不同配置,参见[消息渠道](/zh/docs/usage/channels/overview)。
+\*\* 注意:\*\* 先配置平台与有效连接。可读取的历史记录、编辑和删除操作因平台而异。Bot 接入与下表中的 Slack、WhatsApp 服务连接器是不同配置,参见[消息渠道](/zh/docs/usage/channels/overview)。
<a id="image-generation" />
### 图片生成(Image Generation)
-**用途:**在对话中调用 LobeHub 配置的图片模型,而不要求当前聊天模型本身输出图片。
+\*\* 用途:\*\* 在对话中调用 LobeHub 配置的图片模型,而不要求当前聊天模型本身输出图片。
-**启用后可以:**查询可用模型与参数,提交图片生成请求,查询生成状态。
+\*\* 启用后可以:\*\* 查询可用模型与参数,提交图片生成请求,查询生成状态。
**试着说:**「生成横版产品宣传图,主体在右侧,左侧留出标题区域。」
-**注意:**需要可用图片模型、服务商配置与额度。尺寸、参考图等参数取决于模型。添加工具后,还需检查当前会话的运行模式能否使用该工具。
+\*\* 注意:\*\* 需要可用图片模型、服务商配置与额度。尺寸、参考图等参数取决于模型。添加工具后,还需检查当前会话的运行模式能否使用该工具。
<a id="credentials" />
### 凭据管理(Credentials)
-**用途:**辅助处理第三方账户授权和敏感凭据。
+\*\* 用途:\*\* 辅助处理第三方账户授权和敏感凭据。
-**启用后可以:**发起支持的连接流程,通过安全入口保存凭据,并在支持的云端执行环境中提供所需环境变量。
+\*\* 启用后可以:\*\* 发起支持的连接流程,通过安全入口保存凭据,并在支持的云端执行环境中提供所需环境变量。
**试着说:**「引导我安全连接服务,不要让我把密钥发到对话中。」
-**注意:**向云沙盒注入凭据,不等于向本地设备提供凭据。凭据是否可用取决于执行位置。
+\*\* 注意:\*\* 向云沙盒注入凭据,不等于向本地设备提供凭据。凭据是否可用取决于执行位置。
<a id="calculator" />
### 计算器(Calculator)
-**用途:**执行数值计算与符号数学运算。
+\*\* 用途:\*\* 执行数值计算与符号数学运算。
-**启用后可以:**计算表达式、使用变量、排序、进制转换、解方程,以及求导、积分、极限等。
+\*\* 启用后可以:\*\* 计算表达式、使用变量、排序、进制转换、解方程,以及求导、积分、极限等。
**试着说:**「按每月增长 3% 计算未来一年的收入,列出逐月结果。」
-**注意:**计算器不获取外部数据。计算前,可以先用其他工具查询所需的实时汇率或价格。
+\*\* 注意:\*\* 计算器不获取外部数据。计算前,可以先用其他工具查询所需的实时汇率或价格。
<a id="artifacts" />
### Artifacts
-**用途:**在独立预览面板中展示和迭代视觉或交互作品。
+\*\* 用途:\*\* 在独立预览面板中展示和迭代视觉或交互作品。
-**启用后可以:**生成 HTML 网页、React 交互组件、仪表盘、SVG 图形和简单浏览器游戏;通过后续对话修改配色、布局或交互。
+\*\* 启用后可以:\*\* 生成 HTML 网页、React 交互组件、仪表盘、SVG 图形和简单浏览器游戏;通过后续对话修改配色、布局或交互。
**试着说:**「做一个可切换月度和年度价格的套餐对比页,直接预览;然后加深色模式。」
-**注意:**普通文章和代码解释留在对话中;持续维护的文本用 Documents;模型生成图像用 Image Generation。准备自包含预览时,无需启动云沙盒。外部 API、资源和浏览器权限可能受预览环境限制;该技能不支持通用的 PDF、PPTX 导出。查看预览并测试交互,按面板可用操作查看、复制或保存代码。
+\*\* 注意:\*\* 普通文章和代码解释留在对话中;持续维护的文本用 Documents;模型生成图像用 Image Generation。准备自包含预览时,无需启动云沙盒。外部 API、资源和浏览器权限可能受预览环境限制;该技能不支持通用的 PDF、PPTX 导出。查看预览并测试交互,按面板可用操作查看、复制或保存代码。
<a id="lobehub" />
### LobeHub
-**用途:**指导助理通过 LobeHub CLI 操作平台资源。
+\*\* 用途:\*\* 指导助理通过 LobeHub CLI 操作平台资源。
-**启用后可以:**在环境和权限允许时,管理助理、话题、文档、知识库、模型、插件和 Bot 等资源。
+\*\* 启用后可以:\*\* 在环境和权限允许时,管理助理、话题、文档、知识库、模型、插件和 Bot 等资源。
**试着说:**「把这个助理的开场白改为适合客户研究的版本。」
-**注意:**需要实际可用的 CLI 和账户权限。技能中的操作说明不会绕过权限,也不会自动执行修改。
+\*\* 注意:\*\* 需要实际可用的 CLI 和账户权限。技能中的操作说明不会绕过权限,也不会自动执行修改。
<a id="agent-browser" />
### 助手浏览器(Agent Browser)
-**用途:**用于浏览器和 Electron 页面自动化。
+\*\* 用途:\*\* 用于浏览器和 Electron 页面自动化。
-**启用后可以:**导航页面、点击、填写表单、截图和提取内容,适合需要真实页面交互的网站。
+\*\* 启用后可以:\*\* 导航页面、点击、填写表单、截图和提取内容,适合需要真实页面交互的网站。
**试着说:**「打开产品后台并整理本月数据;遇到登录时让我接手,不要提交修改。」
-**注意:**使用助手浏览器需要支持设备执行的环境;可在桌面端技能商店中添加。它不同于系统管理的 Browser 工具和网页搜索,参见[内置浏览器](/zh/docs/usage/agent/built-in-browser)与[执行设备](/zh/docs/usage/agent/execution-devices)。
+\*\* 注意:\*\* 使用助手浏览器需要支持设备执行的环境;可在桌面端技能商店中添加。它不同于系统管理的 Browser 工具和网页搜索,参见[内置浏览器](/zh/docs/usage/agent/built-in-browser)与[执行设备](/zh/docs/usage/agent/execution-devices)。
### 网页搜索、记忆和知识库在哪里?
@@ -214,36 +215,36 @@ lh task edit T-1 --status completed
你可以连接以下服务,让助理处理已授权账户中的内容。连接后,在连接器详情中查看可用操作和权限;可用操作因账户、服务套餐和部署配置而异。
-| 名称 | 主要用途 | 使用提示 |
-| ---------------- | ------------------------------------------- | ------------------------------------------------------------ |
-| GitHub | 查找仓库、代码、Issue 和 PR,协助开发协作 | 仓库访问和修改权限取决于你的授权;合并 PR 前先确认目标分支。 |
-| Linear | 管理 Issue、项目、迭代、文档和评论 | 按团队和项目权限访问;修改前确认目标 Issue 和字段。 |
-| Outlook Calendar | 查看和管理日历事件、安排会议 | 与 Outlook Mail、OneDrive 分别连接和授权。 |
-| Notion | 管理页面、数据库和知识内容 | 授权需要使用的页面和数据库;未共享的内容无法访问。 |
-| PostHog | 查询产品分析、仪表盘、实验和 feature flags | 在技能商店中点击「连接」,按提示授权项目。 |
-| X | 搜索帖子、获取用户资料,辅助内容发布和互动 | 可用操作取决于账户权限和连接器支持的工具。 |
-| Vercel | 查询项目与部署状态,辅助处理日志和部署配置 | 连接后检查可访问的项目;修改部署配置前确认目标环境。 |
-| Gmail | 查找和读取邮件,辅助撰写、发送及标签管理 | 邮件读取、发送和标签管理需要相应授权。 |
-| Google Drive | 搜索、组织、上传和分享文件 | 只能访问已授权的文件;分享前确认接收人和访问范围。 |
-| Google Calendar | 查看日历、创建事件和安排会议 | 确认使用的日历、时区和事件修改权限。 |
-| Slack | 查找对话、发送消息、处理频道信息 | 访问范围受频道权限限制;与消息工具中的 Bot 接入分别配置。 |
-| Airtable | 查询、创建和更新记录 | 确认已授权所需 base 和 table。 |
-| Google Sheets | 读取、写入和分析电子表格 | 授权目标表格;修改前明确工作表和单元格范围。 |
-| Google Docs | 创建、读取、编辑和格式化文档 | 需要目标文档的访问或编辑权限。 |
-| Supabase | 辅助数据库、认证和存储相关工作 | 按项目授权,并只开放任务需要的数据库与服务权限。 |
-| Confluence | 搜索页面、维护知识内容和空间资料 | 访问范围受站点、空间和页面权限限制。 |
-| Jira | 查询和创建工单、更新状态、跟进项目与 sprint | 确认项目权限以及允许的状态转换。 |
-| ClickUp | 创建和更新任务、跟踪项目 | 确认工作区、列表和任务访问权限。 |
-| Dropbox | 查找、上传、下载、分享和组织文件 | 分享或移动文件前确认目标位置和访问范围。 |
-| Figma | 读取设计信息、浏览组件、导出素材 | 需要设计文件访问权限;具体可用操作见连接器详情。 |
-| HubSpot | 联系人、交易和销售 pipeline 等 CRM 工作 | 联系人、交易等数据按账户角色授权。 |
-| OneDrive | 查找、组织、上传、下载和分享文件 | 与 Outlook Calendar、Outlook Mail 分别连接;只访问授权文件。 |
-| Outlook Mail | 查找、读取和发送邮件,管理收件箱 | 与 Outlook Calendar 分别授权;发送前检查接收人。 |
-| Salesforce | 查询 CRM 记录、跟进线索、更新商机 | 访问受对象、字段和组织权限限制。 |
-| WhatsApp | 通过 Business API 辅助消息、媒体和客户沟通 | 需要 WhatsApp Business API 账户,受业务消息规则限制。 |
-| YouTube | 搜索视频、读取视频信息和可用字幕 | 字幕仅在对应视频提供且可访问时可用。 |
-| Zendesk | 创建、更新和跟踪支持工单,查询客户资料 | 访问受客服角色和工单权限限制。 |
-| Cal.com | 查询空闲时间、预约会议、管理活动类型 | 确认可用时间、时区及预约权限。 |
+| 名称 | 主要用途 | 使用提示 |
+| ---------------- | ---------------------------- | --------------------------------------------- |
+| GitHub | 查找仓库、代码、Issue 和 PR,协助开发协作 | 仓库访问和修改权限取决于你的授权;合并 PR 前先确认目标分支。 |
+| Linear | 管理 Issue、项目、迭代、文档和评论 | 按团队和项目权限访问;修改前确认目标 Issue 和字段。 |
+| Outlook Calendar | 查看和管理日历事件、安排会议 | 与 Outlook Mail、OneDrive 分别连接和授权。 |
+| Notion | 管理页面、数据库和知识内容 | 授权需要使用的页面和数据库;未共享的内容无法访问。 |
+| PostHog | 查询产品分析、仪表盘、实验和 feature flags | 在技能商店中点击「连接」,按提示授权项目。 |
+| X | 搜索帖子、获取用户资料,辅助内容发布和互动 | 可用操作取决于账户权限和连接器支持的工具。 |
+| Vercel | 查询项目与部署状态,辅助处理日志和部署配置 | 连接后检查可访问的项目;修改部署配置前确认目标环境。 |
+| Gmail | 查找和读取邮件,辅助撰写、发送及标签管理 | 邮件读取、发送和标签管理需要相应授权。 |
+| Google Drive | 搜索、组织、上传和分享文件 | 只能访问已授权的文件;分享前确认接收人和访问范围。 |
+| Google Calendar | 查看日历、创建事件和安排会议 | 确认使用的日历、时区和事件修改权限。 |
+| Slack | 查找对话、发送消息、处理频道信息 | 访问范围受频道权限限制;与消息工具中的 Bot 接入分别配置。 |
+| Airtable | 查询、创建和更新记录 | 确认已授权所需 base 和 table。 |
+| Google Sheets | 读取、写入和分析电子表格 | 授权目标表格;修改前明确工作表和单元格范围。 |
+| Google Docs | 创建、读取、编辑和格式化文档 | 需要目标文档的访问或编辑权限。 |
+| Supabase | 辅助数据库、认证和存储相关工作 | 按项目授权,并只开放任务需要的数据库与服务权限。 |
+| Confluence | 搜索页面、维护知识内容和空间资料 | 访问范围受站点、空间和页面权限限制。 |
+| Jira | 查询和创建工单、更新状态、跟进项目与 sprint | 确认项目权限以及允许的状态转换。 |
+| ClickUp | 创建和更新任务、跟踪项目 | 确认工作区、列表和任务访问权限。 |
+| Dropbox | 查找、上传、下载、分享和组织文件 | 分享或移动文件前确认目标位置和访问范围。 |
+| Figma | 读取设计信息、浏览组件、导出素材 | 需要设计文件访问权限;具体可用操作见连接器详情。 |
+| HubSpot | 联系人、交易和销售 pipeline 等 CRM 工作 | 联系人、交易等数据按账户角色授权。 |
+| OneDrive | 查找、组织、上传、下载和分享文件 | 与 Outlook Calendar、Outlook Mail 分别连接;只访问授权文件。 |
+| Outlook Mail | 查找、读取和发送邮件,管理收件箱 | 与 Outlook Calendar 分别授权;发送前检查接收人。 |
+| Salesforce | 查询 CRM 记录、跟进线索、更新商机 | 访问受对象、字段和组织权限限制。 |
+| WhatsApp | 通过 Business API 辅助消息、媒体和客户沟通 | 需要 WhatsApp Business API 账户,受业务消息规则限制。 |
+| YouTube | 搜索视频、读取视频信息和可用字幕 | 字幕仅在对应视频提供且可访问时可用。 |
+| Zendesk | 创建、更新和跟踪支持工单,查询客户资料 | 访问受客服角色和工单权限限制。 |
+| Cal.com | 查询空闲时间、预约会议、管理活动类型 | 确认可用时间、时区及预约权限。 |
### 授权与工具权限
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 303159ad825..fc5b509875b 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -2195,14 +2195,20 @@
"skillStore.wantMore.feedback.title": "[Skill Request] Summarize the skill you need in one sentence",
"skillStore.wantMore.reachedEnd": "You've reached the end. Can't find what you need?",
"skillView.browseStoreDesc": "Find and install skills for your agents",
+ "skillView.connectorTabs.private": "Private",
+ "skillView.connectorTabs.workspace": "Workspace",
"skillView.connectors": "Connectors",
"skillView.connectorsDesc": "Connect the apps and tools your agents can use. Open one to see its account and tools.",
"skillView.empty.description": "Browse the Skill Store or import a skill from the Add menu.",
"skillView.empty.search": "No skills match “{{keyword}}”",
"skillView.empty.title": "No skills yet",
+ "skillView.privateConnectorsDesc": "Only you can see these connectors, and only your private agents use them. Workspace agents never load them.",
+ "skillView.privateConnectorsEmpty.desc": "Add a custom connector here to keep it to yourself and your private agents.",
+ "skillView.privateConnectorsEmpty.title": "No private connectors yet",
"skillView.search.placeholder": "Search skills",
"skillView.skills": "Skills",
"skillView.skillsDesc": "Give your agents task-specific skills. Open a skill to see its instructions and resources.",
+ "skillView.workspaceConnectorsDesc": "Shared with every member, and every agent in this workspace can use them. Open one to see its account and tools.",
"startConversation": "Start Conversation",
"storage.actions.copyAgentGroups.button": "Copy to…",
"storage.actions.copyAgentGroups.desc": "Copy agent groups and their member agents into another workspace or personal account.",
@@ -2754,6 +2760,8 @@
"tools.plugins.management": "Skill Management",
"tools.plugins.noEnabled": "No skills enabled",
"tools.plugins.store": "Add skill",
+ "tools.privateConnector.tag": "Private",
+ "tools.privateConnector.tooltip": "Your private connector: only you can see it, and only your private agents load it.",
"tools.search": "Search skills...",
"tools.skillActivateMode.auto.desc": "AI can autonomously activate tools, run skills, and install new skills from the store",
"tools.skillActivateMode.auto.title": "Auto",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 08d3b139abe..25678477001 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -2195,14 +2195,20 @@
"skillStore.wantMore.feedback.title": "[技能申请] 请用一句话概括您需要的技能",
"skillStore.wantMore.reachedEnd": "已经到底了,未找到所需技能?",
"skillView.browseStoreDesc": "查找并安装适合助理的技能",
+ "skillView.connectorTabs.private": "私人",
+ "skillView.connectorTabs.workspace": "工作区",
"skillView.connectors": "连接器",
"skillView.connectorsDesc": "连接助理可以调用的应用和工具。点开一项,查看授权账号和工具清单。",
"skillView.empty.description": "通过「添加」菜单浏览技能商店或导入技能。",
"skillView.empty.search": "没有找到与「{{keyword}}」匹配的技能",
"skillView.empty.title": "暂无技能",
+ "skillView.privateConnectorsDesc": "这些连接器只有你能看到,也只有你的私人助理会使用。工作区助理不会加载它们。",
+ "skillView.privateConnectorsEmpty.desc": "在这里添加自定义连接器,只供你自己和你的私人助理使用。",
+ "skillView.privateConnectorsEmpty.title": "还没有私人连接器",
"skillView.search.placeholder": "搜索技能",
"skillView.skills": "技能",
"skillView.skillsDesc": "为助理添加完成特定任务的技能。点开一项,查看使用说明和资源。",
+ "skillView.workspaceConnectorsDesc": "与所有成员共享,工作区内的每个助理都能使用。点开一项,查看授权账号和工具清单。",
"startConversation": "开始对话",
"storage.actions.copyAgentGroups.button": "复制到…",
"storage.actions.copyAgentGroups.desc": "将代理组及其成员代理复制到另一个工作区或个人账户。",
@@ -2754,6 +2760,8 @@
"tools.plugins.management": "技能管理",
"tools.plugins.noEnabled": "暂无启用技能",
"tools.plugins.store": "添加技能",
+ "tools.privateConnector.tag": "私人",
+ "tools.privateConnector.tooltip": "你的私人连接器:只有你能看到,也只有你的私人助理会加载它。",
"tools.search": "搜索技能...",
"tools.skillActivateMode.auto.desc": "AI 可自主激活工具、运行技能,并从商店安装新技能",
"tools.skillActivateMode.auto.title": "自动",
diff --git a/packages/builtin-tool-activator/src/ExecutionRuntime/__tests__/activateTools-resolution.test.ts b/packages/builtin-tool-activator/src/ExecutionRuntime/__tests__/activateTools-resolution.test.ts
index cd77adaa855..a3040f9d7e7 100644
--- a/packages/builtin-tool-activator/src/ExecutionRuntime/__tests__/activateTools-resolution.test.ts
+++ b/packages/builtin-tool-activator/src/ExecutionRuntime/__tests__/activateTools-resolution.test.ts
@@ -43,6 +43,19 @@ describe('ActivatorExecutionRuntime.activateTools — request-name resolution',
expect(service.markActivated).toHaveBeenCalledWith(['lobe-web-browsing']);
});
+ it('asks the host for what the conversation may discover', async () => {
+ // A private agent's own connectors are discoverable in its own topic only
+ const service = buildService([webBrowsingManifest]);
+ const runtime = new ActivatorExecutionRuntime({ service });
+ const run = { agentId: 'agt-private', topicId: 'tpc-own' };
+
+ await runtime.activateTools({ identifiers: ['search'], reason: 'test' }, run);
+
+ expect(service.getToolManifests).toHaveBeenCalledWith(['search'], run);
+ expect(service.listToolManifests).toHaveBeenCalledWith(run);
+ expect(service.getToolManifests).toHaveBeenLastCalledWith(['lobe-web-browsing'], run);
+ });
+
it('resolves a bare API name by loading the full discoverable list', async () => {
// Codex P2 on PR #20791: the probe sends only the API name to the
// identifier-keyed map (no manifests come back), so the unique bare-name
@@ -52,7 +65,7 @@ describe('ActivatorExecutionRuntime.activateTools — request-name resolution',
const result = await runtime.activateTools({ identifiers: ['search'], reason: 'test' });
- expect(service.getToolManifests).toHaveBeenCalledWith(['search']);
+ expect(service.getToolManifests).toHaveBeenCalledWith(['search'], undefined);
expect(service.listToolManifests).toHaveBeenCalled();
expect(result.content).toContain('Successfully activated tools: lobe-web-browsing.search');
expect(result.state?.notFound).toEqual([]);
diff --git a/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts b/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts
index a74853644fa..53fee473c06 100644
--- a/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts
@@ -37,7 +37,11 @@ export interface ActivatorRuntimeService {
*/
explainNotFound?: (identifier: string) => string | undefined;
getActivatedToolIds: () => string[];
- getToolManifests: (identifiers: string[]) => Promise<ToolManifestInfo[]>;
+ /**
+ * `run` is the conversation the activation runs in: what is discoverable
+ * (a private agent's own connectors among it) depends on it.
+ */
+ getToolManifests: (identifiers: string[], run?: ActivatorRun) => Promise<ToolManifestInfo[]>;
/**
* Full list of discoverable tool manifests for this run, when the host can
* provide it. Two uses, both about requests the identifier-keyed
@@ -54,10 +58,16 @@ export interface ActivatorRuntimeService {
* Scoping to discoverable tools stays the host's responsibility, same as
* `getToolManifests`.
*/
- listToolManifests?: () => Promise<ToolManifestInfo[]>;
+ listToolManifests?: (run?: ActivatorRun) => Promise<ToolManifestInfo[]>;
markActivated: (identifiers: string[]) => void;
}
+/** The conversation an activation runs in. */
+export interface ActivatorRun {
+ agentId?: string;
+ topicId?: string;
+}
+
export interface ActivatorExecutionRuntimeOptions {
service: ActivatorRuntimeService;
}
@@ -212,7 +222,10 @@ export class ActivatorExecutionRuntime {
return this.service.activateSkill(args);
}
- async activateTools(args: ActivateToolsParams): Promise<BuiltinServerRuntimeOutput> {
+ async activateTools(
+ args: ActivateToolsParams,
+ run?: ActivatorRun,
+ ): Promise<BuiltinServerRuntimeOutput> {
const { identifiers } = args;
if (!identifiers || identifiers.length === 0) {
@@ -250,6 +263,7 @@ export class ActivatorExecutionRuntime {
const prefix = id.slice(0, separatorIndex);
return prefix !== id ? [id, prefix] : [id];
}),
+ run,
);
const unresolved = identifiers.filter(
(id) => resolveActivationIdentifier(id, discoveryManifests) === undefined,
@@ -259,7 +273,7 @@ export class ActivatorExecutionRuntime {
needsDiscoveryList(unresolved) &&
typeof this.service.listToolManifests === 'function'
) {
- discoveryManifests = await this.service.listToolManifests();
+ discoveryManifests = await this.service.listToolManifests(run);
}
// Deduplicate after resolution: two wire names of the same plugin
// (`lobe-web-browsing____search`, `…____crawlSinglePage`) both resolve
@@ -283,7 +297,7 @@ export class ActivatorExecutionRuntime {
}
// Fetch manifests for tools to activate
- const manifests = await this.service.getToolManifests(toActivate);
+ const manifests = await this.service.getToolManifests(toActivate, run);
const foundIdentifiers = new Set(manifests.map((m) => m.identifier));
const notFoundAsTools = toActivate.filter((id) => !foundIdentifiers.has(id));
diff --git a/packages/builtin-tool-activator/src/executor/index.ts b/packages/builtin-tool-activator/src/executor/index.ts
index 61db5976b60..91a0235f1ee 100644
--- a/packages/builtin-tool-activator/src/executor/index.ts
+++ b/packages/builtin-tool-activator/src/executor/index.ts
@@ -59,7 +59,11 @@ class ActivatorExecutor extends BaseExecutor<typeof ActivatorApiName> {
return { stop: true, success: false };
}
- const result = await this.getRuntime(ctx).activateTools(params);
+ // Discoverability follows the conversation the call runs in
+ const result = await this.getRuntime(ctx).activateTools(params, {
+ agentId: ctx.agentId,
+ topicId: ctx.topicId ?? undefined,
+ });
if (result.success) {
return { content: result.content, state: result.state, success: true };
diff --git a/packages/context-engine/src/engine/tools/ToolsEngine.ts b/packages/context-engine/src/engine/tools/ToolsEngine.ts
index 287471913f3..dae4d7e509e 100644
--- a/packages/context-engine/src/engine/tools/ToolsEngine.ts
+++ b/packages/context-engine/src/engine/tools/ToolsEngine.ts
@@ -19,6 +19,11 @@ const log = debug('context-engine:tools-engine');
*/
export class ToolsEngine {
private manifestSchemas: Map<string, LobeToolManifest>;
+ /**
+ * Connector rows sharing a base identifier, by that identifier: the tool ids
+ * of every row's tool set other than the one keyed by the identifier itself.
+ */
+ private connectorRowToolIds = new Map<string, string[]>();
private enableChecker?: PluginEnableChecker;
private functionCallChecker?: FunctionCallChecker;
private defaultToolIds: string[];
@@ -37,6 +42,7 @@ export class ToolsEngine {
this.manifestSchemas = new Map(
options.manifestSchemas.map((schema) => [schema.identifier, schema]),
);
+ this.indexConnectorRows();
this.enableChecker = options.enableChecker;
this.functionCallChecker = options.functionCallChecker;
@@ -192,6 +198,7 @@ export class ToolsEngine {
reason: 'not_found' | 'disabled' | 'incompatible';
}> = [];
+ pluginIds = this.expandConnectorRows(pluginIds);
log('Filtering plugins: %o', pluginIds);
// If function calling is not supported, filter all plugins as incompatible
@@ -220,12 +227,14 @@ export class ToolsEngine {
}
// Use injected checker function or default check logic
+ // A connector row's tool set is enabled as its connector is: agent
+ // configuration and enable rules speak base identifiers.
const isEnabled = this.enableChecker
? this.enableChecker({
context,
manifest,
model,
- pluginId,
+ pluginId: manifest.connector?.identifier ?? pluginId,
provider,
})
: this.defaultEnabledCheck();
@@ -320,6 +329,7 @@ export class ToolsEngine {
for (const schema of manifestSchemas) {
this.manifestSchemas.set(schema.identifier, schema);
}
+ this.indexConnectorRows();
}
/**
@@ -327,13 +337,48 @@ export class ToolsEngine {
*/
addPluginManifest(manifest: LobeToolManifest): void {
this.manifestSchemas.set(manifest.identifier, manifest);
+ this.indexConnectorRows();
}
/**
* Remove plugin manifest
*/
removePluginManifest(pluginId: string): boolean {
- return this.manifestSchemas.delete(pluginId);
+ const removed = this.manifestSchemas.delete(pluginId);
+ this.indexConnectorRows();
+ return removed;
+ }
+
+ private indexConnectorRows(): void {
+ this.connectorRowToolIds.clear();
+ for (const manifest of this.manifestSchemas.values()) {
+ const base = manifest.connector?.identifier;
+ if (!base || base === manifest.identifier) continue;
+ this.connectorRowToolIds.set(base, [
+ ...(this.connectorRowToolIds.get(base) ?? []),
+ manifest.identifier,
+ ]);
+ }
+ }
+
+ /**
+ * Requested ids, each followed by the other connector rows serving it: a
+ * pinned or activated connector identifier enables every row's tool set the
+ * run resolved for it (a private or personal row beside the shared one).
+ */
+ private expandConnectorRows(toolIds: string[]): string[] {
+ if (this.connectorRowToolIds.size === 0) return toolIds;
+ return [
+ ...new Set(
+ toolIds.flatMap((id) => {
+ const rows = this.connectorRowToolIds.get(id);
+ if (!rows) return [id];
+ // A connector with only private or personal rows has no manifest
+ // under its bare identifier: that is not a missing tool
+ return this.manifestSchemas.has(id) ? [id, ...rows] : rows;
+ }),
+ ),
+ ];
}
/**
@@ -341,7 +386,7 @@ export class ToolsEngine {
*/
getEnabledPluginManifests(toolIds: string[] = []): Map<string, LobeToolManifest> {
// Merge user-provided tool IDs with default tool IDs
- const allToolIds = [...toolIds, ...this.defaultToolIds];
+ const allToolIds = this.expandConnectorRows([...toolIds, ...this.defaultToolIds]);
log('Getting enabled plugin manifests for pluginIds=%o', allToolIds);
diff --git a/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.connectorRows.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.connectorRows.test.ts
new file mode 100644
index 00000000000..dad8accbc30
--- /dev/null
+++ b/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.connectorRows.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from 'vitest';
+
+import { ToolsEngine } from '../ToolsEngine';
+import type { LobeToolManifest } from '../types';
+
+const row = (identifier: string, id: string, toolName: string): LobeToolManifest => ({
+ api: [{ description: toolName, name: toolName, parameters: {} }],
+ connector: { id, identifier: 'github' },
+ identifier,
+ meta: { title: identifier },
+ type: 'mcp',
+});
+
+const shared = row('github', 'c-shared', 'create_issue');
+const mine = row('github-3f9a1c2e', 'c-private', 'create_issue');
+const input = (toolIds: string[]) => ({
+ model: 'gpt-4',
+ provider: 'openai',
+ skipDefaultTools: true,
+ toolIds,
+});
+
+/**
+ * Same-identifier connector rows (the workspace's shared one, the caller's
+ * private or personal one) are each their own tool set. Agent configuration
+ * names the connector by its base identifier, which enables every row.
+ */
+describe('ToolsEngine connector rows', () => {
+ it('enables every row of a connector named by its base identifier', () => {
+ const engine = new ToolsEngine({ manifestSchemas: [shared, mine] });
+
+ const result = engine.generateToolsDetailed(input(['github']));
+
+ expect(result.enabledToolIds).toEqual(['github', 'github-3f9a1c2e']);
+ expect(result.tools?.map((tool) => tool.function.name)).toEqual([
+ 'github____create_issue____mcp',
+ 'github-3f9a1c2e____create_issue____mcp',
+ ]);
+ expect([...engine.getEnabledPluginManifests(['github']).keys()]).toEqual([
+ 'github',
+ 'github-3f9a1c2e',
+ ]);
+ });
+
+ it('enables a private-only connector without reporting its base id missing', () => {
+ const engine = new ToolsEngine({ manifestSchemas: [mine] });
+
+ const result = engine.generateToolsDetailed(input(['github']));
+
+ expect(result.enabledToolIds).toEqual(['github-3f9a1c2e']);
+ expect(result.filteredTools).toEqual([]);
+ });
+
+ it('asks the enable checker about the connector, not the row', () => {
+ const asked: string[] = [];
+ const engine = new ToolsEngine({
+ enableChecker: ({ pluginId }) => {
+ asked.push(pluginId);
+ return pluginId !== 'github';
+ },
+ manifestSchemas: [shared, mine],
+ });
+
+ const result = engine.generateToolsDetailed(input(['github']));
+
+ expect(asked).toEqual(['github', 'github']);
+ expect(result.enabledToolIds).toEqual([]);
+ });
+});
diff --git a/packages/context-engine/src/engine/tools/types.ts b/packages/context-engine/src/engine/tools/types.ts
index 1e66da6a8a2..702fa981e0c 100644
--- a/packages/context-engine/src/engine/tools/types.ts
+++ b/packages/context-engine/src/engine/tools/types.ts
@@ -28,6 +28,8 @@ export interface LobeChatPluginApi {
export interface LobeToolManifest {
api: LobeChatPluginApi[];
+ /** A connector row's tool set: its row and the base identifier it serves. */
+ connector?: { id: string; identifier: string };
connectorLinks?: { connectorId: string; param: string };
identifier: string;
meta: any;
diff --git a/packages/database/src/models/__tests__/connectorAgentScope.test.ts b/packages/database/src/models/__tests__/connectorAgentScope.test.ts
index 6348fc2897f..0cb50703824 100644
--- a/packages/database/src/models/__tests__/connectorAgentScope.test.ts
+++ b/packages/database/src/models/__tests__/connectorAgentScope.test.ts
@@ -243,7 +243,14 @@ describe('ConnectorModel agent-scoped resolution', () => {
expect(all).toHaveLength(2);
expect(byIdentifier.gmail).toBe('Agent Gmail');
expect(byIdentifier.notion).toBe('Personal Notion');
- const optedOut = await model.resolveAll(agentA, undefined, ['gmail']);
+ });
+
+ it('resolveToolSets skips the excluded identifiers', async () => {
+ await insertConnector({ agentId: agentA, identifier: 'gmail', name: 'Agent Gmail' });
+ await insertConnector({ identifier: 'notion', name: 'Personal Notion' });
+
+ const model = new ConnectorModel(serverDB, userId);
+ const optedOut = await model.resolveToolSets(agentA, undefined, undefined, ['gmail']);
expect(optedOut.map((r) => r.identifier)).toEqual(['notion']);
});
});
diff --git a/packages/database/src/models/__tests__/connectorVisibility.test.ts b/packages/database/src/models/__tests__/connectorVisibility.test.ts
index 98394871c1e..496f0dc9d89 100644
--- a/packages/database/src/models/__tests__/connectorVisibility.test.ts
+++ b/packages/database/src/models/__tests__/connectorVisibility.test.ts
@@ -295,8 +295,10 @@ describe('connector visibility — agent configuration', () => {
expect(await availableIdentifiers(ownerModel)).toEqual(['ws-shared-linear']);
});
- it('reports the row the agent’s own conversation ranks first, without credentials', async () => {
- await insertConnector({ identifier: 'notion', userId: mate });
+ it('reports every tool set the agent loads, without credentials', async () => {
+ // The shared row and the owner's private one are tool sets of their own: a
+ // disabled private row no longer hides the shared one from validation
+ const sharedRow = await insertConnector({ identifier: 'notion', userId: mate });
const privateRow = await insertConnector({ identifier: 'notion', visibility: 'private' });
await serverDB
.update(userConnectors)
@@ -306,6 +308,7 @@ describe('connector visibility — agent configuration', () => {
expect(await model.queryAvailableForAgent(privateAgent)).toEqual([
{ id: privateRow.id, identifier: 'notion', isEnabled: false, status: 'connected' },
+ { id: sharedRow.id, identifier: 'notion', isEnabled: true, status: 'connected' },
]);
});
});
@@ -370,6 +373,70 @@ describe('connector visibility — priority within one identifier', () => {
});
});
+describe('connector visibility — tool sets of one identifier', () => {
+ const suffix = (id: string) => id.replaceAll('-', '').slice(0, 8);
+ const toolSets = async (target: { agentId?: string; topicId?: string }) =>
+ (await new ConnectorModel(serverDB, owner, workspaceId).resolveToolSets(target, ['gmail'])).map(
+ (row) => [row.toolIdentifier, row.id],
+ );
+
+ it('keeps the shared, private and personal rows each as its own tool set', async () => {
+ const shared = await insertConnector({ identifier: 'gmail', userId: mate });
+ const personal = await insertConnector({ identifier: 'gmail', workspaceId: null });
+ const mine = await insertConnector({ identifier: 'gmail', visibility: 'private' });
+
+ expect(await toolSets({ agentId: privateAgent, topicId: privateTopic })).toEqual([
+ [`gmail-${suffix(mine.id)}`, mine.id],
+ [`gmail-${suffix(personal.id)}`, personal.id],
+ ['gmail', shared.id],
+ ]);
+ // Any run but the private agent's own topic resolves the shared row alone
+ expect(await toolSets({ agentId: workspaceAgent, topicId: workspaceAgentTopic })).toEqual([
+ ['gmail', shared.id],
+ ]);
+ });
+
+ it("never lets a literal identifier share a private row's prefix", async () => {
+ const mine = await insertConnector({ identifier: 'gmail', visibility: 'private' });
+ // A shared connector literally named like the private row's short prefix
+ const literal = await insertConnector({ identifier: `gmail-${suffix(mine.id)}`, userId: mate });
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+ const target = { agentId: privateAgent, topicId: privateTopic };
+
+ // Whichever identifiers a caller asks for, the private row takes its whole id
+ for (const identifiers of [['gmail'], ['gmail', literal.identifier], undefined]) {
+ const rows = await model.resolveToolSets(target, identifiers);
+ expect(rows.find((row) => row.id === mine.id)?.toolIdentifier).toBe(
+ `gmail-${mine.id.replaceAll('-', '')}`,
+ );
+ }
+ expect(
+ (await model.resolveToolSets(target, [literal.identifier])).map((row) => row.toolIdentifier),
+ ).toEqual([literal.identifier]);
+ });
+
+ it('lets a row bound to the agent stand alone for its identifier', async () => {
+ await insertConnector({ identifier: 'gmail', userId: mate });
+ await insertConnector({ identifier: 'gmail', visibility: 'private' });
+ const agentOwned = await insertConnector({ agentId: privateAgent, identifier: 'gmail' });
+
+ expect(await toolSets({ agentId: privateAgent, topicId: privateTopic })).toEqual([
+ ['gmail', agentOwned.id],
+ ]);
+ });
+
+ it('keeps one tool set for duplicate shared rows, the lowest id', async () => {
+ const [first] = [
+ await insertConnector({ identifier: 'gmail', userId: mate }),
+ await insertConnector({ identifier: 'gmail', userId: owner }),
+ ].sort((a, b) => a.id.localeCompare(b.id));
+
+ expect(await toolSets({ agentId: privateAgent, topicId: privateTopic })).toEqual([
+ ['gmail', first.id],
+ ]);
+ });
+});
+
describe('connector visibility — write paths', () => {
it('looks up the idempotency row within one visibility', async () => {
const shared = await insertConnector({ identifier: 'notion', userId: mate });
@@ -389,6 +456,32 @@ describe('connector visibility — write paths', () => {
expect(await model.findScopedByIdentifier('slack', undefined, undefined, 'private')).toBeNull();
});
+ it('counts the private connectors an agent uses, owned or mounted', async () => {
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+ expect(await model.countPrivateAgentBindings(privateAgent)).toBe(0);
+
+ // Shared rows, and private rows serving another agent, never count
+ await insertConnector({ agentId: privateAgent, identifier: 'shared-own' });
+ await insertConnector({
+ identifier: 'shared-mount',
+ metadata: { mountedByAgentId: privateAgent },
+ });
+ await insertConnector({ agentId: workspaceAgent, identifier: 'other', visibility: 'private' });
+ expect(await model.countPrivateAgentBindings(privateAgent)).toBe(0);
+
+ await insertConnector({ agentId: privateAgent, identifier: 'notion', visibility: 'private' });
+ await insertConnector({
+ identifier: 'linear',
+ metadata: { mountedByAgentId: privateAgent },
+ visibility: 'private',
+ });
+ expect(await model.countPrivateAgentBindings(privateAgent)).toBe(2);
+ // Personal scope has no private connectors
+ expect(await new ConnectorModel(serverDB, owner).countPrivateAgentBindings(privateAgent)).toBe(
+ 0,
+ );
+ });
+
it('claims a base identifier within one visibility', async () => {
const model = new ConnectorModel(serverDB, owner, workspaceId);
const input = {
@@ -425,6 +518,35 @@ describe('connector visibility — write paths', () => {
expect(myPrivateSlack.visibility).toBe('private');
});
+ it('lets only one of two concurrent shares of one identifier take the shared slot', async () => {
+ const mine = await insertConnector({ identifier: 'notion', visibility: 'private' });
+ const theirs = await insertConnector({
+ identifier: 'notion',
+ userId: mate,
+ visibility: 'private',
+ });
+
+ const results = await Promise.all([
+ new ConnectorModel(serverDB, owner, workspaceId).changeVisibilityUnlessHeld(
+ mine.id,
+ 'notion',
+ 'public',
+ ),
+ new ConnectorModel(serverDB, mate, workspaceId).changeVisibilityUnlessHeld(
+ theirs.id,
+ 'notion',
+ 'public',
+ ),
+ ]);
+
+ expect(results.filter((result) => 'changed' in result)).toHaveLength(1);
+ const shared = await serverDB
+ .select({ id: userConnectors.id })
+ .from(userConnectors)
+ .where(eq(userConnectors.visibility, 'public'));
+ expect(shared).toHaveLength(1);
+ });
+
it('moves an agent connector into the base scope within its own visibility', async () => {
const model = new ConnectorModel(serverDB, owner, workspaceId);
const myPrivate = await insertConnector({ identifier: 'notion', visibility: 'private' });
diff --git a/packages/database/src/models/__tests__/plugin.test.ts b/packages/database/src/models/__tests__/plugin.test.ts
index 4d18c5edc8e..50e0ae064f0 100644
--- a/packages/database/src/models/__tests__/plugin.test.ts
+++ b/packages/database/src/models/__tests__/plugin.test.ts
@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
import type { NewInstalledPlugin } from '../../schemas';
-import { userInstalledPlugins, users, workspaces } from '../../schemas';
+import { userConnectors, userInstalledPlugins, users, workspaces } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { PluginModel } from '../plugin';
@@ -250,6 +250,58 @@ describe('PluginModel', () => {
'acc-legacy',
]);
});
+
+ it("leaves a teammate's private connection out of a client listing", async () => {
+ // 456's projection mirrors its private connection of the app; the
+ // caller's legacy-only connection has no connection row
+ await serverDB.insert(userConnectors).values({
+ identifier: 'gmail',
+ metadata: { composio: { connectedAccountId: 'acc-private' } },
+ name: 'Gmail',
+ sourceType: 'composio',
+ status: 'connected',
+ userId: '456',
+ visibility: 'private',
+ workspaceId,
+ } as any);
+ const accounts = (rows: { customParams?: any }[]) =>
+ rows.map((row) => row.customParams?.composio?.connectedAccountId).filter(Boolean);
+
+ const caller = new PluginModel(serverDB, userId, workspaceId);
+ expect(accounts(await caller.query({ forClient: true }))).toEqual(['acc-legacy']);
+ // Server runs keep reading every projection row
+ expect(accounts(await caller.query()).sort()).toEqual(['acc-legacy', 'acc-private']);
+ // The owner still lists their own
+ expect(
+ accounts(
+ await new PluginModel(serverDB, '456', workspaceId).query({ forClient: true }),
+ ).sort(),
+ ).toEqual(['acc-legacy', 'acc-private']);
+ });
+
+ it("removes a shared connection's projection but keeps a member's private connection", async () => {
+ // 456's projection mirrors its private connection of the app
+ await serverDB.insert(userConnectors).values({
+ identifier: 'gmail',
+ metadata: { composio: { connectedAccountId: 'acc-private' } },
+ name: 'Gmail',
+ sourceType: 'composio',
+ status: 'connected',
+ userId: '456',
+ visibility: 'private',
+ workspaceId,
+ } as any);
+
+ await new PluginModel(serverDB, userId, workspaceId).deleteComposioProjectionKeepingPrivate(
+ 'gmail',
+ );
+
+ const rows = await new PluginModel(serverDB, userId, workspaceId).queryComposioMirrors();
+ expect(rows.map((row) => row.customParams?.composio?.connectedAccountId)).toEqual([
+ 'acc-private',
+ ]);
+ expect(await new PluginModel(serverDB, userId, workspaceId).findById('search')).toBeDefined();
+ });
});
describe('update', () => {
diff --git a/packages/database/src/models/connector.ts b/packages/database/src/models/connector.ts
index 72d688375e5..4df911bd8dd 100644
--- a/packages/database/src/models/connector.ts
+++ b/packages/database/src/models/connector.ts
@@ -1,7 +1,7 @@
import type { ConnectorVisibility } from '@lobechat/types';
import { safeParseJSON } from '@lobechat/utils';
import type { SQL } from 'drizzle-orm';
-import { and, asc, eq, inArray, isNotNull, isNull, notInArray, or, sql } from 'drizzle-orm';
+import { and, asc, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';
import pMap from 'p-map';
import type { ConnectorCredentials, NewUserConnector, UserConnectorItem } from '../schemas';
@@ -15,6 +15,7 @@ import {
import { EvalConnectorUpdateError, normalizeEvalConnectorPatch } from './connectorEval';
import {
type BaseIdentifierScope,
+ changeBaseVisibilityUnlessHeld,
claimBaseIdentifier,
ConnectorIdentifierHeldError,
moveToBaseUnlessIdentifierHeld,
@@ -23,12 +24,18 @@ import {
} from './connectorIdentifierClaim';
import { ConnectorLinkModel, isConnectorOAuthAccounts } from './connectorLink';
import { deleteIfMetadataContains, updateMetadataIfContains } from './connectorMetadataGuard';
+import { countPrivateConnectorBindings } from './connectorPrivateBindings';
import {
connectorAccessScope,
connectorAgentConfigScope,
connectorRunScope,
type ConnectorRunTarget,
} from './connectorScope';
+import {
+ pickConfigurableConnectors,
+ pickConnectorByPriority,
+ selectConnectorToolSets,
+} from './connectorToolSets';
export { ConnectorIdentifierHeldError } from './connectorIdentifierClaim';
export type { ConnectorRunTarget } from './connectorScope';
@@ -275,45 +282,14 @@ export class ConnectorModel {
};
/**
- * Reduce candidate rows to at most one per identifier. Rows are ranked by
- * binding first, then by whose connection it is:
- *
- * 1. binding — agent-OWNED by this agent > MOUNTED by this agent > free base;
- * 2. within a binding — the owner's private row in this workspace > the
- * owner's personal row > the workspace's shared row. A private agent's
- * owner chose their own connection for their own agent, so it shadows
- * the shared one; a row made inside this workspace beats one carried
- * over from personal space.
- *
- * Equal ranks keep the first row in {@link resolutionOrder} (identifier,
- * then id), so the pick never follows the physical row order. The result
- * drives the order of the model's tool schema array.
- *
- * Only a private agent's run in its own topic can see private or personal
- * rows at all (see {@link connectorRunScope}); every other run only ranks
- * shared rows here.
+ * At most one row per identifier, ranked by binding to the agent, then by
+ * whose connection it is (`connectorRunRank`): a private agent's owner's own
+ * row shadows the shared one. Equal ranks keep the first row in
+ * {@link resolutionOrder}, never the physical order. Only a private agent's
+ * own topic sees private or personal rows at all ({@link connectorRunScope}).
*/
- private pickByPriority = (rows: UserConnectorItem[], agentId?: string): UserConnectorItem[] => {
- const workspaceId = normalizeWorkspaceId(this.workspaceId);
- const bindingRank = (row: UserConnectorItem): number => {
- if (agentId && row.agentId === agentId) return 2;
- if (agentId && row.metadata?.mountedByAgentId === agentId) return 1;
- return 0;
- };
- const ownershipRank = (row: UserConnectorItem): number => {
- if (!workspaceId) return 0;
- if (row.workspaceId === workspaceId && row.visibility === 'private') return 2;
- if (row.workspaceId === null) return 1;
- return 0;
- };
- const rank = (row: UserConnectorItem) => bindingRank(row) * 3 + ownershipRank(row);
- const byIdentifier = new Map<string, UserConnectorItem>();
- for (const row of rows) {
- const current = byIdentifier.get(row.identifier);
- if (!current || rank(row) > rank(current)) byIdentifier.set(row.identifier, row);
- }
- return [...byIdentifier.values()];
- };
+ private pickByPriority = (rows: UserConnectorItem[], agentId?: string): UserConnectorItem[] =>
+ pickConnectorByPriority(rows, { agentId, workspaceId: normalizeWorkspaceId(this.workspaceId) });
/**
* The model for a resolved row's own scope. A private agent's workspace run
@@ -386,6 +362,14 @@ export class ConnectorModel {
moveToBaseUnlessIdentifierHeld = async (id: string, identifier: string) =>
moveToBaseUnlessIdentifierHeld(this.db, this.baseIdentifierScope(), id, identifier);
+ /** {@link changeBaseVisibilityUnlessHeld} */
+ changeVisibilityUnlessHeld = (id: string, identifier: string, visibility: ConnectorVisibility) =>
+ changeBaseVisibilityUnlessHeld(this.db, this.baseIdentifierScope(), id, identifier, visibility);
+
+ /** See {@link countPrivateConnectorBindings}; zero outside a workspace. */
+ countPrivateAgentBindings = (agentId: string): Promise<number> =>
+ countPrivateConnectorBindings(this.db, normalizeWorkspaceId(this.workspaceId), agentId);
+
/** See {@link queryBaseHolders}. */
queryBaseHolders = async (
identifier: string,
@@ -645,6 +629,31 @@ export class ConnectorModel {
});
};
+ /** The run's rows as tool sets, each with its prefix (`toolIdentifier`, {@link pickConnectorToolSets}). */
+ resolveToolSets = async (
+ runTarget: ConnectorRunTargetInput = {},
+ identifiers?: string[],
+ gateKeeper: GateKeeper | undefined = this.gateKeeper,
+ excludedIdentifiers: string[] = [],
+ ): Promise<(DecryptedConnector & { toolIdentifier: string })[]> => {
+ const target = toRunTarget(runTarget);
+ const picked = await selectConnectorToolSets(this.db, {
+ agentId: target.agentId,
+ excludedIdentifiers,
+ identifiers,
+ scope: this.scopePredicate(target),
+ workspaceId: normalizeWorkspaceId(this.workspaceId),
+ });
+ return pMap(
+ picked,
+ async (row) => ({
+ ...(await decryptRow(row, gateKeeper)),
+ toolIdentifier: row.toolIdentifier,
+ }),
+ { concurrency: 5 },
+ );
+ };
+
/**
* Agent-aware variant of {@link query}: every connector the run may resolve,
* deduped by identifier with {@link pickByPriority}. Used to enumerate
@@ -654,20 +663,12 @@ export class ConnectorModel {
resolveAll = async (
runTarget: ConnectorRunTargetInput = {},
gateKeeper: GateKeeper | undefined = this.gateKeeper,
- excludedIdentifiers: string[] = [],
): Promise<DecryptedConnector[]> => {
const target = toRunTarget(runTarget);
const rows = await this.db
.select()
.from(userConnectors)
- .where(
- and(
- this.scopePredicate(target),
- excludedIdentifiers.length
- ? notInArray(userConnectors.identifier, excludedIdentifiers)
- : undefined,
- ),
- )
+ .where(this.scopePredicate(target))
.orderBy(...this.resolutionOrder());
return pMap(this.pickByPriority(rows, target.agentId), (r) => decryptRow(r, gateKeeper), {
@@ -699,7 +700,10 @@ export class ConnectorModel {
.where(this.agentNarrowing(base, agentId))
.orderBy(...this.resolutionOrder());
- return this.pickByPriority(rows, agentId).map(({ id, identifier, isEnabled, status }) => ({
+ return pickConfigurableConnectors(rows, {
+ agentId,
+ workspaceId: normalizeWorkspaceId(this.workspaceId),
+ }).map(({ id, identifier, isEnabled, status }) => ({
id,
identifier,
isEnabled,
diff --git a/packages/database/src/models/connectorIdentifierClaim.ts b/packages/database/src/models/connectorIdentifierClaim.ts
index 9b1cbf95508..6c8103a0c84 100644
--- a/packages/database/src/models/connectorIdentifierClaim.ts
+++ b/packages/database/src/models/connectorIdentifierClaim.ts
@@ -194,3 +194,39 @@ export const moveToBaseUnlessIdentifierHeld = async (
);
return { moved: true as const };
});
+
+/**
+ * Change a base connector's visibility unless the destination slot (a base row
+ * of `identifier` in `visibility`) is held: the lookup and the change are one
+ * step, under the lock {@link claimBaseIdentifier} takes, so two members
+ * sharing private connectors of one identifier at once never both land in the
+ * shared slot.
+ */
+export const changeBaseVisibilityUnlessHeld = async (
+ db: LobeChatDatabase,
+ scope: BaseIdentifierScope,
+ id: string,
+ identifier: string,
+ visibility: ConnectorVisibility,
+): Promise<{ changed: true } | { holder: UserConnectorItem }> =>
+ db.transaction(async (tx) => {
+ await lockBaseIdentifier(tx, scope, identifier);
+
+ const holder = (await findBaseHolders(tx, scope, identifier, visibility)).find(
+ (row) => row.id !== id,
+ );
+ if (holder) return { holder };
+
+ await tx
+ .update(userConnectors)
+ .set({ updatedAt: new Date(), visibility })
+ .where(
+ and(
+ eq(userConnectors.id, id),
+ eq(userConnectors.identifier, identifier),
+ isNull(userConnectors.agentId),
+ scope.ownership(),
+ ),
+ );
+ return { changed: true as const };
+ });
diff --git a/packages/database/src/models/connectorPrivateBindings.ts b/packages/database/src/models/connectorPrivateBindings.ts
new file mode 100644
index 00000000000..f5e53a1c8a2
--- /dev/null
+++ b/packages/database/src/models/connectorPrivateBindings.ts
@@ -0,0 +1,35 @@
+import { and, count, eq, or, sql } from 'drizzle-orm';
+
+import { userConnectors } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+
+/**
+ * How many private connectors in the workspace serve `agentId`: the agent's own
+ * rows, and base rows mounted on it (`metadata.mountedByAgentId`). A private
+ * connector serves only its creator's private agents, and run scoping drops it
+ * from a shared agent — so while any exists, publishing the agent would leave
+ * its configured tool unavailable, or silently answer it with a shared
+ * connector of the same identifier running another account.
+ */
+export const countPrivateConnectorBindings = async (
+ db: LobeChatDatabase,
+ workspaceId: string | null | undefined,
+ agentId: string,
+): Promise<number> => {
+ // A personal scope has no private connectors
+ if (!workspaceId) return 0;
+ const [row] = await db
+ .select({ value: count() })
+ .from(userConnectors)
+ .where(
+ and(
+ eq(userConnectors.workspaceId, workspaceId),
+ eq(userConnectors.visibility, 'private'),
+ or(
+ eq(userConnectors.agentId, agentId),
+ sql`${userConnectors.metadata} ->> 'mountedByAgentId' = ${agentId}`,
+ ),
+ ),
+ );
+ return Number(row?.value ?? 0);
+};
diff --git a/packages/database/src/models/connectorToolSets.ts b/packages/database/src/models/connectorToolSets.ts
new file mode 100644
index 00000000000..281ed7f3718
--- /dev/null
+++ b/packages/database/src/models/connectorToolSets.ts
@@ -0,0 +1,190 @@
+import { hasCallableMcpEndpoint } from '@lobechat/const';
+import {
+ connectorShortToolIdentifier,
+ connectorToolIdentifier,
+ isOwnConnectorRow,
+} from '@lobechat/types';
+import type { SQL } from 'drizzle-orm';
+import { and, asc, inArray, notInArray } from 'drizzle-orm';
+
+import { userConnectors } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+
+/** The fields of a connector row a run ranks it by and names its tool set from. */
+interface RankedRow {
+ agentId: string | null;
+ id: string;
+ identifier: string;
+ metadata?: { mountedByAgentId?: unknown } | null;
+ visibility?: string | null;
+ workspaceId: string | null;
+}
+
+/**
+ * How a run ranks one connector row against another of its identifier:
+ *
+ * 1. binding — agent-OWNED by this agent > MOUNTED by this agent > free base;
+ * 2. within a binding — the owner's private row in this workspace > the
+ * owner's personal row > the workspace's shared row.
+ */
+const connectorRunRank = (
+ row: RankedRow,
+ { agentId, workspaceId }: { agentId?: string; workspaceId?: string | null },
+) => {
+ const binding =
+ agentId && row.agentId === agentId
+ ? 2
+ : agentId && row.metadata?.mountedByAgentId === agentId
+ ? 1
+ : 0;
+ const ownership = !workspaceId
+ ? 0
+ : row.workspaceId === workspaceId && row.visibility === 'private'
+ ? 2
+ : row.workspaceId === null
+ ? 1
+ : 0;
+ return { binding, rank: binding * 3 + ownership };
+};
+
+/**
+ * One row per identifier, the highest {@link connectorRunRank}; equal ranks
+ * keep the first row (callers pass rows in resolution order: identifier, id).
+ */
+export const pickConnectorByPriority = <T extends RankedRow>(
+ rows: T[],
+ context: { agentId?: string; workspaceId?: string | null },
+): T[] => {
+ const byIdentifier = new Map<string, T>();
+ for (const row of rows) {
+ const current = byIdentifier.get(row.identifier);
+ if (!current || connectorRunRank(row, context).rank > connectorRunRank(current, context).rank)
+ byIdentifier.set(row.identifier, row);
+ }
+ return [...byIdentifier.values()];
+};
+
+/**
+ * The connector rows a run turns into tool sets, each with its tool prefix
+ * ({@link connectorToolIdentifier}). A row bound to the run's agent (its own,
+ * or mounted on it) still stands alone for its identifier: the agent's setup
+ * chose it. Otherwise every row of the identifier the run may use is its own
+ * tool set — the workspace's shared one and the caller's private and personal
+ * ones may connect different accounts and expose different tools. Rows sharing
+ * a prefix (duplicate shared rows written before identifier claims) keep the
+ * first. Within an identifier the highest rank comes first.
+ */
+export const pickConnectorToolSets = <T extends RankedRow>(
+ rows: T[],
+ context: {
+ agentId?: string;
+ /** Identifiers of the run's rows a short own-row prefix could collide with. */
+ reservedIdentifiers?: ReadonlySet<string>;
+ workspaceId?: string | null;
+ },
+): (T & { toolIdentifier: string })[] => {
+ const groups = new Map<string, T[]>();
+ for (const row of rows) groups.set(row.identifier, [...(groups.get(row.identifier) ?? []), row]);
+
+ return [...groups.values()].flatMap((group) => {
+ const ranked = group
+ .map((row, order) => ({ order, row, ...connectorRunRank(row, context) }))
+ .sort((a, b) => b.rank - a.rank || a.order - b.order);
+ const kept = ranked[0].binding > 0 ? [ranked[0]] : ranked;
+ const byPrefix = new Map<string, T & { toolIdentifier: string }>();
+ for (const { row } of kept) {
+ const toolIdentifier = connectorToolIdentifier(
+ row,
+ context.workspaceId,
+ context.reservedIdentifiers,
+ );
+ if (!byPrefix.has(toolIdentifier)) byPrefix.set(toolIdentifier, { ...row, toolIdentifier });
+ }
+ return [...byPrefix.values()];
+ });
+};
+
+/**
+ * The identifiers, among the rows `scope` admits, that an own row's short
+ * prefix would read as (a connector literally named `mail-12345678`): such a
+ * row's tool set takes the whole row id instead. Looked up in the whole scope,
+ * not the rows a caller fetched, so every caller names a row alike.
+ */
+export const queryReservedToolIdentifiers = async (
+ db: LobeChatDatabase,
+ scope: SQL | undefined,
+ rows: RankedRow[],
+ workspaceId?: string | null,
+): Promise<Set<string>> => {
+ const shortPrefixes = rows
+ .filter((row) => isOwnConnectorRow(row, workspaceId))
+ .map(connectorShortToolIdentifier);
+ if (shortPrefixes.length === 0) return new Set();
+ const taken = await db
+ .select({ identifier: userConnectors.identifier })
+ .from(userConnectors)
+ .where(and(scope, inArray(userConnectors.identifier, shortPrefixes)));
+ return new Set(taken.map((row) => row.identifier));
+};
+
+/**
+ * The rows `scope` admits (optionally of `identifiers`) as a run's tool sets,
+ * in resolution order (identifier, then id), each named collision-free
+ * ({@link pickConnectorToolSets}, {@link queryReservedToolIdentifiers}).
+ */
+export const selectConnectorToolSets = async (
+ db: LobeChatDatabase,
+ {
+ agentId,
+ excludedIdentifiers = [],
+ identifiers,
+ scope,
+ workspaceId,
+ }: {
+ agentId?: string;
+ /** Identifiers the caller already has or will drop, so their rows are not read. */
+ excludedIdentifiers?: string[];
+ identifiers?: string[];
+ scope: SQL | undefined;
+ workspaceId?: string | null;
+ },
+) => {
+ if (identifiers?.length === 0) return [];
+ const rows = await db
+ .select()
+ .from(userConnectors)
+ .where(
+ and(
+ scope,
+ identifiers ? inArray(userConnectors.identifier, identifiers) : undefined,
+ excludedIdentifiers.length
+ ? notInArray(userConnectors.identifier, excludedIdentifiers)
+ : undefined,
+ ),
+ )
+ .orderBy(asc(userConnectors.identifier), asc(userConnectors.id));
+ // Collisions are read over the whole scope, so excluding rows keeps every
+ // remaining row's prefix.
+ const reservedIdentifiers = await queryReservedToolIdentifiers(db, scope, rows, workspaceId);
+ return pickConnectorToolSets(rows, { agentId, reservedIdentifiers, workspaceId });
+};
+
+/**
+ * The rows an agent's configuration may name, as its runs use them: every MCP
+ * row its own tool set ({@link pickConnectorToolSets}), every other row (a
+ * Composio connection, whose tools another path serves) one per identifier
+ * ({@link pickConnectorByPriority}). A configuration naming the identifier is
+ * valid while any of them is usable.
+ */
+export const pickConfigurableConnectors = <
+ T extends RankedRow & { mcpConnectionType?: string | null; mcpServerUrl?: string | null },
+>(
+ rows: T[],
+ context: { agentId?: string; workspaceId?: string | null },
+): T[] => [
+ ...pickConnectorToolSets(rows.filter(hasCallableMcpEndpoint), context),
+ ...pickConnectorByPriority(
+ rows.filter((row) => !hasCallableMcpEndpoint(row)),
+ context,
+ ),
+];
diff --git a/packages/database/src/models/plugin.ts b/packages/database/src/models/plugin.ts
index e087e2c788c..65f1cca163a 100644
--- a/packages/database/src/models/plugin.ts
+++ b/packages/database/src/models/plugin.ts
@@ -2,7 +2,7 @@ import type { LobeTool } from '@lobechat/types';
import { and, desc, eq, inArray, sql } from 'drizzle-orm';
import type { InstalledPluginItem, NewInstalledPlugin } from '../schemas';
-import { userInstalledPlugins } from '../schemas';
+import { userConnectors, userInstalledPlugins } from '../schemas';
import type { LobeChatDatabase } from '../type';
import { buildWorkspaceWhere } from '../utils/workspace';
@@ -67,6 +67,30 @@ export class PluginModel {
.where(and(eq(userInstalledPlugins.identifier, id), this.visible()));
};
+ /**
+ * Remove an app's projection when its shared Composio connection goes. The
+ * shared connection's projection is the app's, so a teammate's legacy
+ * connection goes with it; a row mirroring a member's private connection of
+ * the same app stays, as that connection still runs on it.
+ */
+ deleteComposioProjectionKeepingPrivate = async (identifier: string) => {
+ return this.db.delete(userInstalledPlugins).where(
+ and(
+ eq(userInstalledPlugins.identifier, identifier),
+ this.visible(),
+ sql`NOT EXISTS (
+ SELECT 1 FROM ${userConnectors}
+ WHERE ${userConnectors.identifier} = ${identifier}
+ AND ${userConnectors.visibility} = 'private'
+ AND ${userConnectors.agentId} IS NULL
+ AND ${userConnectors.workspaceId} IS NOT DISTINCT FROM ${userInstalledPlugins.workspaceId}
+ AND ${userConnectors.metadata} -> 'composio' ->> 'connectedAccountId'
+ = ${userInstalledPlugins.customParams} -> 'composio' ->> 'connectedAccountId'
+ )`,
+ ),
+ );
+ };
+
/**
* Remove the projection rows that mirror one Composio account, leaving the
* app's other projection rows. In a workspace every member's projection row
@@ -90,7 +114,14 @@ export class PluginModel {
return this.db.delete(userInstalledPlugins).where(this.ownership());
};
- query = async () => {
+ /**
+ * The installed plugins in scope. `forClient` leaves out the Composio
+ * projection of a teammate's private connection: the projection is
+ * workspace-wide, but only its owner may run that connection, so a client
+ * listing it would offer tools whose every call is refused. A projection with
+ * no connection row (a legacy-only connection) stays.
+ */
+ query = async ({ forClient = false }: { forClient?: boolean } = {}) => {
const data = await this.db
.select({
createdAt: userInstalledPlugins.createdAt,
@@ -103,7 +134,22 @@ export class PluginModel {
updatedAt: userInstalledPlugins.updatedAt,
})
.from(userInstalledPlugins)
- .where(this.visible())
+ .where(
+ and(
+ this.visible(),
+ forClient
+ ? sql`NOT EXISTS (
+ SELECT 1 FROM ${userConnectors}
+ WHERE ${userConnectors.identifier} = ${userInstalledPlugins.identifier}
+ AND ${userConnectors.visibility} = 'private'
+ AND ${userConnectors.userId} <> ${this.userId}
+ AND ${userConnectors.workspaceId} IS NOT DISTINCT FROM ${userInstalledPlugins.workspaceId}
+ AND ${userConnectors.metadata} -> 'composio' ->> 'connectedAccountId'
+ = ${userInstalledPlugins.customParams} -> 'composio' ->> 'connectedAccountId'
+ )`
+ : undefined,
+ ),
+ )
.orderBy(desc(userInstalledPlugins.createdAt));
return data.map<LobeTool>((item) => ({
diff --git a/packages/database/src/schemas/connector.ts b/packages/database/src/schemas/connector.ts
index fffb0e6d48f..e9fae34fff0 100644
--- a/packages/database/src/schemas/connector.ts
+++ b/packages/database/src/schemas/connector.ts
@@ -181,7 +181,7 @@ export const userConnectors = pgTable(
isEnabled: boolean('is_enabled').notNull().default(true),
// ── OIDC/OAuth config (plaintext — non-sensitive) ─────────────────────
- oidcConfig: jsonb('oidc_config').$type<OIDCConfig>(),
+ oidcConfig: jsonb('oidc_config').$type<ConnectorOIDCConfig>(),
// ── Encrypted credentials ─────────────────────────────────────────────
/**
diff --git a/packages/database/src/schemas/connectorRowTypes.check.ts b/packages/database/src/schemas/connectorRowTypes.check.ts
new file mode 100644
index 00000000000..f86032fff87
--- /dev/null
+++ b/packages/database/src/schemas/connectorRowTypes.check.ts
@@ -0,0 +1,19 @@
+/**
+ * Compile-time check that the connector shapes declared in `@lobechat/types`
+ * (`packages/types/src/connector.ts`) match `user_connectors`. Code outside the
+ * schema imports those declared types; a mismatch fails `type-check`.
+ */
+import type { ConnectorOIDCConfig, ResolvedConnectorRef } from '@lobechat/types';
+
+import type { userConnectors } from './connector';
+
+type Equal<A, B> =
+ (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;
+type Assert<T extends true> = T;
+
+type UserConnectorRow = typeof userConnectors.$inferSelect;
+
+export type ConnectorRowTypesMatchSchema = [
+ Assert<Equal<ResolvedConnectorRef, Pick<UserConnectorRow, 'id' | 'userId' | 'workspaceId'>>>,
+ Assert<Equal<ConnectorOIDCConfig | null, UserConnectorRow['oidcConfig']>>,
+];
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 22d5ebe40e1..68fbae5d5db 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -2074,16 +2074,25 @@ When I am ___, I need ___
'[Skill Request] Summarize the skill you need in one sentence',
'skillStore.wantMore.reachedEnd': "You've reached the end. Can't find what you need?",
'skillView.browseStoreDesc': 'Find and install skills for your agents',
+ 'skillView.connectorTabs.private': 'Private',
+ 'skillView.connectorTabs.workspace': 'Workspace',
'skillView.connectors': 'Connectors',
'skillView.connectorsDesc':
'Connect the apps and tools your agents can use. Open one to see its account and tools.',
'skillView.empty.description': 'Browse the Skill Store or import a skill from the Add menu.',
'skillView.empty.search': 'No skills match “{{keyword}}”',
'skillView.empty.title': 'No skills yet',
+ 'skillView.privateConnectorsDesc':
+ 'Only you can see these connectors, and only your private agents use them. Workspace agents never load them.',
+ 'skillView.privateConnectorsEmpty.desc':
+ 'Add a custom connector here to keep it to yourself and your private agents.',
+ 'skillView.privateConnectorsEmpty.title': 'No private connectors yet',
'skillView.search.placeholder': 'Search skills',
'skillView.skills': 'Skills',
'skillView.skillsDesc':
'Give your agents task-specific skills. Open a skill to see its instructions and resources.',
+ 'skillView.workspaceConnectorsDesc':
+ 'Shared with every member, and every agent in this workspace can use them. Open one to see its account and tools.',
'startConversation': 'Start Conversation',
'storage.actions.transfer.button': 'Move to…',
'storage.actions.transfer.desc':
@@ -4779,6 +4788,9 @@ When I am ___, I need ___
'tools.plugins.management': 'Skill Management',
'tools.plugins.noEnabled': 'No skills enabled',
'tools.plugins.store': 'Add skill',
+ 'tools.privateConnector.tag': 'Private',
+ 'tools.privateConnector.tooltip':
+ 'Your private connector: only you can see it, and only your private agents load it.',
'tools.search': 'Search skills...',
'tools.loading.onDemand': 'Load on demand',
'tools.activation.action.auto': 'Auto',
diff --git a/packages/mecha/src/toolSet/discoveryPool.test.ts b/packages/mecha/src/toolSet/discoveryPool.test.ts
index 4590f0b3463..135dce9f06c 100644
--- a/packages/mecha/src/toolSet/discoveryPool.test.ts
+++ b/packages/mecha/src/toolSet/discoveryPool.test.ts
@@ -361,3 +361,20 @@ describe('resolveClientExecutors', () => {
).toEqual({});
});
});
+
+describe("a connector row's tool set", () => {
+ const mine = manifest('github-3f9a1c2e', { connector: { id: 'c-mine', identifier: 'github' } });
+
+ it("follows its connector's disabled and exclusive entries", () => {
+ const enabledManifests = new Map([['github-3f9a1c2e', mine]]);
+
+ expect(
+ resolveDiscoveryPool(request({ disabledPluginIds: ['github'], enabledManifests }))
+ .manifestMap['github-3f9a1c2e'],
+ ).toBeUndefined();
+ expect(
+ resolveDiscoveryPool(request({ enabledManifests, exclusivePluginIds: ['github'] }))
+ .manifestMap['github-3f9a1c2e'],
+ ).toBe(mine);
+ });
+});
diff --git a/packages/mecha/src/toolSet/discoveryPool.ts b/packages/mecha/src/toolSet/discoveryPool.ts
index 007730df992..8cecbea9c3f 100644
--- a/packages/mecha/src/toolSet/discoveryPool.ts
+++ b/packages/mecha/src/toolSet/discoveryPool.ts
@@ -10,6 +10,7 @@ import {
executionTargetToRuntimeMode,
type LobeAgentChatConfig,
type LobeBuiltinTool,
+ manifestBaseIdentifier,
resolveToolMode,
type ToolExecutor,
type ToolSource,
@@ -116,7 +117,11 @@ export interface DiscoveryPoolRequest {
export interface DiscoveryPool {
/** The single guard every ingest into the pool goes through. */
- isManifestIngestAllowed: (identifier: string) => boolean;
+ /**
+ * `baseIdentifier` is a connector row's connector (`manifest.connector`): its
+ * tool set follows the connector's exclusive and disabled entries.
+ */
+ isManifestIngestAllowed: (identifier: string, baseIdentifier?: string) => boolean;
/** What the activator may discover and enable mid-run. */
manifestMap: Record<string, LobeToolManifest>;
/** Which family a discovered tool executes through. */
@@ -143,9 +148,9 @@ export const resolveDiscoveryPool = (request: DiscoveryPoolRequest): DiscoveryPo
// leaving it discoverable would let explicit activation re-surface the
// device list mid-run. Enforced at the ingest layer so no later source
// can re-add an identifier the walls removed.
- const isManifestIngestAllowed = (identifier: string): boolean => {
- if (exclusive && !exclusive.has(identifier)) return false;
- if (disabled.has(identifier)) return false;
+ const isManifestIngestAllowed = (identifier: string, baseIdentifier = identifier): boolean => {
+ if (exclusive && !exclusive.has(identifier) && !exclusive.has(baseIdentifier)) return false;
+ if (disabled.has(identifier) || disabled.has(baseIdentifier)) return false;
if (
hasDeviceProxy &&
identifier === AuvManifest.identifier &&
@@ -162,7 +167,7 @@ export const resolveDiscoveryPool = (request: DiscoveryPoolRequest): DiscoveryPo
// Seed with the invocation set (candidates ∪ defaults the engine enabled).
request.enabledManifests.forEach((manifest, id) => {
- if (isManifestIngestAllowed(id)) manifestMap[id] = manifest;
+ if (isManifestIngestAllowed(id, manifestBaseIdentifier(manifest))) manifestMap[id] = manifest;
});
const runtimeMode = executionTargetToRuntimeMode(executionTarget);
@@ -214,7 +219,7 @@ export const resolveDiscoveryPool = (request: DiscoveryPoolRequest): DiscoveryPo
// Connector families, with the source the runtime executes them through.
const ingestFamily = (manifests: readonly LobeToolManifest[], source: ToolSource) => {
for (const manifest of manifests) {
- if (!isManifestIngestAllowed(manifest.identifier)) continue;
+ if (!isManifestIngestAllowed(manifest.identifier, manifestBaseIdentifier(manifest))) continue;
if (!manifestMap[manifest.identifier]) manifestMap[manifest.identifier] = manifest;
sourceMap[manifest.identifier] = source;
}
diff --git a/packages/mecha/src/toolSet/manifestPool.test.ts b/packages/mecha/src/toolSet/manifestPool.test.ts
index 766d5dd210a..e3fa411551d 100644
--- a/packages/mecha/src/toolSet/manifestPool.test.ts
+++ b/packages/mecha/src/toolSet/manifestPool.test.ts
@@ -256,3 +256,52 @@ describe('assembleManifestPool', () => {
warn.mockRestore();
});
});
+
+describe('connector rows sharing an identifier', () => {
+ const tools = [{ permission: 'auto', toolName: 'create_issue' }];
+ const shared = buildConnectorManifest({
+ id: 'c-shared',
+ identifier: 'github',
+ isEnabled: true,
+ name: 'GitHub',
+ toolIdentifier: 'github',
+ tools,
+ })!;
+ const mine = buildConnectorManifest({
+ id: 'c-mine',
+ identifier: 'github',
+ isEnabled: true,
+ name: 'GitHub',
+ toolIdentifier: 'github-3f9a1c2e',
+ tools,
+ })!;
+
+ it("keys each row's manifest by its tool prefix and names the row and its connector", () => {
+ expect(mine.identifier).toBe('github-3f9a1c2e');
+ expect(mine.connector).toEqual({ id: 'c-mine', identifier: 'github' });
+ expect(mine.meta.description).toBe('GitHub connector (your own connection) with 1 tools');
+ expect(shared.meta.description).toBe('GitHub connector with 1 tools');
+ });
+
+ it('replaces the plugin and follows the exclusion of the connector they serve', () => {
+ const pool = assembleManifestPool({
+ connectors: [shared, mine],
+ installedPlugins: [manifest('github')],
+ });
+ expect(pool.manifests.map((m) => m.identifier)).toEqual(['github', 'github-3f9a1c2e']);
+ expect([...pool.connectorIdentifiers]).toEqual(['github']);
+
+ // A private-only connector still replaces the same-named plugin
+ expect(
+ assembleManifestPool({
+ connectors: [mine],
+ installedPlugins: [manifest('github')],
+ }).manifests.map((m) => m.identifier),
+ ).toEqual(['github-3f9a1c2e']);
+
+ expect(
+ assembleManifestPool({ connectors: [shared, mine] }, { excludedIdentifiers: ['github'] })
+ .manifests,
+ ).toEqual([]);
+ });
+});
diff --git a/packages/mecha/src/toolSet/manifestPool.ts b/packages/mecha/src/toolSet/manifestPool.ts
index 6347bb141d3..23b8fee7962 100644
--- a/packages/mecha/src/toolSet/manifestPool.ts
+++ b/packages/mecha/src/toolSet/manifestPool.ts
@@ -2,6 +2,7 @@ import { isSyncedMcpToolVisibleTo, type McpAppThreadEntry } from '@lobechat/cons
import { hasMandatoryApproval, mayRequireMandatoryApproval } from '@lobechat/const/plugin';
import type { LobeToolManifest } from '@lobechat/context-engine';
import type { BuiltinToolResolveContext, LobeBuiltinTool } from '@lobechat/types';
+import { manifestBaseIdentifier } from '@lobechat/types';
import debug from 'debug';
import { injectConnectorLinkParam, resolveConnectorLinkParam } from './connectorLinks';
@@ -24,10 +25,18 @@ export interface ConnectorToolFacts {
}
export interface ConnectorFacts {
+ /** The row: a manifest built from it names it (`manifest.connector`). */
+ id?: string;
identifier: string;
isEnabled?: boolean | null;
links?: { id: string; name: string }[];
name: string;
+ /**
+ * The row's tool prefix (`connectorToolIdentifier`): the manifest's
+ * identifier. Differs from `identifier` for a private or personal row, which
+ * is a tool set of its own beside the workspace's shared one.
+ */
+ toolIdentifier?: string;
tools: ConnectorToolFacts[];
}
@@ -139,13 +148,17 @@ export const buildConnectorManifest = (
};
});
+ const toolIdentifier = connector.toolIdentifier ?? connector.identifier;
+ // The model may see a shared and an own row of one connector side by side
+ const own = toolIdentifier !== connector.identifier ? ' (your own connection)' : '';
return {
api,
- identifier: connector.identifier,
+ ...(connector.id && { connector: { id: connector.id, identifier: connector.identifier } }),
+ identifier: toolIdentifier,
...(mcpApps && { mcpAppEntrypoints: entries }),
meta: {
avatar: 'MCP_AVATAR',
- description: `${connector.name} connector with ${api.length} tools`,
+ description: `${connector.name} connector${own} with ${api.length} tools`,
title: connector.name,
},
type: 'mcp',
@@ -217,7 +230,10 @@ export interface AssembleManifestPoolOptions {
}
export interface ManifestPool {
- /** Identifiers served by a connector manifest; same-named plugins were dropped. */
+ /**
+ * Base identifiers served by a connector manifest (any row's tool set);
+ * same-named plugins were dropped.
+ */
connectorIdentifiers: Set<string>;
/**
* How many manifests the exclusion actually removed — not the size of the
@@ -241,7 +257,8 @@ export const assembleManifestPool = (
): ManifestPool => {
const { connectorPermissions, manifestContext } = options;
const connectorManifests = dropInvalidManifests(sources.connectors ?? [], 'connectors');
- const connectorIdentifiers = new Set(connectorManifests.map((m) => m.identifier));
+ // Base identifiers: every row's tool set of a connector replaces its plugin
+ const connectorIdentifiers = new Set(connectorManifests.map(manifestBaseIdentifier));
const withPermissions = (manifest: LobeToolManifest): LobeToolManifest => {
const perms = connectorPermissions?.get(manifest.identifier);
@@ -277,7 +294,10 @@ export const assembleManifestPool = (
...connectorManifests,
...additionalManifests,
];
- const manifests = merged.filter((m) => !excluded.has(m.identifier));
+ // A connector row's tool set is excluded with its connector
+ const manifests = merged.filter(
+ (m) => !excluded.has(m.identifier) && !excluded.has(manifestBaseIdentifier(m)),
+ );
return { connectorIdentifiers, excludedCount: merged.length - manifests.length, manifests };
};
diff --git a/packages/types/src/connector.ts b/packages/types/src/connector.ts
index 0c5318af374..b9804034fec 100644
--- a/packages/types/src/connector.ts
+++ b/packages/types/src/connector.ts
@@ -110,3 +110,14 @@ export interface ConnectorOAuthAccounts {
accounts: ConnectorLinkRecord[];
type: 'oauth2';
}
+
+/**
+ * The `user_connectors` row a call resolved to: its id plus the owner and the
+ * workspace it lives in (`null` for a personal row). Writes that follow the call,
+ * such as connection health, go through this row's own scope.
+ */
+export interface ResolvedConnectorRef {
+ id: string;
+ userId: string;
+ workspaceId: string | null;
+}
diff --git a/packages/types/src/connectorToolIdentifier.test.ts b/packages/types/src/connectorToolIdentifier.test.ts
new file mode 100644
index 00000000000..0c6cb03992f
--- /dev/null
+++ b/packages/types/src/connectorToolIdentifier.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ connectorIdentifierCandidates,
+ connectorToolIdentifier,
+ manifestBaseIdentifier,
+} from './connectorToolIdentifier';
+
+const id = '3f9a1c2e-0000-4000-8000-000000000001';
+
+describe('connectorToolIdentifier', () => {
+ it('keeps the identifier for a shared row, an agent row and a personal run', () => {
+ expect(connectorToolIdentifier({ id, identifier: 'github', visibility: 'public' }, 'ws')).toBe(
+ 'github',
+ );
+ expect(
+ connectorToolIdentifier(
+ { agentId: 'agt', id, identifier: 'github', visibility: 'private' },
+ 'ws',
+ ),
+ ).toBe('github');
+ expect(connectorToolIdentifier({ id, identifier: 'github', workspaceId: null })).toBe('github');
+ });
+
+ it('takes the whole row id when a row the run sees is literally named like its prefix', () => {
+ // A shared connector literally named `github-3f9a1c2e` beside a private
+ // `github` whose id starts so: the two must never share a prefix
+ expect(
+ connectorToolIdentifier(
+ { id, identifier: 'github', visibility: 'private' },
+ 'ws',
+ new Set(['github', 'github-3f9a1c2e']),
+ ),
+ ).toBe('github-3f9a1c2e000040008000000000000001');
+ expect(connectorIdentifierCandidates('github-3f9a1c2e000040008000000000000001')).toEqual([
+ 'github-3f9a1c2e000040008000000000000001',
+ 'github',
+ ]);
+ });
+
+ it("suffixes a private row, and a personal row in a workspace run, with the row's id", () => {
+ expect(connectorToolIdentifier({ id, identifier: 'github', visibility: 'private' }, 'ws')).toBe(
+ 'github-3f9a1c2e',
+ );
+ expect(
+ connectorToolIdentifier(
+ { id, identifier: 'github', visibility: 'public', workspaceId: null },
+ 'ws',
+ ),
+ ).toBe('github-3f9a1c2e');
+ });
+});
+
+describe('connectorIdentifierCandidates', () => {
+ it('names itself, and the base a row suffix points to', () => {
+ expect(connectorIdentifierCandidates('github')).toEqual(['github']);
+ expect(connectorIdentifierCandidates('github-3f9a1c2e')).toEqual(['github-3f9a1c2e', 'github']);
+ expect(connectorIdentifierCandidates('my-mcp')).toEqual(['my-mcp']);
+ });
+});
+
+describe('manifestBaseIdentifier', () => {
+ it("reads a connector row's base identifier, else the manifest's own", () => {
+ expect(
+ manifestBaseIdentifier({
+ connector: { identifier: 'github' },
+ identifier: 'github-3f9a1c2e',
+ }),
+ ).toBe('github');
+ expect(manifestBaseIdentifier({ identifier: 'lobe-web-browsing' })).toBe('lobe-web-browsing');
+ });
+});
diff --git a/packages/types/src/connectorToolIdentifier.ts b/packages/types/src/connectorToolIdentifier.ts
new file mode 100644
index 00000000000..306fffa4186
--- /dev/null
+++ b/packages/types/src/connectorToolIdentifier.ts
@@ -0,0 +1,85 @@
+/**
+ * The tool-name prefix of a connector row: what its manifest is keyed by, what
+ * the model calls it by, and what a tool call is routed back to the row with.
+ *
+ * Several rows may share an `identifier` in one run: the workspace's shared
+ * connector, the caller's private one, and (in a private agent's workspace
+ * run) their personal one. Each is its own tool set — they may connect
+ * different accounts, sync at different times and expose different tools — so
+ * each needs its own prefix:
+ *
+ * - a shared row, an agent's own row, and every row outside a workspace keep
+ * `identifier`, so existing tool names and call history are unchanged;
+ * - a private row, and a personal row resolved in a workspace run, append a
+ * suffix derived from the row id. It depends on the row alone, so it stays
+ * stable when a sibling row appears or goes, and a stored tool call still
+ * names the row it ran on.
+ *
+ * Identifiers are free-form, so a connector may literally be named like a
+ * suffixed prefix (`mail-12345678`). `reservedIdentifiers` are the identifiers
+ * of the rows the run can see: a suffix that would read as one of them takes
+ * the whole row id instead, so no two rows of a run ever share a prefix.
+ */
+export const connectorToolIdentifier = (
+ row: {
+ agentId?: string | null;
+ id: string;
+ identifier: string;
+ visibility?: string | null;
+ workspaceId?: string | null;
+ },
+ /** The workspace the run is in; omitted or null for a personal run. */
+ runWorkspaceId?: string | null,
+ /** Identifiers of the rows the run can see (see above). */
+ reservedIdentifiers?: ReadonlySet<string>,
+): string => {
+ if (!isOwnConnectorRow(row, runWorkspaceId)) return row.identifier;
+ const short = connectorShortToolIdentifier(row);
+ return reservedIdentifiers?.has(short)
+ ? `${row.identifier}-${row.id.replaceAll('-', '').toLowerCase()}`
+ : short;
+};
+
+/**
+ * Whether a row's tool set is named apart from its connector's identifier: a
+ * private row, or a personal row in a workspace run (an agent's own row never).
+ */
+export const isOwnConnectorRow = (
+ row: { agentId?: string | null; visibility?: string | null; workspaceId?: string | null },
+ runWorkspaceId?: string | null,
+): boolean =>
+ !row.agentId && (row.visibility === 'private' || (!!runWorkspaceId && row.workspaceId === null));
+
+/**
+ * The short prefix an own row takes unless a row the run can see is literally
+ * named so ({@link connectorToolIdentifier}).
+ */
+export const connectorShortToolIdentifier = (row: { id: string; identifier: string }): string =>
+ `${row.identifier}-${connectorRowSuffix(row.id)}`;
+
+/** Eight hex characters of the row id: `[\w-]`-safe, so tool names stay readable. */
+export const connectorRowSuffix = (id: string): string =>
+ id.replaceAll('-', '').slice(0, 8).toLowerCase();
+
+/**
+ * The identifiers a tool identifier may belong to: itself (a shared row, or a
+ * plain identifier that happens to end like a suffix), and the base it names
+ * when it ends in a row suffix. A caller resolves the rows of every candidate
+ * and keeps the one whose {@link connectorToolIdentifier} matches, so an
+ * identifier that merely looks suffixed is never mistaken for another row.
+ */
+export const connectorIdentifierCandidates = (toolIdentifier: string): string[] => {
+ const match = /^(.+)-([\da-f]{8}|[\da-f]{32})$/.exec(toolIdentifier);
+ return match ? [toolIdentifier, match[1]] : [toolIdentifier];
+};
+
+/**
+ * The connector identifier a manifest serves: the base identifier of a
+ * connector row's tool set (`manifest.connector`), else its own identifier.
+ * Agent configuration (`agents.plugins` pins and disables), share grants and
+ * plugin precedence all speak base identifiers.
+ */
+export const manifestBaseIdentifier = (manifest: {
+ connector?: { identifier: string } | null;
+ identifier: string;
+}): string => manifest.connector?.identifier ?? manifest.identifier;
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 9d4300736d9..a02a81cd806 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -99,6 +99,7 @@ export * from './acceptanceReviewRound';
export * from './agentRuntime';
export * from './artboard';
export * from './connector';
+export * from './connectorToolIdentifier';
export * from './inboundWebhook';
export * from './oauthApp';
export * from './openai/chat';
diff --git a/packages/types/src/tool/manifest.ts b/packages/types/src/tool/manifest.ts
index baa1e697807..b4963a6fb52 100644
--- a/packages/types/src/tool/manifest.ts
+++ b/packages/types/src/tool/manifest.ts
@@ -20,6 +20,13 @@ export interface ToolManifest {
$schema?: string;
api: LobeChatPluginApi[];
author?: string;
+ /**
+ * A connector row's tool set: the row it executes on and the connector
+ * identifier it serves. `identifier` above is the row's tool prefix
+ * (`connectorToolIdentifier`), which differs from the base identifier for a
+ * private or personal row sharing it with the workspace's shared one.
+ */
+ connector?: { id: string; identifier: string };
connectorLinks?: { connectorId: string; param: string };
createdAt?: string;
gateway?: string;
@@ -45,6 +52,7 @@ export interface ToolManifest {
export const ToolManifestSchema = z.object({
$schema: z.string().optional(),
api: z.array(LobeChatPluginApiSchema),
+ connector: z.object({ id: z.string(), identifier: z.string() }).optional(),
connectorLinks: z.object({ connectorId: z.string(), param: z.string() }).optional(),
author: z.string().optional(),
createdAt: z.string().optional(),
diff --git a/src/features/ChatInput/ActionBar/Tools/PrivateConnectorTag.tsx b/src/features/ChatInput/ActionBar/Tools/PrivateConnectorTag.tsx
new file mode 100644
index 00000000000..655c83c00b6
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Tools/PrivateConnectorTag.tsx
@@ -0,0 +1,18 @@
+import { Icon, Tag, Tooltip } from '@lobehub/ui';
+import { LockIcon } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+/** Marks the caller's private connector in a private agent's skill menu. */
+const PrivateConnectorTag = () => {
+ const { t } = useTranslation('setting');
+
+ return (
+ <Tooltip placement={'top'} title={t('tools.privateConnector.tooltip')}>
+ <Tag icon={<Icon icon={LockIcon} />} size={'small'}>
+ {t('tools.privateConnector.tag')}
+ </Tag>
+ </Tooltip>
+ );
+};
+
+export default PrivateConnectorTag;
diff --git a/src/features/ChatInput/ActionBar/Tools/agentMenuConnectors.test.ts b/src/features/ChatInput/ActionBar/Tools/agentMenuConnectors.test.ts
new file mode 100644
index 00000000000..6ca8b7307b3
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Tools/agentMenuConnectors.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';
+
+import { agentMenuConnectors, agentStillLoadsIdentifier } from './agentMenuConnectors';
+
+const connector = (patch: Partial<ConnectorWithTools>): ConnectorWithTools => ({
+ credentials: null,
+ id: 'c1',
+ identifier: 'team-linear',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example/linear',
+ metadata: null,
+ name: 'Team Linear',
+ sourceType: 'custom',
+ status: 'connected',
+ tools: [],
+ visibility: 'public',
+ ...patch,
+});
+
+const shared = connector({ id: 'shared-linear' });
+const myNotion = connector({ id: 'my-notion', identifier: 'my-notion', visibility: 'private' });
+// The caller's private connection of an identifier the workspace also shares
+const myLinear = connector({ id: 'my-linear', visibility: 'private' });
+
+const ids = (rows: ConnectorWithTools[]) => rows.map((c) => c.id);
+
+describe('agentMenuConnectors', () => {
+ it("never offers the caller's private connectors to a workspace agent", () => {
+ expect(
+ ids(
+ agentMenuConnectors([shared, myNotion, myLinear], {
+ inWorkspace: true,
+ privateAgent: false,
+ }),
+ ),
+ ).toEqual(['shared-linear']);
+ });
+
+ it('offers a private agent the shared connectors plus its owner’s private ones', () => {
+ expect(
+ ids(agentMenuConnectors([shared, myNotion], { inWorkspace: true, privateAgent: true })),
+ ).toEqual(['shared-linear', 'my-notion']);
+ });
+
+ it('keeps the private row of an identifier the workspace also shares, as the run does', () => {
+ // Either physical order: the private connection is the one that executes
+ for (const rows of [
+ [shared, myLinear],
+ [myLinear, shared],
+ ]) {
+ expect(ids(agentMenuConnectors(rows, { inWorkspace: true, privateAgent: true }))).toEqual([
+ 'my-linear',
+ ]);
+ }
+ });
+
+ it('lists every connector outside a workspace', () => {
+ expect(
+ ids(agentMenuConnectors([shared, myNotion], { inWorkspace: false, privateAgent: false })),
+ ).toEqual(['shared-linear', 'my-notion']);
+ });
+});
+
+describe('agentStillLoadsIdentifier', () => {
+ const privateAgent = { inWorkspace: true, privateAgent: true };
+
+ it('keeps the pin when a deleted private row leaves the shared row it shadowed', () => {
+ // Regression: deleting the private row unpinned the identifier, so the
+ // shared connector that now serves it disappeared from the agent.
+ expect(agentStillLoadsIdentifier([shared, myLinear], myLinear, privateAgent)).toBe(true);
+ });
+
+ it('drops the pin when no row of the identifier is left', () => {
+ expect(agentStillLoadsIdentifier([shared, myNotion], myNotion, privateAgent)).toBe(false);
+ expect(agentStillLoadsIdentifier([shared], shared, privateAgent)).toBe(false);
+ });
+
+ it('does not count a private row a workspace agent never loads', () => {
+ expect(
+ agentStillLoadsIdentifier([shared, myLinear], shared, {
+ inWorkspace: true,
+ privateAgent: false,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/src/features/ChatInput/ActionBar/Tools/agentMenuConnectors.ts b/src/features/ChatInput/ActionBar/Tools/agentMenuConnectors.ts
new file mode 100644
index 00000000000..cdb1861e1be
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Tools/agentMenuConnectors.ts
@@ -0,0 +1,102 @@
+import isEqual from 'fast-deep-equal';
+import { useCallback, useMemo } from 'react';
+
+import {
+ getActiveWorkspaceId,
+ useActiveWorkspaceId,
+} from '@/business/client/hooks/useActiveWorkspaceId';
+import { useAgentStore } from '@/store/agent';
+import { useToolStore } from '@/store/tool';
+import { connectorSelectors, pickRunConnectors } from '@/store/tool/slices/connector';
+import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';
+
+/**
+ * The MCP connectors an agent's skill menu offers: the ones that agent loads,
+ * by the rule the server applies to its configuration and runs
+ * (`connectorAgentConfigScope`, then `ConnectorModel.pickByPriority`).
+ *
+ * - Outside a workspace nothing is private: every listed connector.
+ * - A workspace agent loads the shared connectors only. The caller's private
+ * connectors never run in it, so the menu does not offer them for pinning.
+ * - A private agent also loads its owner's private connectors (the workspace
+ * list holds no one else's). A private and a shared connector of the same
+ * identifier resolve to the private one at run time, so the menu keeps that
+ * row: the one its settings and the pin act on.
+ */
+export const agentMenuConnectors = (
+ connectors: ConnectorWithTools[],
+ {
+ agentId,
+ inWorkspace,
+ privateAgent,
+ }: { agentId?: string; inWorkspace: boolean; privateAgent: boolean },
+): ConnectorWithTools[] => {
+ if (!inWorkspace) return connectors;
+
+ return pickRunConnectors(connectors, { agentId, includePrivate: privateAgent });
+};
+
+/** {@link agentMenuConnectors} for `agentId`, from the user's MCP connectors. */
+export const useAgentMenuConnectors = (agentId?: string): ConnectorWithTools[] => {
+ const inWorkspace = !!useActiveWorkspaceId();
+ const privateAgent = useAgentStore(
+ (s) => !!agentId && s.agentMap?.[agentId]?.visibility === 'private',
+ );
+ // Library connections only: an agent's own connections are managed on its profile
+ const connectors = useToolStore(
+ connectorSelectors.userMcpConnectorsForAgent(agentId ?? ''),
+ isEqual,
+ );
+
+ // A stable list: the menu rebuilds its connector rows when this changes
+ return useMemo(
+ () => agentMenuConnectors(connectors, { agentId, inWorkspace, privateAgent }),
+ [agentId, connectors, inWorkspace, privateAgent],
+ );
+};
+
+/**
+ * Whether `agentId` still loads a connector of `deleted`'s identifier once
+ * `deleted` is gone: a private connector that shadowed a shared one leaves the
+ * shared row serving the identifier.
+ */
+export const agentStillLoadsIdentifier = (
+ connectors: ConnectorWithTools[],
+ deleted: Pick<ConnectorWithTools, 'id' | 'identifier'>,
+ context: { agentId?: string; inWorkspace: boolean; privateAgent: boolean },
+): boolean =>
+ agentMenuConnectors(
+ connectors.filter((c) => c.id !== deleted.id),
+ context,
+ ).some((c) => c.identifier === deleted.identifier);
+
+/**
+ * Turn a deleted connector off for the agent, as removing a Composio connection
+ * does, so no orphaned switch survives it; unless the agent still loads a row of
+ * its identifier ({@link agentStillLoadsIdentifier}), which keeps it on. A
+ * failed write is logged: the delete has already happened.
+ */
+export const useUnpinDeletedConnector = (
+ agentId: string | undefined,
+ /** Turns the connector off for the agent (its two-state switch). */
+ turnOff: (identifier: string) => Promise<void>,
+) =>
+ useCallback(
+ async (deleted: ConnectorWithTools) => {
+ const context = {
+ agentId,
+ inWorkspace: !!getActiveWorkspaceId(),
+ privateAgent:
+ !!agentId && useAgentStore.getState().agentMap?.[agentId]?.visibility === 'private',
+ };
+ const connectors = connectorSelectors.userMcpConnectors(useToolStore.getState());
+ if (agentStillLoadsIdentifier(connectors, deleted, context)) return;
+
+ try {
+ await turnOff(deleted.identifier);
+ } catch (error) {
+ console.error('[Connector] Failed to unpin plugin after delete:', error);
+ }
+ },
+ [agentId, turnOff],
+ );
diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
index b42c7eed32c..32cfa2c8663 100644
--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
@@ -43,7 +43,6 @@ import {
pluginSelectors,
} from '@/store/tool/selectors';
import { ComposioServerStatus } from '@/store/tool/slices/composioStore';
-import { connectorSelectors } from '@/store/tool/slices/connector';
import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore/types';
import { useAgentId } from '../../hooks/useAgentId';
@@ -53,6 +52,7 @@ import { closeToolDetailPopovers } from '../components/useDetailPopoverState';
import { MemoryEffortControl } from '../Memory/Controls';
import { useMemoryEnabled } from '../Memory/useMemoryEnabled';
import { SearchAdvancedControls } from '../Search/Controls';
+import { useAgentMenuConnectors, useUnpinDeletedConnector } from './agentMenuConnectors';
import { isCapabilityTool, resolveCapabilityConfigPatch } from './capabilityTools';
import ComposioServerItem from './ComposioServerItem';
import ComposioSkillIcon from './ComposioSkillIcon';
@@ -60,6 +60,7 @@ import { SKILL_ICON_SIZE } from './constants';
import { resolveImplicitMode } from './librarySkillPolicy';
import LobehubSkillIcon from './LobehubSkillIcon';
import LobehubSkillServerItem from './LobehubSkillServerItem';
+import PrivateConnectorTag from './PrivateConnectorTag';
import SkillRow from './SkillRow';
import ToolItemDetailPopover from './ToolItemDetailPopover';
import { ToolPickerHeader } from './ToolPickerHeader';
@@ -511,10 +512,11 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
// Agent Skills related state
const installedBuiltinSkills = useToolStore(builtinToolSelectors.installedBuiltinSkills, isEqual);
- // MCP connectors the user added: custom ones and marketplace installs
- const customConnectors = useToolStore(
- connectorSelectors.userMcpConnectorsForAgent(agentId),
- isEqual,
+ // MCP connectors the user added that this agent loads (custom and marketplace)
+ const customConnectors = useAgentMenuConnectors(agentId);
+ // A deleted connector's switch turns off, unless the agent still loads a row of it
+ const unpinDeleted = useUnpinDeletedConnector(agentId, (identifier) =>
+ updateSkillPolicy(identifier, 'disabled'),
);
const getConfigure = useConnectorConfigure();
const [
@@ -865,9 +867,8 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
],
);
- // Connector MCP list items (custom ones and marketplace installs).
- // Toggling adds the connector identifier to agents.plugins[] — the same field
- // the runtime resolves connectors from, so they become callable immediately.
+ // Connector MCP rows (custom and marketplace). Toggling adds the identifier to
+ // agents.plugins[], the field the runtime resolves connectors from.
const customConnectorItems = useMemo(
() =>
customConnectors.map((connector) => {
@@ -890,15 +891,10 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
displayName: title,
onDelete: async () => {
await deleteConnector(connector.id);
- // Mirror removeComposioServer: drop the identifier from agent.plugins so
- // no orphaned pin survives the connector deletion.
- try {
- await updateSkillPolicy(connector.identifier, 'disabled');
- } catch (error) {
- console.error('[Connector] Failed to unpin plugin after delete:', error);
- }
+ await unpinDeleted(connector);
},
},
+ extraTag: connector.visibility === 'private' ? <PrivateConnectorTag /> : undefined,
icon,
id: connector.identifier,
popoverContent,
@@ -906,7 +902,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
title,
});
}),
- [customConnectors, t, createManagedSkillItem, deleteConnector, getConfigure, updateSkillPolicy],
+ [customConnectors, t, createManagedSkillItem, deleteConnector, getConfigure, unpinDeleted],
);
// Distinguish community plugins and custom plugins.
diff --git a/src/features/Connectors/CustomConnectorModal/index.test.tsx b/src/features/Connectors/CustomConnectorModal/index.test.tsx
index 8ba33daf5f9..59034bdfa3a 100644
--- a/src/features/Connectors/CustomConnectorModal/index.test.tsx
+++ b/src/features/Connectors/CustomConnectorModal/index.test.tsx
@@ -430,3 +430,40 @@ describe('CustomConnectorModal OAuth on save', () => {
);
});
});
+
+describe('CustomConnectorModal create visibility', () => {
+ const save = () =>
+ mocks.devModal!.onSave!({
+ customParams: { mcp: { auth: { type: 'none' }, type: 'http', url: 'https://mcp.example' } },
+ identifier: 'my-notion',
+ } as LobeToolCustomPlugin);
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.state.connector = undefined;
+ mocks.state.createConnector.mockResolvedValue({ id: 'new-id', isNew: true });
+ mocks.state.syncConnectorTools.mockResolvedValue(undefined);
+ });
+
+ it("adds the connector as the caller's private one from the Private tab", async () => {
+ render(<CustomConnectorModal open visibility={'private'} onClose={() => {}} />);
+ await save();
+
+ expect(mocks.state.createConnector).toHaveBeenCalledWith(
+ expect.objectContaining({ identifier: 'my-notion', visibility: 'private' }),
+ );
+ });
+
+ it('leaves the visibility to the server everywhere else (the shared pool)', async () => {
+ for (const visibility of [undefined, 'public'] as const) {
+ mocks.state.createConnector.mockClear();
+ const { unmount } = render(
+ <CustomConnectorModal open visibility={visibility} onClose={() => {}} />,
+ );
+ await save();
+
+ expect(mocks.state.createConnector.mock.calls[0][0]).not.toHaveProperty('visibility');
+ unmount();
+ }
+ });
+});
diff --git a/src/features/Connectors/CustomConnectorModal/index.tsx b/src/features/Connectors/CustomConnectorModal/index.tsx
index 89a87b9f0a0..9483df109ab 100644
--- a/src/features/Connectors/CustomConnectorModal/index.tsx
+++ b/src/features/Connectors/CustomConnectorModal/index.tsx
@@ -1,4 +1,8 @@
-import { type LobeToolCustomPlugin, type McpConnectVia } from '@lobechat/types';
+import {
+ type ConnectorVisibility,
+ type LobeToolCustomPlugin,
+ type McpConnectVia,
+} from '@lobechat/types';
import { connectorConnectVia, connectorDeviceBinding } from '@lobechat/utils/mcpEndpoint';
import { memo, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -41,6 +45,11 @@ interface CustomConnectorModalProps {
onClose: () => void;
onEditSuccess?: () => void;
open: boolean;
+ /**
+ * Create mode in a workspace: `private` adds the connector as the caller's
+ * own, which only their private agents load (the Private tab's add).
+ */
+ visibility?: ConnectorVisibility;
}
/** Drop empty key/value pairs a user may have left behind in an editor. */
@@ -81,7 +90,7 @@ interface StdioConfig {
* connected yet (see `requiresOAuth`); other edits keep the accounts
*/
const CustomConnectorModal = memo<CustomConnectorModalProps>(
- ({ open, onClose, connectorId, legacyPlugin, onEditSuccess }) => {
+ ({ open, onClose, connectorId, legacyPlugin, onEditSuccess, visibility }) => {
const { t } = useTranslation('tool');
const createConnector = useToolStore((s) => s.createConnector);
const deleteConnector = useToolStore((s) => s.deleteConnector);
@@ -439,6 +448,7 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
}),
name: identifier,
sourceType: ConnectorSourceType.custom,
+ ...(visibility === 'private' && { visibility }),
};
// OAuth: create with the OIDC config, then drive the authorize popup that
@@ -538,6 +548,9 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
mode={isEditMode || isMigrationMode ? 'edit' : 'create'}
open={open}
value={editValue}
+ privateConnector={
+ isEditMode ? connector?.visibility === 'private' : visibility === 'private'
+ }
onDelete={handleDelete}
onSave={handleSave}
onOpenChange={(next) => {
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/InlineMcpAppView.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/InlineMcpAppView.tsx
index 38424e7807e..1b443ccc0f2 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/InlineMcpAppView.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/InlineMcpAppView.tsx
@@ -14,10 +14,11 @@ export const InlineMcpAppView = (
const canSendMessage = useConversationStore((s) => s.composerTarget.writable);
const sendMessage = useConversationStore((s) => s.sendMessage);
const scope = useConversationStore((s) => messageMapKey(s.context));
+ const topicId = useConversationStore((s) => s.context.topicId ?? undefined);
return (
<ManagedMcpAppView
{...props}
- host={{ agentId, canSendMessage, sendMessage }}
+ host={{ agentId, canSendMessage, sendMessage, topicId }}
icon={icon}
location={'inline'}
scope={scope}
diff --git a/src/features/Conversation/WorkingSidebar/DynamicTabPanes.tsx b/src/features/Conversation/WorkingSidebar/DynamicTabPanes.tsx
index 193bc57def0..df3ae0716bb 100644
--- a/src/features/Conversation/WorkingSidebar/DynamicTabPanes.tsx
+++ b/src/features/Conversation/WorkingSidebar/DynamicTabPanes.tsx
@@ -87,6 +87,8 @@ interface DynamicTabPanesProps {
onBrowserMetadataChange: (tab: string, metadata: BrowserTabMetadata) => void;
onCloseTab: (tab: string) => void;
openedTabs: string[];
+ /** The conversation an entrypoint app runs in. */
+ topicId?: string;
visible: boolean;
}
@@ -100,6 +102,7 @@ const DynamicTabPanes = memo<DynamicTabPanesProps>(
onBrowserMetadataChange,
openedTabs,
onCloseTab,
+ topicId,
visible,
}) => {
const enabled = useServerConfigStore(serverConfigSelectors.enableMcpApps);
@@ -153,6 +156,7 @@ const DynamicTabPanes = memo<DynamicTabPanesProps>(
agentId={agentId}
scope={composerTarget.contextKey}
tab={tab}
+ topicId={topicId}
onClose={onCloseTab}
/>
</Flexbox>
diff --git a/src/features/Conversation/WorkingSidebar/McpAppPane.tsx b/src/features/Conversation/WorkingSidebar/McpAppPane.tsx
index 6e76413ba54..5e49b9996cd 100644
--- a/src/features/Conversation/WorkingSidebar/McpAppPane.tsx
+++ b/src/features/Conversation/WorkingSidebar/McpAppPane.tsx
@@ -35,6 +35,7 @@ export const McpAppPane = ({ id, scope }: { id: string; scope: string }) => {
if (!host) throw new Error('No writable conversation');
await host.sendMessage(params);
},
+ topicId: message.topicId ?? undefined,
}}
onThisDevice={!!mcpApp.deviceId}
/>
diff --git a/src/features/Conversation/WorkingSidebar/McpEntryPane.tsx b/src/features/Conversation/WorkingSidebar/McpEntryPane.tsx
index f6afac0d159..9b3a08cca05 100644
--- a/src/features/Conversation/WorkingSidebar/McpEntryPane.tsx
+++ b/src/features/Conversation/WorkingSidebar/McpEntryPane.tsx
@@ -15,11 +15,14 @@ export const McpEntryPane = ({
tab,
scope,
agentId,
+ topicId,
onClose,
}: {
tab: string;
scope: string;
agentId?: string;
+ /** The conversation the app runs in: its calls and resources resolve there. */
+ topicId?: string;
onClose: (tab: string) => void;
}) => {
const { t } = useTranslation('plugin');
@@ -40,7 +43,7 @@ export const McpEntryPane = ({
const open = () => {
setUnsupported(false);
if (identifier && toolName)
- void openMcpAppEntrypoint({ agentId, id, identifier, linkId, toolName });
+ void openMcpAppEntrypoint({ agentId, id, identifier, linkId, toolName, topicId });
};
// Context the view reported belongs to this instance only
useEffect(() => () => mcpAppContext.clear(id), [id]);
@@ -80,6 +83,7 @@ export const McpEntryPane = ({
toolCallId={id}
host={{
agentId,
+ topicId,
canSendMessage: !!host,
sendMessage: async (params) => {
if (host) await host.sendMessage(params);
diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsx
index d3c477b1f17..5bd1ee1655d 100644
--- a/src/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/index.tsx
@@ -847,6 +847,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
scope: composerTarget.writable ? composerTarget.contextKey : undefined,
terminalAvailable,
toggleTerminalPanel,
+ topicId: topicId ?? undefined,
});
// The floating card keeps a 16px margin on each side.
@@ -1074,6 +1075,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
browserSessionId={browserSessionId}
composerTarget={composerTarget}
openedTabs={openedTabs}
+ topicId={topicId ?? undefined}
visible={!!showRightPanel}
onCloseTab={closeTab}
onBrowserMetadataChange={(tab, metadata) => {
diff --git a/src/features/Conversation/WorkingSidebar/useOpenMenuItems.tsx b/src/features/Conversation/WorkingSidebar/useOpenMenuItems.tsx
index 7ddb63bebb8..b242eca5805 100644
--- a/src/features/Conversation/WorkingSidebar/useOpenMenuItems.tsx
+++ b/src/features/Conversation/WorkingSidebar/useOpenMenuItems.tsx
@@ -22,6 +22,8 @@ interface OpenMenuOptions {
scope?: string;
terminalAvailable: boolean;
toggleTerminalPanel: (open: boolean) => void;
+ /** The conversation an app opened from the menu runs in. */
+ topicId?: string;
}
export const useOpenMenuItems = ({
availableTabs,
@@ -35,9 +37,10 @@ export const useOpenMenuItems = ({
scope,
terminalAvailable,
toggleTerminalPanel,
+ topicId,
}: OpenMenuOptions) => {
const { t } = useTranslation(['chat', 'setting', 'plugin']);
- const entries = useMcpAppEntrypoints(agentId);
+ const entries = useMcpAppEntrypoints(agentId, topicId);
return useCallback((): DropdownItem[] => {
const itemOf = (key: string): DropdownItem | undefined => {
const tab = availableTabs.get(key);
@@ -137,6 +140,7 @@ export const useOpenMenuItems = ({
identifier: entry.identifier,
linkId: entry.linkId,
toolName: entry.toolName,
+ topicId,
}),
);
}
@@ -166,5 +170,6 @@ export const useOpenMenuItems = ({
t,
terminalAvailable,
toggleTerminalPanel,
+ topicId,
]);
};
diff --git a/src/features/MCPApp/McpAppView.tsx b/src/features/MCPApp/McpAppView.tsx
index b460f487b28..ee785ae19da 100644
--- a/src/features/MCPApp/McpAppView.tsx
+++ b/src/features/MCPApp/McpAppView.tsx
@@ -54,7 +54,12 @@ export interface McpAppViewProps {
arguments?: string;
/** Rendered instead when the view can't be loaded. */
fallback: ReactNode;
- host: Pick<AppViewContext, 'agentId' | 'sendMessage' | 'canSendMessage'>;
+ /**
+ * `topicId`: the conversation the result belongs to. The view is read, and
+ * calls, with the same run scope the producing tool call had (a private
+ * agent's own topic can reach its owner's private connectors).
+ */
+ host: Pick<AppViewContext, 'agentId' | 'sendMessage' | 'canSendMessage' | 'topicId'>;
identifier: string;
/**
* The connector account the view acts as, when its arguments cannot name
@@ -109,7 +114,7 @@ const McpAppView = memo<McpAppViewProps>(
// This view's requests still waiting for the user's answer
const [waitingApprovals, setWaitingApprovals] = useState(0);
const isDark = useIsDark();
- const { agentId, sendMessage, canSendMessage } = host;
+ const { agentId, sendMessage, canSendMessage, topicId } = host;
const containerRef = useRef<HTMLDivElement>(null);
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
const [appModes, setAppModes] = useState<McpAppDisplayMode[]>();
@@ -122,6 +127,7 @@ const McpAppView = memo<McpAppViewProps>(
onThisDevice,
server,
toolArguments: args,
+ topicId,
});
const resource = pickAppResource(data, resourceUri);
@@ -184,6 +190,7 @@ const McpAppView = memo<McpAppViewProps>(
sendMessage,
server,
t,
+ topicId,
});
const bridgeRef = useRef<AppBridge>(undefined);
// The session of the view now in the frame
diff --git a/src/features/MCPApp/appHost.test.ts b/src/features/MCPApp/appHost.test.ts
index e856487f08f..9856c3dd4e3 100644
--- a/src/features/MCPApp/appHost.test.ts
+++ b/src/features/MCPApp/appHost.test.ts
@@ -66,6 +66,7 @@ const setup = ({
sendMessage,
server: 'weather-server',
t: (key: string) => key,
+ topicId: 'tpc_1',
}),
onHeight,
onNavigated,
@@ -405,6 +406,12 @@ describe('connectAppView', () => {
await call(1, 'Rome');
+ // Approved and run in the view's conversation, so both resolve the same connector
+ expect(getAppToolCallPolicy).toHaveBeenCalledWith('weather-demo', 'get_forecast', {
+ agentId: 'agt_1',
+ toolArgs: { city: 'Rome' },
+ topicId: 'tpc_1',
+ });
expect(invokeMcpToolCall).toHaveBeenCalledWith(
expect.objectContaining({ apiName: 'get_forecast', identifier: 'weather-demo' }),
// On the server, and where, the view came from
@@ -414,6 +421,7 @@ describe('connectAppView', () => {
onThisDevice: true,
server: 'weather-server',
signal: expect.any(AbortSignal),
+ topicId: 'tpc_1',
},
);
});
diff --git a/src/features/MCPApp/appHost.ts b/src/features/MCPApp/appHost.ts
index ceba8df6d8d..8e4e5f172ae 100644
--- a/src/features/MCPApp/appHost.ts
+++ b/src/features/MCPApp/appHost.ts
@@ -7,13 +7,13 @@ import type { TFunction } from 'i18next';
import { mcpService } from '@/services/mcp';
import { getToolStoreState } from '@/store/tool';
-import { connectorSelectors } from '@/store/tool/slices/connector/selectors';
import { anySignal } from './abortSignal';
import { mcpAppNameSelector } from './appName';
import type { AppDisplayContext, McpAppBridgeHost } from './bridge';
import { buildHostContext, connectMcpAppBridge } from './bridge';
import { confirmAppMessage, confirmAppOpenLink, confirmAppToolCall } from './confirm';
+import { connectorForTool } from './connectorForTool';
import { isAppFrameNavigatedNotice } from './frameDocument';
import { sendAppMessage } from './sendAppMessage';
import { getAppToolCallPolicy } from './toolCallPolicy';
@@ -48,6 +48,12 @@ export interface AppViewContext {
/** The MCP server the view came from; its tool calls reach no other. */
server?: string;
t: TFunction<'plugin'> | ((key: string, options?: Record<string, unknown>) => string);
+ /**
+ * The conversation the result belongs to: its calls resolve connectors with
+ * the same run scope the producing tool call had, so a private agent's own
+ * topic can reach its owner's private connectors.
+ */
+ topicId?: string;
}
export interface ConnectAppViewOptions {
@@ -162,11 +168,12 @@ export const connectAppView = ({
onThisDevice,
server,
t,
+ topicId,
args: initiatingArgs,
linkId: viewLinkId,
} = getContext();
const linkId = viewLinkId ?? getMcpAppLinkId(identifier, agentId, initiatingArgs);
- const policy = await getAppToolCallPolicy(identifier, name, { agentId, toolArgs });
+ const policy = await getAppToolCallPolicy(identifier, name, { agentId, toolArgs, topicId });
let allowed = policy === 'allow';
if (policy === 'confirm') {
if (pendingToolApprovals >= MAX_PENDING_TOOL_APPROVALS) {
@@ -214,7 +221,7 @@ export const connectAppView = ({
type: 'mcp',
},
// The view's HTML came from this machine for a local server, so its calls do too
- { agentId, fromMcpApp: true, onThisDevice, server, signal, linkId },
+ { agentId, fromMcpApp: true, onThisDevice, server, signal, linkId, topicId },
),
);
} finally {
@@ -335,10 +342,7 @@ export const getMcpAppLinkId = (
agentId?: string,
args?: string,
): string | undefined => {
- const connector = connectorSelectors.connectorByIdentifierForAgent(
- identifier,
- agentId,
- )(getToolStoreState());
+ const connector = connectorForTool(identifier, agentId)(getToolStoreState());
const param = resolveConnectorLinkParam(connector?.tools.map((tool) => tool.inputSchema) ?? []);
const input: unknown = safeParseJSON(args ?? '{}');
return isRecord(input) && typeof input[param] === 'string' ? (input[param] as string) : undefined;
diff --git a/src/features/MCPApp/appName.ts b/src/features/MCPApp/appName.ts
index bc5b966f9cf..cba87db5e14 100644
--- a/src/features/MCPApp/appName.ts
+++ b/src/features/MCPApp/appName.ts
@@ -1,7 +1,8 @@
import { toolSelectors } from '@/store/tool/selectors';
-import { connectorSelectors } from '@/store/tool/slices/connector';
import type { ToolStore } from '@/store/tool/store';
+import { connectorForTool } from './connectorForTool';
+
/**
* The name an MCP App goes by in the conversation: its plugin's title, else the
* connector's name (the agent's own connector first), else the identifier once
@@ -11,5 +12,5 @@ export const mcpAppNameSelector =
(identifier: string, agentId?: string) =>
(s: ToolStore): string =>
toolSelectors.getMetaById(identifier)(s)?.title ||
- connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(s)?.name ||
+ connectorForTool(identifier, agentId)(s)?.name ||
identifier;
diff --git a/src/features/MCPApp/connectorForTool.ts b/src/features/MCPApp/connectorForTool.ts
new file mode 100644
index 00000000000..462806f1706
--- /dev/null
+++ b/src/features/MCPApp/connectorForTool.ts
@@ -0,0 +1,16 @@
+import { getAllRunConnectors } from '@/services/runConnectors';
+import { connectorSelectors } from '@/store/tool/slices/connector/selectors';
+import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';
+import type { ToolStore } from '@/store/tool/store';
+
+/**
+ * The connector row an MCP App's tool prefix names: the local lists' row,
+ * else a row the server listed for a conversation (`connector.listForRun`) —
+ * the owner's personal connector a private agent's own topic runs is only
+ * there.
+ */
+export const connectorForTool =
+ (identifier: string, agentId?: string) =>
+ (s: ToolStore): ConnectorWithTools | undefined =>
+ connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(s) ??
+ getAllRunConnectors().find((row) => row.toolIdentifier === identifier);
diff --git a/src/features/MCPApp/entrypoints.test.ts b/src/features/MCPApp/entrypoints.test.ts
index 911d883eb2e..2181ca677fa 100644
--- a/src/features/MCPApp/entrypoints.test.ts
+++ b/src/features/MCPApp/entrypoints.test.ts
@@ -41,7 +41,9 @@ describe('sidebar app entries', () => {
},
);
expect(selectMcpAppEntrypoints(inaccessible as ToolStore, false)).toEqual([]);
- expect(selectMcpAppEntrypoints(state, true)).toEqual([{ ...entry, identifier: 'notes' }]);
+ expect(selectMcpAppEntrypoints(state, true)).toEqual([
+ { ...entry, connectorIdentifier: 'notes', identifier: 'notes' },
+ ]);
});
it('uses the agent connector and hides disabled tools even if a plugin declares the entry', () => {
const connector = {
@@ -55,6 +57,74 @@ describe('sidebar app entries', () => {
const scoped = { ...state, agentConnectors: { agent: [connector] } } as unknown as ToolStore;
expect(selectMcpAppEntrypoints(scoped, true, 'agent')).toEqual([]);
});
+ it("lists a personal row the conversation's listing holds, under its listed prefix", () => {
+ // A private agent's own topic runs its owner's personal connector: no local
+ // list holds that row, only the server's listing for the conversation
+ const personal = {
+ id: 'personal-row',
+ identifier: 'docs',
+ isEnabled: true,
+ mcpServerUrl: 'https://docs.example.com',
+ toolIdentifier: 'docs-personal',
+ tools: [{ toolName: 'open', permission: 'auto', metadata: { threadEntry: entry } }],
+ };
+ const listed = selectMcpAppEntrypoints(state, true, 'agent', [personal] as any);
+ expect(listed).toContainEqual({
+ ...entry,
+ connectorIdentifier: 'docs',
+ identifier: 'docs-personal',
+ });
+ // Without the listing the local lists stand in, which do not hold it
+ expect(
+ selectMcpAppEntrypoints(state, true, 'agent').some((e) => e.identifier === 'docs-personal'),
+ ).toBe(false);
+ });
+ it("shows a listed row's entries once a later sync discovers them locally", () => {
+ const listedRow = {
+ id: 'shared-row',
+ identifier: 'docs',
+ isEnabled: true,
+ mcpServerUrl: 'https://docs.example.com',
+ toolIdentifier: 'docs',
+ tools: [{ toolName: 'open', permission: 'auto' }],
+ };
+ // The listing predates discovery; the local copy has since been synced
+ const synced = {
+ ...state,
+ connectors: [
+ { ...listedRow, tools: [{ ...listedRow.tools[0], metadata: { threadEntry: entry } }] },
+ ],
+ } as unknown as ToolStore;
+ expect(selectMcpAppEntrypoints(synced, true, 'agent', [listedRow] as any)).toContainEqual({
+ ...entry,
+ connectorIdentifier: 'docs',
+ identifier: 'docs',
+ });
+ });
+ it('lists a private row mounted on the agent once, under the prefix its calls run by', () => {
+ // Regression: the mounted row is in both the base and the agent list; the
+ // agent list added its bare identifier, a second entry the server refuses.
+ const mounted = {
+ agentId: null,
+ id: '3f9a1c2e-mounted',
+ identifier: 'notes',
+ isEnabled: true,
+ mcpServerUrl: 'https://example.com',
+ metadata: { mountedByAgentId: 'agent' },
+ tools: [{ toolName: 'open', permission: 'auto', metadata: { threadEntry: entry } }],
+ visibility: 'private',
+ };
+ const scoped = {
+ ...state,
+ agentConnectors: { agent: [mounted] },
+ connectors: [mounted],
+ installedPlugins: [],
+ } as unknown as ToolStore;
+
+ expect(selectMcpAppEntrypoints(scoped, true, 'agent')).toEqual([
+ { ...entry, connectorIdentifier: 'notes', identifier: 'notes-3f9a1c2e' },
+ ]);
+ });
it('round trips entry identifiers containing colons and rejects malformed tabs', () => {
expect(parseMcpEntryTab(mcpEntryTabKey('notes:mine', 'open/page'))).toEqual({
identifier: 'notes:mine',
@@ -89,11 +159,23 @@ describe('sidebar app entries', () => {
true,
),
).toEqual([
- { ...entry, accountName: 'Work', identifier: 'mail', linkId: 'lnk_a' },
- { ...entry, accountName: 'Personal', identifier: 'mail', linkId: 'lnk_b' },
+ {
+ ...entry,
+ accountName: 'Work',
+ connectorIdentifier: 'mail',
+ identifier: 'mail',
+ linkId: 'lnk_a',
+ },
+ {
+ ...entry,
+ accountName: 'Personal',
+ connectorIdentifier: 'mail',
+ identifier: 'mail',
+ linkId: 'lnk_b',
+ },
]);
expect(selectMcpAppEntrypoints(connector([{ id: 'lnk_a', name: 'Work' }]), true)).toEqual([
- { ...entry, identifier: 'mail' },
+ { ...entry, connectorIdentifier: 'mail', identifier: 'mail' },
]);
});
it("keeps an entry's account in its tab", () => {
diff --git a/src/features/MCPApp/entrypoints.ts b/src/features/MCPApp/entrypoints.ts
index 692e237b618..39c246f3934 100644
--- a/src/features/MCPApp/entrypoints.ts
+++ b/src/features/MCPApp/entrypoints.ts
@@ -1,5 +1,6 @@
import { isDesktop } from '@lobechat/const';
import type { McpAppThreadEntry } from '@lobechat/const/mcpApp';
+import { connectorToolIdentifier } from '@lobechat/types';
import {
connectorMcpEndpoint,
type McpEndpointShape,
@@ -7,6 +8,7 @@ import {
} from '@lobechat/utils/mcpEndpoint';
import { isInstalledPluginAvailableInCurrentEnv } from '@/helpers/toolAvailability';
+import type { RunConnectorRow } from '@/services/runConnectors';
import { getServerConfigStoreState } from '@/store/serverConfig/store';
import { connectorSelectors } from '@/store/tool/slices/connector/selectors';
import type { ToolStore } from '@/store/tool/store';
@@ -14,6 +16,9 @@ import type { ToolStore } from '@/store/tool/store';
export interface AppEntrypoint extends McpAppThreadEntry {
/** Name of the account it opens as, on a connector holding several. */
accountName?: string;
+ /** The connector it belongs to, as the agent's configuration names it. */
+ connectorIdentifier?: string;
+ /** Its tool's identifier: the connector row's tool prefix. */
identifier: string;
/**
* The account it opens as, on a connector holding several: an entrypoint's
@@ -66,17 +71,46 @@ export const selectMcpAppEntrypoints = (
state: ToolStore,
enabled: boolean,
agentId?: string,
+ /**
+ * The rows the server listed for the conversation (`connector.listForRun`),
+ * each under its authoritative tool prefix. They are the conversation's
+ * connectors when present: only they hold the owner's personal rows a
+ * private agent's own topic runs.
+ */
+ runRows?: RunConnectorRow[],
): AppEntrypoint[] => {
if (!enabled) return [];
+ // Each row under its tool prefix, as the server names it: a private row is
+ // its own app beside the shared one of its connector, and a row mounted on
+ // the agent keeps its own prefix (only an agent-owned row is bare)
+ const reserved = new Set(state.connectors.map((c) => c.identifier));
+ const prefixOf = (connector: (typeof state.connectors)[number]) =>
+ connectorToolIdentifier(connector, undefined, reserved);
const identifiers = new Set([
...state.installedPlugins.map((plugin) => plugin.identifier),
- ...state.connectors.map((connector) => connector.identifier),
- ...(agentId ? (state.agentConnectors[agentId] ?? []) : []).map(
- (connector) => connector.identifier,
- ),
+ ...(runRows
+ ? runRows.map((row) => row.toolIdentifier)
+ : [
+ ...state.connectors.map(prefixOf),
+ ...(agentId ? (state.agentConnectors[agentId] ?? []) : []).map(prefixOf),
+ ]),
]);
+ // A listed row the local lists also hold reads their copy's tools: a
+ // discovery sync updates those after the listing, so its entries show
+ const localRows = new Map(
+ [...state.connectors, ...(agentId ? (state.agentConnectors[agentId] ?? []) : [])].map(
+ (row) => [row.id, row] as const,
+ ),
+ );
+ const connectorOf = (identifier: string) => {
+ if (!runRows)
+ return connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(state);
+ const row = runRows.find((listed) => listed.toolIdentifier === identifier);
+ const local = row && localRows.get(row.id);
+ return row && local ? { ...row, isEnabled: local.isEnabled, tools: local.tools } : row;
+ };
return [...identifiers].flatMap((identifier) => {
- const connector = connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(state);
+ const connector = connectorOf(identifier);
if (connector && !connector.isEnabled) return [];
const isMcp = connector && (connector.mcpServerUrl || connector.mcpConnectionType === 'stdio');
const plugin = state.installedPlugins.find((item) => item.identifier === identifier);
@@ -108,10 +142,11 @@ export const selectMcpAppEntrypoints = (
? accounts.map((account) => ({
...entry,
accountName: account.name,
+ connectorIdentifier: connector?.identifier ?? identifier,
identifier,
linkId: account.id,
}))
- : [{ ...entry, identifier }],
+ : [{ ...entry, connectorIdentifier: connector?.identifier ?? identifier, identifier }],
);
});
};
diff --git a/src/features/MCPApp/openEntrypoint.test.ts b/src/features/MCPApp/openEntrypoint.test.ts
index 9904badb9d0..f656c161012 100644
--- a/src/features/MCPApp/openEntrypoint.test.ts
+++ b/src/features/MCPApp/openEntrypoint.test.ts
@@ -72,6 +72,24 @@ describe('openMcpAppEntrypoint', () => {
});
});
+ it('runs the entrypoint in the conversation it opens from', async () => {
+ // A private connector resolves only in its owner's private-agent topic, so
+ // without the topic both the approval and the call land on another row.
+ mocks.invoke.mockResolvedValue(viewResult('private'));
+
+ await openMcpAppEntrypoint({ ...call, topicId: 'tpc_own' });
+
+ expect(mocks.policy).toHaveBeenCalledWith('fixture', 'open_thread', {
+ agentId: 'agent',
+ fromEntrypoint: true,
+ topicId: 'tpc_own',
+ });
+ expect(mocks.invoke).toHaveBeenCalledWith(
+ expect.objectContaining({ apiName: 'open_thread', id: call.id }),
+ { agentId: 'agent', fromEntrypoint: true, topicId: 'tpc_own' },
+ );
+ });
+
it('shows the tab as opening until the call answers', async () => {
let answer!: (value: unknown) => void;
mocks.invoke.mockReturnValue(new Promise((resolve) => (answer = resolve)));
diff --git a/src/features/MCPApp/openEntrypoint.ts b/src/features/MCPApp/openEntrypoint.ts
index cc83a5965e4..325e0bba350 100644
--- a/src/features/MCPApp/openEntrypoint.ts
+++ b/src/features/MCPApp/openEntrypoint.ts
@@ -13,6 +13,12 @@ export interface McpAppEntrypointCall {
/** The account to open as, on a connector holding several. */
linkId?: string;
toolName: string;
+ /**
+ * The conversation the app opens in. A private connector resolves only in
+ * its owner's private-agent topic, so the approval and the call need it to
+ * reach the row the open menu listed.
+ */
+ topicId?: string;
}
/** Call an entrypoint's tool with `{}`, as MCP Apps opens one, and require a view in the result. */
@@ -22,17 +28,19 @@ export const callMcpAppEntrypoint = async ({
identifier,
linkId,
toolName,
+ topicId,
}: McpAppEntrypointCall): Promise<MCPToolCallResult> => {
// Entrypoints ignore `_meta.ui.visibility`; the agent's tool rules still apply
const policy = await getAppToolCallPolicy(identifier, toolName, {
agentId,
fromEntrypoint: true,
+ topicId,
});
if (policy === 'deny') throw new Error('This tool is unavailable');
const response = await mcpService.invokeMcpToolCall(
{ apiName: toolName, arguments: '{}', id, identifier, type: 'mcp' },
- { agentId, fromEntrypoint: true, linkId },
+ { agentId, fromEntrypoint: true, linkId, topicId },
);
if (!response?.success || !getMcpAppFromState(response.state)) {
throw new Error('The entrypoint returned no app view');
diff --git a/src/features/MCPApp/toolCallPolicy.connectorScope.test.ts b/src/features/MCPApp/toolCallPolicy.connectorScope.test.ts
new file mode 100644
index 00000000000..5834496136b
--- /dev/null
+++ b/src/features/MCPApp/toolCallPolicy.connectorScope.test.ts
@@ -0,0 +1,102 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getAppToolCallPolicy } from './toolCallPolicy';
+
+/**
+ * Which connector a view's call is approved against, with the real resolution
+ * (`resolveRunConnector` over the real connector selectors): the caller holds a
+ * private and a shared row of the same identifier, and only the server knows
+ * which one the conversation runs.
+ */
+const { resolveForRun, toolState } = vi.hoisted(() => ({
+ resolveForRun: vi.fn(),
+ toolState: {
+ agentConnectors: {} as Record<string, unknown[]>,
+ connectors: [] as unknown[],
+ ensureConfirmedConnectors: async () => {},
+ isConnectorListConfirmed: () => true,
+ syncConnectorTools: async () => {},
+ },
+}));
+
+vi.mock('@/store/tool', () => ({ getToolStoreState: () => toolState }));
+vi.mock('@/store/tool/store', () => ({ getToolStoreState: () => toolState }));
+vi.mock('@/store/tool/selectors', () => ({
+ pluginSelectors: {
+ getCustomPluginById: () => () => undefined,
+ getInstalledPluginById: () => () => undefined,
+ },
+}));
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: { connector: { resolveForRun: { query: resolveForRun } } },
+}));
+vi.mock('@/store/user', () => ({ getUserStoreState: () => ({}) }));
+vi.mock('@/store/user/selectors', () => ({
+ toolInterventionSelectors: { allowList: () => [], approvalMode: () => 'manual' },
+}));
+
+const mailRow = (id: string, visibility: 'private' | 'public', permission: string) => ({
+ agentId: null,
+ id,
+ identifier: 'mail',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example.com/mcp',
+ metadata: null,
+ tools: [{ permission, toolName: 'send' }],
+ visibility,
+});
+
+describe('getAppToolCallPolicy — private and shared rows of one connector', () => {
+ beforeEach(() => {
+ resolveForRun.mockReset();
+ toolState.connectors = [
+ // The caller's own private row runs `send` automatically…
+ mailRow('conn-private', 'private', 'auto'),
+ // …the workspace's shared row asks first
+ mailRow('conn-shared', 'public', 'needs_approval'),
+ ];
+ });
+
+ it("judges the shared row's tool by the shared row, whatever the private one allows", async () => {
+ // Regression: the policy ranked the private row first for any agent, so a
+ // public agent's view ran the shared tool with no approval. The two rows
+ // are now separate tool sets: the connector's identifier names the shared one.
+ expect(
+ await getAppToolCallPolicy('mail', 'send', { agentId: 'agt_public', topicId: 'tpc_1' }),
+ ).toBe('confirm');
+ });
+
+ it("follows the private row's tool set when the server runs it in the agent's own topic", async () => {
+ resolveForRun.mockResolvedValue({ id: 'conn-private' });
+
+ expect(
+ await getAppToolCallPolicy('mail-connpriv', 'send', {
+ agentId: 'agt_private',
+ topicId: 'tpc_own',
+ }),
+ ).toBe('allow');
+ expect(resolveForRun).toHaveBeenCalledWith({
+ agentId: 'agt_private',
+ identifier: 'mail-connpriv',
+ topicId: 'tpc_own',
+ });
+ });
+
+ it('judges the shared row without asking the server when the call names no topic', async () => {
+ expect(await getAppToolCallPolicy('mail', 'send', { agentId: 'agt_private' })).toBe('confirm');
+ expect(resolveForRun).not.toHaveBeenCalled();
+ });
+
+ it("asks when the server can't say which row runs", async () => {
+ resolveForRun.mockRejectedValue(new Error('offline'));
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ expect(
+ await getAppToolCallPolicy('mail-connpriv', 'send', {
+ agentId: 'agt_private',
+ topicId: 'tpc_own',
+ }),
+ ).toBe('confirm');
+ });
+});
diff --git a/src/features/MCPApp/toolCallPolicy.pluginPermission.test.ts b/src/features/MCPApp/toolCallPolicy.pluginPermission.test.ts
new file mode 100644
index 00000000000..b70d33d715c
--- /dev/null
+++ b/src/features/MCPApp/toolCallPolicy.pluginPermission.test.ts
@@ -0,0 +1,101 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getAppToolCallPolicy } from './toolCallPolicy';
+
+/**
+ * A plugin-backed MCP keeps its bare identifier on every call, while its tool
+ * permissions live on endpoint-less connector rows of that identifier: the
+ * workspace's shared row and the caller's private one. The permission is the
+ * one the conversation runs by, never only the row the bare identifier names.
+ */
+const { listed, toolState } = vi.hoisted(() => ({
+ listed: { rows: undefined as unknown[] | undefined },
+ toolState: {
+ agentConnectors: {} as Record<string, unknown[]>,
+ connectors: [] as unknown[],
+ ensureConfirmedConnectors: async () => {},
+ isConnectorListConfirmed: () => true,
+ syncConnectorTools: async () => {},
+ },
+}));
+
+vi.mock('@/store/tool', () => ({ getToolStoreState: () => toolState }));
+vi.mock('@/store/tool/store', () => ({ getToolStoreState: () => toolState }));
+vi.mock('@/store/tool/selectors', () => ({
+ pluginSelectors: {
+ getCustomPluginById: () => () => undefined,
+ getInstalledPluginById: (id: string) => () =>
+ id === 'notes'
+ ? { identifier: 'notes', manifest: { api: [{ name: 'delete_note' }] } }
+ : undefined,
+ isInstalledPluginsServerConfirmed: () => true,
+ },
+}));
+vi.mock('@/services/runConnectors', () => ({
+ getAllRunConnectors: () => listed.rows ?? [],
+ getRunConnectors: () => listed.rows,
+}));
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: { connector: { resolveForRun: { query: vi.fn().mockResolvedValue(null) } } },
+}));
+vi.mock('@/store/user', () => ({ getUserStoreState: () => ({}) }));
+vi.mock('@/store/user/selectors', () => ({
+ toolInterventionSelectors: { allowList: () => [], approvalMode: () => 'manual' },
+}));
+
+const permissionRow = (id: string, visibility: 'private' | 'public', permission: string) => ({
+ agentId: null,
+ id,
+ identifier: 'notes',
+ isEnabled: true,
+ metadata: null,
+ tools: [{ permission, toolName: 'delete_note' }],
+ visibility,
+});
+
+describe('getAppToolCallPolicy — a plugin tool with private and shared permission rows', () => {
+ const shared = permissionRow('conn-shared', 'public', 'auto');
+ const mine = permissionRow('conn-mine', 'private', 'disabled');
+
+ beforeEach(() => {
+ toolState.connectors = [shared, mine];
+ listed.rows = undefined;
+ });
+
+ it("refuses a tool the caller's private row disables when the run's rows are unknown", async () => {
+ // Regression: the plugin's permission was read from the row the bare
+ // identifier names (the shared one), so the private `disabled` setting
+ // the owner's own conversation runs by was dropped and the view allowed.
+ expect(
+ await getAppToolCallPolicy('notes', 'delete_note', {
+ agentId: 'agt_private',
+ topicId: 'tpc_own',
+ }),
+ ).toBe('deny');
+ });
+
+ it("follows the private row when the conversation's listing holds it", async () => {
+ listed.rows = [
+ { ...shared, toolIdentifier: 'notes' },
+ { ...mine, toolIdentifier: 'notes-connmine' },
+ ];
+
+ expect(
+ await getAppToolCallPolicy('notes', 'delete_note', {
+ agentId: 'agt_private',
+ topicId: 'tpc_own',
+ }),
+ ).toBe('deny');
+ });
+
+ it('follows the shared row when the listing leaves the private one out', async () => {
+ listed.rows = [{ ...shared, toolIdentifier: 'notes' }];
+
+ expect(
+ await getAppToolCallPolicy('notes', 'delete_note', {
+ agentId: 'agt_public',
+ topicId: 'tpc_1',
+ }),
+ ).not.toBe('deny');
+ });
+});
diff --git a/src/features/MCPApp/toolCallPolicy.test.ts b/src/features/MCPApp/toolCallPolicy.test.ts
index c2961a49545..44242b0576d 100644
--- a/src/features/MCPApp/toolCallPolicy.test.ts
+++ b/src/features/MCPApp/toolCallPolicy.test.ts
@@ -35,12 +35,12 @@ vi.mock('@/store/tool/selectors', () => ({
},
}));
-vi.mock('@/store/tool/slices/connector', () => ({
- connectorSelectors: {
- connectorByIdentifierForAgent: (id: string, agentId?: string) => () =>
- (agentId && toolStore.loaded.has(agentId) ? agentTools.get(agentId)?.get(id) : undefined) ??
- connectors.get(id),
- },
+// The row the conversation's call runs on; `toolCallPolicy.connectorScope.test.ts`
+// covers how it is resolved
+vi.mock('@/services/connectorRun', () => ({
+ resolveRunConnector: async (id: string, { agentId }: { agentId?: string } = {}) =>
+ (agentId && toolStore.loaded.has(agentId) ? agentTools.get(agentId)?.get(id) : undefined) ??
+ connectors.get(id),
}));
vi.mock('@/store/user', () => ({ getUserStoreState: () => ({}) }));
diff --git a/src/features/MCPApp/toolCallPolicy.ts b/src/features/MCPApp/toolCallPolicy.ts
index 0cb7fd9b284..af113aa46eb 100644
--- a/src/features/MCPApp/toolCallPolicy.ts
+++ b/src/features/MCPApp/toolCallPolicy.ts
@@ -9,14 +9,18 @@ import type {
} from '@lobechat/types';
import { getDisabledPluginIds } from '@lobechat/types';
+import { resolveRunConnector, type RunConnector } from '@/services/connectorRun';
+import { getRunConnectors } from '@/services/runConnectors';
import { getAgentStoreState } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { getToolStoreState } from '@/store/tool';
import { pluginSelectors } from '@/store/tool/selectors';
-import { connectorSelectors } from '@/store/tool/slices/connector';
+import { pickRunConnectors } from '@/store/tool/slices/connector/selectors';
import { getUserStoreState } from '@/store/user';
import { toolInterventionSelectors } from '@/store/user/selectors';
+import { connectorForTool } from './connectorForTool';
+
/**
* What LobeHub does with a `tools/call` a view sends. A view can call tools on
* load without any user gesture, so a call the conversation would stop for
@@ -88,18 +92,66 @@ type ToolLookup = { intervention?: unknown } | { missingFrom: string } | null;
* The tool's own approval setting as the conversation's manifest carries it,
* or null when the server doesn't offer the tool.
*/
+const PERMISSION_STRICTNESS: Record<string, number> = { auto: 1, disabled: 3, needs_approval: 2 };
+
+const strictestPermission = (permissions: (string | undefined)[]): string | undefined =>
+ permissions.reduce<string | undefined>(
+ (strictest, permission) =>
+ permission &&
+ (PERMISSION_STRICTNESS[permission] ?? 0) > (PERMISSION_STRICTNESS[strictest ?? ''] ?? 0)
+ ? permission
+ : strictest,
+ undefined,
+ );
+
+/**
+ * A plugin tool's permission as the conversation applies it: plugin calls keep
+ * the bare identifier, so the permission row is the one the run ranks first
+ * for it (the owner's private row shadows the shared one in their private
+ * agent's own topic, `pickRunConnectors`), not the row whose tool prefix the
+ * identifier names. The server's listing for the conversation decides which
+ * rows take part; without it any row of the identifier may be the one, so the
+ * strictest setting among them holds.
+ */
+const pluginToolPermission = (
+ identifier: string,
+ toolName: string,
+ run: { agentId?: string; topicId?: string },
+): string | undefined => {
+ const s = getToolStoreState();
+ const listed = run.agentId ? getRunConnectors(run) : undefined;
+ const rows = listed
+ ? pickRunConnectors(
+ listed.filter((c) => c.identifier === identifier),
+ { agentId: run.agentId, includePrivate: true },
+ )
+ : [
+ ...(s.connectors ?? []),
+ ...(run.agentId ? (s.agentConnectors?.[run.agentId] ?? []) : []),
+ ].filter((c) => c.identifier === identifier);
+ return strictestPermission(
+ rows.map((c) => c.tools.find((t) => t.toolName === toolName)?.permission),
+ );
+};
+
const findToolIntervention = (
+ /**
+ * The connector the call runs on ({@link resolveRunConnector}): approval is
+ * the executing row's, never a same-named row the conversation can't use.
+ */
+ resolved: RunConnector | undefined,
identifier: string,
toolName: string,
agentId: string | undefined,
/** The lists were just loaded from the server; if not, nothing here can waive approval. */
revalidated: boolean,
fromEntrypoint = false,
+ /** A plugin tool's permission as the conversation applies it ({@link pluginToolPermission}). */
+ pluginPermission?: string,
): ToolLookup => {
const s = getToolStoreState();
const confirmed = revalidated && s.isConnectorListConfirmed(agentId);
- const resolved = connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(s);
const plugin =
pluginSelectors.getInstalledPluginById(identifier)(s) ||
pluginSelectors.getCustomPluginById(identifier)(s);
@@ -152,7 +204,12 @@ const findToolIntervention = (
// (patchManifestWithPermissions). Until the server confirms the lists they
// may be stale or missing, so ask.
if (!confirmed) return { intervention: 'required' };
- const permission = resolved?.tools.find((t) => t.toolName === toolName)?.permission;
+ // The row the identifier names and the row the conversation ranks first for
+ // it: the stricter setting holds
+ const permission = strictestPermission([
+ resolved?.tools.find((t) => t.toolName === toolName)?.permission,
+ pluginPermission,
+ ]);
if (permission === 'disabled') return null;
// Never looser than the tool's own `always` (`patchManifestWithPermissions`)
if (permission === 'needs_approval')
@@ -220,6 +277,35 @@ const resyncConnectorTools = (connectorId: string): Promise<boolean> => {
return resync;
};
+/**
+ * The tool's setting on the connector the call runs on. Without an answer from
+ * the server about which row that is, it asks.
+ */
+const lookUpTool = async (
+ identifier: string,
+ toolName: string,
+ run: { agentId?: string; topicId?: string },
+ revalidated: boolean,
+ fromEntrypoint = false,
+): Promise<ToolLookup> => {
+ let connector: RunConnector | undefined;
+ try {
+ connector = await resolveRunConnector(identifier, run);
+ } catch (error) {
+ console.warn('[MCPApp] failed to resolve the connector of a view tool call:', error);
+ return { intervention: 'required' };
+ }
+ return findToolIntervention(
+ connector,
+ identifier,
+ toolName,
+ run.agentId,
+ revalidated,
+ fromEntrypoint,
+ pluginToolPermission(identifier, toolName, run),
+ );
+};
+
export const getAppToolCallPolicy = async (
identifier: string,
toolName: string,
@@ -227,14 +313,22 @@ export const getAppToolCallPolicy = async (
agentId,
toolArgs = {},
fromEntrypoint = false,
- }: { agentId?: string; toolArgs?: Record<string, unknown>; fromEntrypoint?: boolean } = {},
+ topicId,
+ }: {
+ agentId?: string;
+ toolArgs?: Record<string, unknown>;
+ fromEntrypoint?: boolean;
+ /** The conversation the view's result belongs to; its calls run in it. */
+ topicId?: string;
+ } = {},
): Promise<AppToolCallPolicy> => {
if (
fromEntrypoint &&
agentId &&
getDisabledPluginIds(
agentSelectors.getAgentConfigById(agentId)(getAgentStoreState())?.plugins,
- ).includes(identifier)
+ // The agent disables a connector, not one row's tool prefix
+ ).includes(connectorForTool(identifier, agentId)(getToolStoreState())?.identifier ?? identifier)
)
return 'deny';
if (fromEntrypoint) {
@@ -248,10 +342,11 @@ export const getAppToolCallPolicy = async (
}
}
const revalidated = await revalidateConnectors(agentId);
- let tool = findToolIntervention(identifier, toolName, agentId, revalidated, fromEntrypoint);
+ const run = { agentId, topicId };
+ let tool = await lookUpTool(identifier, toolName, run, revalidated, fromEntrypoint);
if (tool && 'missingFrom' in tool) {
tool = (await resyncConnectorTools(tool.missingFrom))
- ? findToolIntervention(identifier, toolName, agentId, revalidated, fromEntrypoint)
+ ? await lookUpTool(identifier, toolName, run, revalidated, fromEntrypoint)
: null;
}
if (!tool || 'missingFrom' in tool) return 'deny';
diff --git a/src/features/MCPApp/useMcpAppEntrypoints.ts b/src/features/MCPApp/useMcpAppEntrypoints.ts
index 0465bb2d2c7..d7a7776d2e2 100644
--- a/src/features/MCPApp/useMcpAppEntrypoints.ts
+++ b/src/features/MCPApp/useMcpAppEntrypoints.ts
@@ -1,6 +1,7 @@
-import { getDisabledPluginIds } from '@lobechat/types';
-import { useEffect } from 'react';
+import { connectorToolIdentifier, getDisabledPluginIds } from '@lobechat/types';
+import { useEffect, useState } from 'react';
+import { getRunConnectors, refreshRunConnectors } from '@/services/runConnectors';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { refreshMcpAppDiscovery } from '@/store/mcpApp/discovery';
@@ -12,8 +13,22 @@ import { connectorSelectors } from '@/store/tool/slices/connector/selectors';
import { selectMcpAppEntrypoints } from './entrypoints';
/** Refresh legacy cached discovery once per user session, without schema migration. */
-export const useMcpAppEntrypoints = (agentId?: string) => {
+export const useMcpAppEntrypoints = (agentId?: string, topicId?: string) => {
const enabled = useServerConfigStore(serverConfigSelectors.enableMcpApps);
+ // The conversation's connector rows as the server lists them, personal ones
+ // included; until listed (or outside a workspace) the local lists stand in
+ const [runRows, setRunRows] = useState(() => getRunConnectors({ agentId, topicId }));
+ useEffect(() => {
+ setRunRows(getRunConnectors({ agentId, topicId }));
+ if (!enabled || !agentId) return;
+ let live = true;
+ void refreshRunConnectors({ agentId, topicId }).then((rows) => {
+ if (live && rows) setRunRows(rows);
+ });
+ return () => {
+ live = false;
+ };
+ }, [enabled, agentId, topicId]);
const agentPlugins = useAgentStore((s) =>
enabled && agentId ? agentSelectors.getAgentConfigById(agentId)(s)?.plugins : undefined,
);
@@ -37,7 +52,9 @@ export const useMcpAppEntrypoints = (agentId?: string) => {
const state = getToolStoreState();
for (const row of [...connectors, ...(agentId ? (agentConnectors[agentId] ?? []) : [])]) {
const connector = connectorSelectors.connectorByIdentifierForAgent(
- row.identifier,
+ row.agentId
+ ? row.identifier
+ : connectorToolIdentifier(row, undefined, new Set(connectors.map((c) => c.identifier))),
agentId,
)(state);
if (connector?.id !== row.id || !connector.isEnabled) continue;
@@ -68,7 +85,9 @@ export const useMcpAppEntrypoints = (agentId?: string) => {
});
}
}, [enabled, plugins, pluginsConfirmed, connectors, agentConnectors, agentId]);
- return selectMcpAppEntrypoints(getToolStoreState(), enabled, agentId).filter(
- (entry) => !getDisabledPluginIds(agentPlugins).includes(entry.identifier),
+ return selectMcpAppEntrypoints(getToolStoreState(), enabled, agentId, runRows).filter(
+ // The agent disables a connector, not one row's tool prefix
+ (entry) =>
+ !getDisabledPluginIds(agentPlugins).includes(entry.connectorIdentifier ?? entry.identifier),
);
};
diff --git a/src/features/MCPApp/useMcpAppIdentity.ts b/src/features/MCPApp/useMcpAppIdentity.ts
index 06ce47697df..a07b6344e8c 100644
--- a/src/features/MCPApp/useMcpAppIdentity.ts
+++ b/src/features/MCPApp/useMcpAppIdentity.ts
@@ -1,10 +1,11 @@
import { useToolStore } from '@/store/tool';
import { toolSelectors } from '@/store/tool/selectors';
-import { connectorSelectors } from '@/store/tool/slices/connector/selectors';
+
+import { connectorForTool } from './connectorForTool';
export const useMcpAppIdentity = (identifier: string, agentId?: string) =>
useToolStore((s) => {
- const connector = connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(s);
+ const connector = connectorForTool(identifier, agentId)(s);
const plugin = toolSelectors.getMetaById(identifier)(s);
return [
connector?.name || plugin?.title || identifier,
diff --git a/src/features/PluginDevModal/MCPManifestForm/BoundDeviceSelect.test.ts b/src/features/PluginDevModal/MCPManifestForm/BoundDeviceSelect.test.ts
new file mode 100644
index 00000000000..93e35f1f44d
--- /dev/null
+++ b/src/features/PluginDevModal/MCPManifestForm/BoundDeviceSelect.test.ts
@@ -0,0 +1,50 @@
+import type { DeviceListItem } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { bindableMcpDeviceGroups } from './BoundDeviceSelect';
+
+const device = (deviceId: string, scope: 'personal' | 'workspace', visibility?: string) =>
+ ({ deviceId, scope, visibility }) as DeviceListItem;
+
+// A device list carries the caller's personal devices, the workspace's public
+// ones and only the caller's own private workspace enrollments
+const devices = [
+ device('laptop', 'personal'),
+ device('my-private', 'workspace', 'private'),
+ device('office-nas', 'workspace', 'public'),
+];
+
+const ids = (groups: ReturnType<typeof bindableMcpDeviceGroups>) => ({
+ private: groups.private.map((d) => d.deviceId),
+ shared: groups.shared.map((d) => d.deviceId),
+});
+
+describe('bindableMcpDeviceGroups', () => {
+ it('offers a personal server the personal devices', () => {
+ expect(ids(bindableMcpDeviceGroups(devices, false))).toEqual({
+ private: [],
+ shared: ['laptop'],
+ });
+ });
+
+ it('offers a shared workspace server the public workspace devices only', () => {
+ expect(ids(bindableMcpDeviceGroups(devices, true))).toEqual({
+ private: [],
+ shared: ['office-nas'],
+ });
+ });
+
+ it("also offers a private workspace server its creator's private devices", () => {
+ expect(ids(bindableMcpDeviceGroups(devices, true, true))).toEqual({
+ private: ['my-private'],
+ shared: ['office-nas'],
+ });
+ });
+
+ it('keeps personal devices out of a private workspace server', () => {
+ expect(ids(bindableMcpDeviceGroups([device('laptop', 'personal')], true, true))).toEqual({
+ private: [],
+ shared: [],
+ });
+ });
+});
diff --git a/src/features/PluginDevModal/MCPManifestForm/BoundDeviceSelect.tsx b/src/features/PluginDevModal/MCPManifestForm/BoundDeviceSelect.tsx
index 38574a3e224..f809e2134b0 100644
--- a/src/features/PluginDevModal/MCPManifestForm/BoundDeviceSelect.tsx
+++ b/src/features/PluginDevModal/MCPManifestForm/BoundDeviceSelect.tsx
@@ -17,22 +17,38 @@ const AUTO = 'auto';
const STATUS_PREFIX = 'status:';
/**
- * The devices an MCP server of the current scope may be bound to: the user's
- * personal devices for a personal server, the workspace's public devices for a
- * workspace one (a private enrollment only resolves for the member who
- * enrolled it, while every member's runs use the server). The server checks
- * the same rule on save (`assertConnectorDeviceBindingAllowed`).
+ * The devices an MCP server of the current scope may be bound to, grouped as
+ * the picker lists them. They follow who runs the server, the same split as
+ * connector loading:
+ *
+ * - personal server: the user's personal devices;
+ * - shared workspace server: the workspace's public devices (a private
+ * enrollment only resolves for the member who enrolled it, while every
+ * member's runs use the server);
+ * - private workspace server (`privateConnector`): also the user's own private
+ * devices of the workspace, since only their private agents run it. A device
+ * list only ever carries the caller's own private rows, and only the creator
+ * sees a private connector, so these are the creator's.
+ *
+ * The server checks the same rule on save (`assertConnectorDeviceBindingAllowed`).
*/
-export const bindableMcpDevices = (
+export const bindableMcpDeviceGroups = (
devices: DeviceListItem[] | undefined,
workspaceScoped: boolean,
-): DeviceListItem[] => {
+ privateConnector = false,
+): { private: DeviceListItem[]; shared: DeviceListItem[] } => {
const groups = groupExecutionTargetDevices(devices);
- return workspaceScoped ? groups.publicWorkspace : groups.personal;
+ if (!workspaceScoped) return { private: [], shared: groups.personal };
+ return {
+ private: privateConnector ? groups.privateWorkspace : [],
+ shared: groups.publicWorkspace,
+ };
};
interface BoundDeviceSelectProps {
onChange?: (value: string | undefined) => void;
+ /** The server is a private workspace connector: its creator's private devices are bindable too. */
+ privateConnector?: boolean;
/** The bound device id; `undefined` picks a device automatically. */
value?: string;
}
@@ -43,11 +59,15 @@ interface BoundDeviceSelectProps {
* unshared) stays selected as unavailable, so the user sees why its calls fail
* instead of the binding silently reading as automatic.
*/
-const BoundDeviceSelect = memo<BoundDeviceSelectProps>(({ onChange, value }) => {
+const BoundDeviceSelect = memo<BoundDeviceSelectProps>(({ onChange, privateConnector, value }) => {
const { t } = useTranslation(['plugin', 'chat']);
const workspaceScoped = !!useActiveWorkspaceId();
const { data, error, isConfirmed, isLoading, mutate } = useDeviceList();
- const devices = useMemo(() => bindableMcpDevices(data, workspaceScoped), [data, workspaceScoped]);
+ const groups = useMemo(
+ () => bindableMcpDeviceGroups(data, workspaceScoped, privateConnector),
+ [data, privateConnector, workspaceScoped],
+ );
+ const devices = useMemo(() => [...groups.private, ...groups.shared], [groups]);
const deviceName = (device: DeviceListItem) =>
device.friendlyName || device.hostname || device.deviceId;
@@ -85,6 +105,12 @@ const BoundDeviceSelect = memo<BoundDeviceSelectProps>(({ onChange, value }) =>
const isMissing = !!value && isConfirmed && !devices.some((d) => d.deviceId === value);
const options = useMemo<SelectOptions<string>>(() => {
+ const toOption = (device: DeviceListItem) => ({
+ disabled: !isConfirmed,
+ label: renderDevice(device),
+ title: deviceName(device),
+ value: device.deviceId,
+ });
// Until the server confirms the list, the stored copy may hold devices
// since removed or unshared: show its rows, but only pick from the
// confirmed list.
@@ -97,13 +123,8 @@ const BoundDeviceSelect = memo<BoundDeviceSelectProps>(({ onChange, value }) =>
value: `${STATUS_PREFIX}loading`,
},
]
- : devices.length > 0
- ? devices.map((device) => ({
- disabled: !isConfirmed,
- label: renderDevice(device),
- title: deviceName(device),
- value: device.deviceId,
- }))
+ : groups.shared.length > 0
+ ? groups.shared.map(toOption)
: [
{
disabled: true,
@@ -126,6 +147,16 @@ const BoundDeviceSelect = memo<BoundDeviceSelectProps>(({ onChange, value }) =>
},
]
: []),
+ // Only the caller's own private devices reach this list, so the group
+ // is simply absent for anyone without one
+ ...(error || isLoading || groups.private.length === 0
+ ? []
+ : [
+ {
+ label: t('chat:heteroAgent.executionTarget.personalGroup'),
+ options: groups.private.map(toOption),
+ },
+ ]),
...(error
? []
: [
@@ -140,6 +171,7 @@ const BoundDeviceSelect = memo<BoundDeviceSelectProps>(({ onChange, value }) =>
}, [
devices,
error,
+ groups,
isConfirmed,
isLoading,
isMissing,
diff --git a/src/features/PluginDevModal/MCPManifestForm/index.tsx b/src/features/PluginDevModal/MCPManifestForm/index.tsx
index c36258bf6b2..ebd5e710d9f 100644
--- a/src/features/PluginDevModal/MCPManifestForm/index.tsx
+++ b/src/features/PluginDevModal/MCPManifestForm/index.tsx
@@ -55,6 +55,11 @@ interface MCPManifestFormProps {
* button: there is nothing to authorize or test.
*/
onAuthorizeOAuth?: () => void;
+ /**
+ * The edited connector is private to its creator, so its device binding may
+ * also name their own private devices (see `bindableMcpDeviceGroups`).
+ */
+ privateConnector?: boolean;
}
export interface OAuthNotice {
@@ -104,6 +109,7 @@ const MCPManifestForm = ({
enableOAuth,
onAuthorizeOAuth,
oauthNotice,
+ privateConnector,
}: MCPManifestFormProps) => {
const { t } = useTranslation('plugin');
const mcpType = useWatch(form, MCP_TYPE);
@@ -430,7 +436,7 @@ const MCPManifestForm = ({
label={t('dev.mcp.boundDevice.label')}
name={BOUND_DEVICE}
>
- <BoundDeviceSelect />
+ <BoundDeviceSelect privateConnector={privateConnector} />
</Form.Field>
)}
{isOAuth &&
diff --git a/src/features/PluginDevModal/index.tsx b/src/features/PluginDevModal/index.tsx
index c4675b57138..2bb160b9063 100644
--- a/src/features/PluginDevModal/index.tsx
+++ b/src/features/PluginDevModal/index.tsx
@@ -45,6 +45,8 @@ interface DevModalProps {
) => Promise<void> | void;
onValueChange?: (value: Partial<LobeToolCustomPlugin>) => void;
open?: boolean;
+ /** The edited connector is private to its creator (see MCPManifestForm). */
+ privateConnector?: boolean;
value?: LobeToolCustomPlugin;
}
@@ -60,6 +62,7 @@ const DevModal = memo<DevModalProps>(
enableDeviceBinding,
enableOAuth,
getOAuthPlan,
+ privateConnector,
}) => {
const isEditMode = mode === 'edit';
const { t } = useTranslation('plugin');
@@ -238,6 +241,7 @@ const DevModal = memo<DevModalProps>(
form={form}
isEditMode={isEditMode}
oauthNotice={oauthPlan.notice}
+ privateConnector={privateConnector}
onAuthorizeOAuth={oauthPlan.authorize ? runOAuthFlow : undefined}
/>
</Flexbox>
diff --git a/src/features/Settings/skill/features/DetailBreadcrumb.tsx b/src/features/Settings/skill/features/DetailBreadcrumb.tsx
index 032fc5f286d..1f1c51be9ba 100644
--- a/src/features/Settings/skill/features/DetailBreadcrumb.tsx
+++ b/src/features/Settings/skill/features/DetailBreadcrumb.tsx
@@ -1,5 +1,6 @@
'use client';
+import type { ConnectorVisibility } from '@lobechat/types';
import { Breadcrumb, Icon, Text } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
@@ -28,36 +29,40 @@ interface DetailBreadcrumbProps {
listLabel: string;
onBack: () => void;
type: ToolDetailType;
+ /** The workspace connector tab the detail was opened from (names that tab's row). */
+ visibility?: ConnectorVisibility;
}
/** `Connectors › <entry>`: the second-level page names where it returns to. */
-const DetailBreadcrumb = memo<DetailBreadcrumbProps>(({ identifier, listLabel, onBack, type }) => {
- const name = useToolDisplayName(identifier, type);
+const DetailBreadcrumb = memo<DetailBreadcrumbProps>(
+ ({ identifier, listLabel, onBack, type, visibility }) => {
+ const name = useToolDisplayName(identifier, type, visibility);
- return (
- <div {...stylex.props(styles.root)}>
- <Breadcrumb
- separator={<Icon icon={ChevronRight} size={14} />}
- items={[
- {
- title: (
- <button type={'button'} {...stylex.props(styles.back)} onClick={onBack}>
- {listLabel}
- </button>
- ),
- },
- {
- title: (
- <Text ellipsis as={'span'} style={{ maxWidth: 320 }} weight={500}>
- {name}
- </Text>
- ),
- },
- ]}
- />
- </div>
- );
-});
+ return (
+ <div {...stylex.props(styles.root)}>
+ <Breadcrumb
+ separator={<Icon icon={ChevronRight} size={14} />}
+ items={[
+ {
+ title: (
+ <button type={'button'} {...stylex.props(styles.back)} onClick={onBack}>
+ {listLabel}
+ </button>
+ ),
+ },
+ {
+ title: (
+ <Text ellipsis as={'span'} style={{ maxWidth: 320 }} weight={500}>
+ {name}
+ </Text>
+ ),
+ },
+ ]}
+ />
+ </div>
+ );
+ },
+);
DetailBreadcrumb.displayName = 'DetailBreadcrumb';
diff --git a/src/features/Settings/skill/features/LeftPanel.tsx b/src/features/Settings/skill/features/LeftPanel.tsx
index 64ea9f70fe6..6ad8c28a3b6 100644
--- a/src/features/Settings/skill/features/LeftPanel.tsx
+++ b/src/features/Settings/skill/features/LeftPanel.tsx
@@ -1,9 +1,10 @@
'use client';
-import { Button, DropdownMenu, Flexbox, Icon, SearchBar, Text, Tooltip } from '@lobehub/ui';
+import type { ConnectorVisibility } from '@lobechat/types';
+import { Button, DropdownMenu, Flexbox, Icon, SearchBar, Tabs, Text, Tooltip } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
-import { ChevronDown, Grid2x2Plus, Import, Plus, Store } from 'lucide-react';
+import { ChevronDown, Grid2x2Plus, Import, LockIcon, Plus, Store, UsersIcon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -39,6 +40,7 @@ const styles = stylex.create({
},
},
body: { overflowY: 'auto', flex: '1', paddingBlock: '4px', paddingInline: '8px' },
+ columnTabs: { paddingInline: '8px' },
pageBody: { paddingBlockStart: '0', paddingBlockEnd: '24px', paddingInline: '0' },
// Title and one line of what connectors do on the left; search and the page
// actions on the right, the primary Add last.
@@ -54,6 +56,7 @@ const styles = stylex.create({
paddingInline: '12px',
},
pageSearch: { width: '240px' },
+ pageTabs: { paddingInline: '12px' },
pageTitle: {
marginBlock: 0,
fontSize: cssVar.fontSizeHeading3,
@@ -91,14 +94,29 @@ interface LeftPanelProps {
fullWidth?: boolean;
onDeleteSelected: () => void;
onSelect: (identifier: string, type: ToolDetailType) => void;
+ onVisibilityChange?: (visibility: ConnectorVisibility) => void;
/** Render as the page-level list a row opens a second-level detail from. */
page?: boolean;
selectedIdentifier?: string;
viewMode: SkillViewMode;
+ /**
+ * Workspace connectors only: the active tab — the shared pool (`public`) or
+ * the caller's private connectors. Unset outside a workspace (no tabs).
+ */
+ visibility?: ConnectorVisibility;
}
const LeftPanel = memo<LeftPanelProps>(
- ({ fullWidth, onDeleteSelected, onSelect, page, selectedIdentifier, viewMode }) => {
+ ({
+ fullWidth,
+ onDeleteSelected,
+ onSelect,
+ onVisibilityChange,
+ page,
+ selectedIdentifier,
+ viewMode,
+ visibility,
+ }) => {
const { t } = useTranslation(['setting', 'tool']);
const interfaceDensity = useInterfaceDensity();
const [showAddConnector, setShowAddConnector] = useState(false);
@@ -107,8 +125,36 @@ const LeftPanel = memo<LeftPanelProps>(
const isConnectorView = viewMode === 'connector';
const handleOpenStore = isConnectorView ? createSkillStoreModal : createMarketSkillStoreModal;
const { allowed: canCreate } = usePermission('create_content');
- // Adding a workspace connector follows the same member policy as editing one.
- const { canManage: canAddConnector, isPending: isPolicyPending } = useConnectorManageable();
+ const isPrivateTab = isConnectorView && visibility === 'private';
+ // Adding a shared workspace connector follows the same member policy as
+ // editing one; a private connector is the caller's own and skips it.
+ const { canManage: canManageShared, isPending: isSharedPolicyPending } =
+ useConnectorManageable();
+ const canAddConnector = isPrivateTab || canManageShared;
+ const isPolicyPending = !isPrivateTab && isSharedPolicyPending;
+ const visibilityTabs = isConnectorView && visibility && (
+ <Tabs
+ activeKey={visibility}
+ items={[
+ {
+ icon: <Icon icon={UsersIcon} />,
+ key: 'public',
+ label: t('skillView.connectorTabs.workspace'),
+ },
+ {
+ icon: <Icon icon={LockIcon} />,
+ key: 'private',
+ label: t('skillView.connectorTabs.private'),
+ },
+ ]}
+ onChange={(key) => onVisibilityChange?.(key as ConnectorVisibility)}
+ />
+ );
+ const connectorsDesc = isPrivateTab
+ ? t('skillView.privateConnectorsDesc')
+ : visibility
+ ? t('skillView.workspaceConnectorsDesc')
+ : t('skillView.connectorsDesc');
const addConnectorTitle = t('connector.add.title', {
defaultValue: 'Add Custom Connector',
ns: 'tool',
@@ -130,15 +176,22 @@ const LeftPanel = memo<LeftPanelProps>(
},
]
: []),
- {
- desc: t(
- isConnectorView ? 'connectorMarket.add.browseStoreDesc' : 'skillView.browseStoreDesc',
- ),
- icon: <Icon icon={Store} />,
- key: 'store',
- label: t('connectorMarket.add.browseStore'),
- onClick: handleOpenStore,
- },
+ // A store install joins the shared pool, so the private tab omits it
+ ...(isPrivateTab
+ ? []
+ : [
+ {
+ desc: t(
+ isConnectorView
+ ? 'connectorMarket.add.browseStoreDesc'
+ : 'skillView.browseStoreDesc',
+ ),
+ icon: <Icon icon={Store} />,
+ key: 'store',
+ label: t('connectorMarket.add.browseStore'),
+ onClick: handleOpenStore,
+ },
+ ]),
...(!isConnectorView
? [
{
@@ -164,7 +217,7 @@ const LeftPanel = memo<LeftPanelProps>(
{t(isConnectorView ? 'skillView.connectors' : 'skillView.skills')}
</h1>
<Text type={'secondary'}>
- {t(isConnectorView ? 'skillView.connectorsDesc' : 'skillView.skillsDesc')}
+ {isConnectorView ? connectorsDesc : t('skillView.skillsDesc')}
</Text>
</Flexbox>
<Flexbox horizontal align={'center'} flex={'none'} gap={8}>
@@ -189,7 +242,9 @@ const LeftPanel = memo<LeftPanelProps>(
</DropdownMenu>
</Flexbox>
</div>
- {isConnectorView && <ConnectorManagePolicy variant={'page'} />}
+ {visibilityTabs && <div {...stylex.props(styles.pageTabs)}>{visibilityTabs}</div>}
+ {/* The member policy governs the shared pool only */}
+ {isConnectorView && !isPrivateTab && <ConnectorManagePolicy variant={'page'} />}
</>
);
@@ -200,6 +255,7 @@ const LeftPanel = memo<LeftPanelProps>(
keyword={keyword}
renderHeader={renderHeader}
viewMode={viewMode}
+ visibility={visibility}
onClearKeyword={() => setKeyword('')}
onDeleteSelected={onDeleteSelected}
onSelect={onSelect}
@@ -207,6 +263,7 @@ const LeftPanel = memo<LeftPanelProps>(
</div>
<CustomConnectorModal
open={showAddConnector}
+ visibility={visibility}
onClose={() => setShowAddConnector(false)}
/>
</SkillListVariantProvider>
@@ -258,27 +315,35 @@ const LeftPanel = memo<LeftPanelProps>(
onClick={openSkillImportModal}
/>
)}
- <Button
- aria-label={t('skillStore.title')}
- icon={<Icon icon={Store} />}
- size="small"
- onClick={handleOpenStore}
- />
+ {!isPrivateTab && (
+ <Button
+ aria-label={t('skillStore.title')}
+ icon={<Icon icon={Store} />}
+ size="small"
+ onClick={handleOpenStore}
+ />
+ )}
</div>
</div>
- {isConnectorView && <ConnectorManagePolicy />}
+ {visibilityTabs && <div {...stylex.props(styles.columnTabs)}>{visibilityTabs}</div>}
+ {isConnectorView && !isPrivateTab && <ConnectorManagePolicy />}
<div {...stylex.props(styles.body)}>
<SkillList
selectedIdentifier={selectedIdentifier}
viewMode={viewMode}
+ visibility={visibility}
onDeleteSelected={onDeleteSelected}
onSelect={onSelect}
/>
</div>
</div>
- <CustomConnectorModal open={showAddConnector} onClose={() => setShowAddConnector(false)} />
+ <CustomConnectorModal
+ open={showAddConnector}
+ visibility={visibility}
+ onClose={() => setShowAddConnector(false)}
+ />
</NavPanelDensityContext>
);
},
diff --git a/src/features/Settings/skill/features/SkillDetail/index.tsx b/src/features/Settings/skill/features/SkillDetail/index.tsx
index 269b31399c4..906c316be35 100644
--- a/src/features/Settings/skill/features/SkillDetail/index.tsx
+++ b/src/features/Settings/skill/features/SkillDetail/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { getLobehubSkillProviderById } from '@lobechat/const';
-import { agentDisplayName } from '@lobechat/types';
+import { agentDisplayName, type ConnectorVisibility } from '@lobechat/types';
import { Avatar, Button, confirmModal, Markdown, Skeleton, toast, Tooltip } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
@@ -78,6 +78,8 @@ interface SkillDetailProps {
identifier: string;
onDelete?: () => void;
type: ToolDetailType;
+ /** The workspace connector tab the row was opened from. */
+ visibility?: ConnectorVisibility;
}
/**
@@ -167,7 +169,7 @@ LobehubConnectorAction.displayName = 'LobehubConnectorAction';
* - 'builtin-skill': renders BuiltinSkill description panel (Artifacts, Task, etc.)
* - 'builtin'/'plugin'/'mcp-connector': syncs connector entry, renders permission editor
*/
-const SkillDetail = memo<SkillDetailProps>(({ identifier, type, onDelete }) => {
+const SkillDetail = memo<SkillDetailProps>(({ identifier, type, onDelete, visibility }) => {
const { t } = useTranslation('plugin');
const { t: ts } = useTranslation('setting');
@@ -185,7 +187,7 @@ const SkillDetail = memo<SkillDetailProps>(({ identifier, type, onDelete }) => {
const installBuiltinTool = useToolStore((s) => s.installBuiltinTool);
const uninstallBuiltinTool = useToolStore((s) => s.uninstallBuiltinTool);
const deleteAgentSkill = useToolStore((s) => s.deleteAgentSkill);
- const connector = useToolStore(connectorSelectors.connectorByIdentifier(identifier));
+ const connector = useToolStore(connectorSelectors.connectorByIdentifier(identifier, visibility));
// For agent connectors the `identifier` slot carries the connector id; resolve
// the row from the agent-bound pool to show its owning-agent usage block.
const agentBoundConnector = useToolStore((s) =>
diff --git a/src/features/Settings/skill/features/SkillList.tsx b/src/features/Settings/skill/features/SkillList.tsx
index 27b27cfbd64..658a9311373 100644
--- a/src/features/Settings/skill/features/SkillList.tsx
+++ b/src/features/Settings/skill/features/SkillList.tsx
@@ -1,17 +1,19 @@
'use client';
+import type { ConnectorVisibility } from '@lobechat/types';
import { Button, Center, Empty } from '@lobehub/ui';
import { SkillsIcon } from '@lobehub/ui/icons';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import { media } from '@lobehub/ui/stylex/media.stylex';
import * as stylex from '@stylexjs/stylex';
import isEqual from 'fast-deep-equal';
-import { ChevronDownIcon, ChevronRightIcon, SearchX } from 'lucide-react';
+import { ChevronDownIcon, ChevronRightIcon, LockIcon, SearchX } from 'lucide-react';
import type React from 'react';
import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncError from '@/components/AsyncError';
+import { SkeletonList } from '@/components/Skeleton/NavPanel/List';
import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useToolStore } from '@/store/tool';
@@ -23,7 +25,12 @@ import {
pluginSelectors,
} from '@/store/tool/selectors';
import { ComposioServerStatus } from '@/store/tool/slices/composioStore';
-import { connectorSelectors } from '@/store/tool/slices/connector';
+import {
+ connectorSelectors,
+ isInConnectorTab,
+ isIntegrationInConnectorTab,
+} from '@/store/tool/slices/connector';
+import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';
import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore/types';
import { type LobeToolType } from '@/types/tool/tool';
@@ -43,6 +50,7 @@ import {
} from './connectorSections';
import LobehubSkillItem from './LobehubSkillItem';
import McpSkillItem from './McpSkillItem';
+import { privateTabState } from './privateTabState';
import type { ToolDetailType } from './SkillDetail';
import { useSkillListVariant } from './SkillListRow';
@@ -101,6 +109,12 @@ interface SkillListProps {
renderHeader?: () => React.ReactNode;
selectedIdentifier?: string;
viewMode?: SkillViewMode;
+ /**
+ * Workspace connector tab: `public` lists the shared pool (every catalog
+ * section); `private` lists only the caller's private connectors. Unset
+ * outside a workspace.
+ */
+ visibility?: ConnectorVisibility;
}
const SkillList = memo<SkillListProps>(
@@ -112,6 +126,7 @@ const SkillList = memo<SkillListProps>(
renderHeader,
selectedIdentifier,
viewMode = 'connector',
+ visibility,
}) => {
const { t } = useTranslation('setting');
const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
@@ -126,14 +141,27 @@ const SkillList = memo<SkillListProps>(
const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);
const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);
const builtinSkills = useToolStore((s) => s.builtinSkills, isEqual);
- const customConnectors = useToolStore(connectorSelectors.customConnectors, isEqual);
- const marketplaceConnectors = useToolStore(
+ const allCustomConnectors = useToolStore(connectorSelectors.customConnectors, isEqual);
+ const allMarketplaceConnectors = useToolStore(
connectorSelectors.marketplaceMcpConnectors,
isEqual,
);
const isConnectorsInit = useToolStore((s) => s.isConnectorsInit);
const fetchConnectors = useToolStore((s) => s.fetchConnectors);
- const agentBoundConnectors = useToolStore(connectorSelectors.agentBoundConnectors, isEqual);
+ // The Private tab reads only this list: keep its load's failure for Retry
+ const connectorsSWR = useToolStore((s) => s.useFetchConnectors)(true);
+ const allAgentBoundConnectors = useToolStore(connectorSelectors.agentBoundConnectors, isEqual);
+ // What an OAuth integration's tab is decided by: its rows' visibility, and
+ // which of them holds the account its actions act on
+ const connectorTabRows = useToolStore(
+ (s) =>
+ connectorSelectors.connectorList(s).map(({ identifier, metadata, visibility }) => ({
+ identifier,
+ metadata: metadata?.composio ? { composio: metadata.composio } : null,
+ visibility,
+ })),
+ isEqual,
+ );
const isAgentBoundInit = useToolStore((s) => s.isAgentBoundInit);
const fetchAgentBoundConnectors = useToolStore((s) => s.fetchAgentBoundConnectors);
const allBuiltinTools = useToolStore((s) => s.builtinTools, isEqual);
@@ -211,14 +239,41 @@ const SkillList = memo<SkillListProps>(
// Integrations (built-in skills / tools and the OAuth catalog, connected
// first), then installed plugins split into community and custom MCPs.
// A few dozen entries: cheap enough to derive on each render.
- const integrations = buildIntegrationItems({
+ const allIntegrations = buildIntegrationItems({
...connectionState,
allBuiltinTools,
builtinSkills,
connectorAvailability: { composio: isComposioEnabled, lobehub: isLobehubSkillEnabled },
});
- const communityMCPs = installedPluginList.filter((plugin) => plugin.type === 'plugin');
- const customMCPs = installedPluginList.filter((plugin) => plugin.type === 'customPlugin');
+
+ // Each workspace tab lists its own pool. Built-in tools, plugins and agent
+ // connectors carry no visibility and stay with the shared pool; a connector
+ // row lists under the tab of its visibility, and an OAuth integration
+ // (Composio, LobeHub) under the tabs of its connector rows.
+ const isPrivateTab = isConnectorView && visibility === 'private';
+ const inTab = (c: ConnectorWithTools) => isInConnectorTab(c, visibility);
+ const customConnectors = allCustomConnectors.filter(inTab);
+ const marketplaceConnectors = allMarketplaceConnectors.filter(inTab);
+ const tabVisibility = isConnectorView ? visibility : undefined;
+ const integrations = allIntegrations.filter((item) => {
+ if (item.type === 'composio')
+ return isIntegrationInConnectorTab(
+ item.serverType.identifier,
+ connectorTabRows,
+ tabVisibility,
+ getComposioServerByIdentifier(item.serverType.identifier)?.connectedAccountId,
+ );
+ if (item.type === 'lobehub')
+ return isIntegrationInConnectorTab(item.provider.id, connectorTabRows, tabVisibility);
+ return !isPrivateTab;
+ });
+ const communityMCPs = isPrivateTab
+ ? []
+ : installedPluginList.filter((plugin) => plugin.type === 'plugin');
+ const customMCPs = isPrivateTab
+ ? []
+ : installedPluginList.filter((plugin) => plugin.type === 'customPlugin');
+ const agentBoundConnectors = isPrivateTab ? [] : allAgentBoundConnectors;
const hasAnySkills =
viewMode === 'skill'
@@ -234,6 +289,49 @@ const SkillList = memo<SkillListProps>(
const header = isPage ? renderHeader?.() : undefined;
+ const privateState = isPrivateTab
+ ? privateTabState({
+ count: customConnectors.length + marketplaceConnectors.length + integrations.length,
+ error: connectorsSWR.error,
+ isConnectorsInit,
+ })
+ : undefined;
+ if (privateState === 'loading')
+ return (
+ <>
+ {header}
+ <SkeletonList aria-busy paddingBlock={12} rows={4} />
+ </>
+ );
+ if (privateState === 'error') {
+ return (
+ <>
+ {header}
+ <Center className={stylex.props(styles.container).className} paddingBlock={48}>
+ <AsyncError
+ error={connectorsSWR.error}
+ variant={'block'}
+ onRetry={() => void connectorsSWR.mutate()}
+ />
+ </Center>
+ </>
+ );
+ }
+ if (privateState === 'empty') {
+ return (
+ <>
+ {header}
+ <Center className={stylex.props(styles.container).className} paddingBlock={48}>
+ <Empty
+ description={t('skillView.privateConnectorsEmpty.desc')}
+ icon={LockIcon}
+ title={t('skillView.privateConnectorsEmpty.title')}
+ />
+ </Center>
+ </>
+ );
+ }
+
// A failed fetch must read as a failure with Retry, never as the "no skills"
// empty (error gated ahead of empty).
if (skillsError && !hasAnySkills) {
diff --git a/src/features/Settings/skill/features/privateTabState.test.ts b/src/features/Settings/skill/features/privateTabState.test.ts
new file mode 100644
index 00000000000..b6f132b4d74
--- /dev/null
+++ b/src/features/Settings/skill/features/privateTabState.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+
+import { privateTabState } from './privateTabState';
+
+describe('privateTabState', () => {
+ it('is loading, not empty, before the connector list has loaded', () => {
+ // Regression: a cold visit painted "no private connectors" before the
+ // list request had even started.
+ expect(privateTabState({ count: 0, isConnectorsInit: false })).toBe('loading');
+ });
+
+ it('shows the failure of a list that could not load', () => {
+ expect(
+ privateTabState({ count: 0, error: new Error('offline'), isConnectorsInit: false }),
+ ).toBe('error');
+ });
+
+ it('is empty only for a loaded list without private rows', () => {
+ expect(privateTabState({ count: 0, isConnectorsInit: true })).toBe('empty');
+ // A later refresh failing does not unread a loaded list
+ expect(privateTabState({ count: 0, error: new Error('x'), isConnectorsInit: true })).toBe(
+ 'empty',
+ );
+ });
+
+ it('lists rows it already has', () => {
+ expect(privateTabState({ count: 2, isConnectorsInit: false })).toBe('list');
+ expect(privateTabState({ count: 2, isConnectorsInit: true })).toBe('list');
+ });
+});
diff --git a/src/features/Settings/skill/features/privateTabState.ts b/src/features/Settings/skill/features/privateTabState.ts
new file mode 100644
index 00000000000..70990c7063a
--- /dev/null
+++ b/src/features/Settings/skill/features/privateTabState.ts
@@ -0,0 +1,23 @@
+/**
+ * What the workspace connector page's Private tab shows. Its rows only exist
+ * once the connector list has loaded, so before that the tab is loading, or
+ * shows the load's failure: never "no private connectors" for a list it has
+ * not read.
+ */
+export type PrivateTabState = 'empty' | 'error' | 'list' | 'loading';
+
+export const privateTabState = ({
+ count,
+ error,
+ isConnectorsInit,
+}: {
+ /** Rows the tab lists: private connectors and private OAuth integrations. */
+ count: number;
+ /** The connector list load's failure, if it failed. */
+ error?: unknown;
+ isConnectorsInit: boolean;
+}): PrivateTabState => {
+ if (count > 0) return 'list';
+ if (!isConnectorsInit) return error ? 'error' : 'loading';
+ return 'empty';
+};
diff --git a/src/features/Settings/skill/features/useToolDisplayName.ts b/src/features/Settings/skill/features/useToolDisplayName.ts
index 1a08f963f5f..00a546d3eef 100644
--- a/src/features/Settings/skill/features/useToolDisplayName.ts
+++ b/src/features/Settings/skill/features/useToolDisplayName.ts
@@ -1,4 +1,5 @@
import { getComposioAppByIdentifier, getLobehubSkillProviderById } from '@lobechat/const';
+import type { ConnectorVisibility } from '@lobechat/types';
import { useTranslation } from 'react-i18next';
import { useToolStore } from '@/store/tool';
@@ -12,7 +13,11 @@ import type { ToolDetailType } from './SkillDetail';
* breadcrumb reads `Connectors › <the row you clicked>`. Falls back to the
* identifier while the entry is still loading.
*/
-export const useToolDisplayName = (identifier: string, type: ToolDetailType): string => {
+export const useToolDisplayName = (
+ identifier: string,
+ type: ToolDetailType,
+ visibility?: ConnectorVisibility,
+): string => {
const { t } = useTranslation('setting');
const builtinTitle = useToolStore((s) =>
@@ -29,7 +34,7 @@ export const useToolDisplayName = (identifier: string, type: ToolDetailType): st
const connectorName = useToolStore((s) =>
type === 'agent-connector'
? (s.agentBoundConnectors ?? []).find((c) => c.id === identifier)?.name
- : connectorSelectors.connectorByIdentifier(identifier)(s)?.name,
+ : connectorSelectors.connectorByIdentifier(identifier, visibility)(s)?.name,
);
const pluginTitle = useToolStore((s) =>
type === 'plugin' ? pluginSelectors.getPluginMetaById(identifier)(s)?.title : undefined,
diff --git a/src/features/Settings/skill/index.tsx b/src/features/Settings/skill/index.tsx
index d4cbf09d184..9b06b9b5742 100644
--- a/src/features/Settings/skill/index.tsx
+++ b/src/features/Settings/skill/index.tsx
@@ -1,5 +1,6 @@
'use client';
+import type { ConnectorVisibility } from '@lobechat/types';
import { ActionIcon, Flexbox } from '@lobehub/ui';
import * as stylex from '@stylexjs/stylex';
import isEqual from 'fast-deep-equal';
@@ -8,6 +9,7 @@ import { Activity, memo, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate, useSearchParams } from 'react-router';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import NavHeader from '@/features/NavHeader';
import { useToolStore } from '@/store/tool';
import { agentSkillsSelectors } from '@/store/tool/selectors';
@@ -74,6 +76,27 @@ export const ToolSettings = memo<ToolSettingsProps>(({ viewMode }) => {
const [searchParams, setSearchParams] = useSearchParams();
const querySkillIdentifier = searchParams.get('skill');
const stackedSelected = parseMobileSelection(searchParams.get(MOBILE_SELECTION_PARAM));
+ // Workspace connectors sit behind two tabs, as devices do: the shared pool
+ // every member and agent uses, and the caller's private connectors, which
+ // only their private agents load. The tab lives in `?visibility=`, so a
+ // detail opened from it returns to it and names that tab's row.
+ const workspaceId = useActiveWorkspaceId();
+ const visibility: ConnectorVisibility | undefined =
+ viewMode === 'connector' && workspaceId
+ ? searchParams.get('visibility') === 'private'
+ ? 'private'
+ : 'public'
+ : undefined;
+ const changeVisibility = (next: ConnectorVisibility) =>
+ setSearchParams(
+ (prev) => {
+ const params = new URLSearchParams(prev);
+ if (next === 'private') params.set('visibility', next);
+ else params.delete('visibility');
+ return params;
+ },
+ { replace: true },
+ );
// Stacked: opening a detail is a history entry, so back returns to the list.
const openStackedDetail = useCallback(
@@ -135,8 +158,10 @@ export const ToolSettings = memo<ToolSettingsProps>(({ viewMode }) => {
fullWidth
page={!mobile || viewMode === 'skill'}
viewMode={viewMode}
+ visibility={visibility}
onDeleteSelected={closeStackedDetail}
onSelect={handleSelect}
+ onVisibilityChange={changeVisibility}
/>
</Activity>
);
@@ -155,6 +180,7 @@ export const ToolSettings = memo<ToolSettingsProps>(({ viewMode }) => {
<SkillDetail
identifier={stackedSelected.identifier}
type={stackedSelected.type}
+ visibility={visibility}
onDelete={closeStackedDetail}
/>
</Flexbox>
@@ -181,6 +207,7 @@ export const ToolSettings = memo<ToolSettingsProps>(({ viewMode }) => {
<DetailBreadcrumb
identifier={stackedSelected.identifier}
type={stackedSelected.type}
+ visibility={visibility}
listLabel={t(viewMode === 'skill' ? 'skillView.skills' : 'skillView.connectors', {
ns: 'setting',
})}
@@ -190,6 +217,7 @@ export const ToolSettings = memo<ToolSettingsProps>(({ viewMode }) => {
<SkillDetail
identifier={stackedSelected.identifier}
type={stackedSelected.type}
+ visibility={visibility}
onDelete={closeStackedDetail}
/>
</Flexbox>
diff --git a/src/helpers/toolEngineering/buildClientConnectorManifests.ts b/src/helpers/toolEngineering/buildClientConnectorManifests.ts
index e5e11cc55de..35f389b5439 100644
--- a/src/helpers/toolEngineering/buildClientConnectorManifests.ts
+++ b/src/helpers/toolEngineering/buildClientConnectorManifests.ts
@@ -1,5 +1,5 @@
import { buildConnectorManifest } from '@lobechat/mecha';
-import { type ToolManifest } from '@lobechat/types';
+import { connectorToolIdentifier, type ToolManifest } from '@lobechat/types';
import { getServerConfigStoreState, serverConfigSelectors } from '@/store/serverConfig';
import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';
@@ -10,16 +10,25 @@ import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';
* the client has no token; connector tool calls are executed server-side via
* `connector.callTool`, which decrypts the stored credentials. The permission
* mapping is the shared rule in `@lobechat/mecha`.
+ *
+ * Each row is its own tool set under its tool prefix (the server's
+ * `toolIdentifier`, else `connectorToolIdentifier`): a private row beside the
+ * shared one of its connector is offered under its own name.
*/
-export const buildClientConnectorManifests = (connectors: ConnectorWithTools[]): ToolManifest[] =>
- connectors
+export const buildClientConnectorManifests = (connectors: ConnectorWithTools[]): ToolManifest[] => {
+ // Named as the server names them: no own row reads as a listed identifier
+ const reserved = new Set(connectors.map((connector) => connector.identifier));
+ return connectors
.map((connector) =>
buildConnectorManifest(
{
+ id: connector.id,
identifier: connector.identifier,
isEnabled: connector.isEnabled,
name: connector.name,
links: connector.links,
+ toolIdentifier:
+ connector.toolIdentifier ?? connectorToolIdentifier(connector, undefined, reserved),
tools: connector.tools ?? [],
},
!!getServerConfigStoreState() &&
@@ -28,3 +37,4 @@ export const buildClientConnectorManifests = (connectors: ConnectorWithTools[]):
)
.filter((manifest): manifest is NonNullable<typeof manifest> => !!manifest)
.map((manifest) => manifest as ToolManifest);
+};
diff --git a/src/helpers/toolEngineering/index.runConnectors.test.ts b/src/helpers/toolEngineering/index.runConnectors.test.ts
new file mode 100644
index 00000000000..84f4326914c
--- /dev/null
+++ b/src/helpers/toolEngineering/index.runConnectors.test.ts
@@ -0,0 +1,119 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { createToolsEngine } from './index';
+
+/**
+ * Client-run chats build their connector tool sets from the rows the server
+ * listed for the conversation (`connector.listForRun`), each under its own
+ * tool prefix: only the server knows a private agent's own topic, and only it
+ * holds the owner's personal rows.
+ */
+let mockConnectors: any[] = [];
+let mockRunConnectors: any[] | undefined;
+let mockComposioServers: any[] = [];
+
+vi.mock('@/services/runConnectors', () => ({
+ getRunConnectors: () => mockRunConnectors,
+}));
+vi.mock('@/store/tool', () => ({
+ getToolStoreState: () => ({
+ agentConnectors: {},
+ builtinSkills: [],
+ builtinTools: [],
+ composioServers: mockComposioServers,
+ connectors: mockConnectors,
+ installedPlugins: [],
+ lobehubSkillServers: [],
+ }),
+}));
+vi.mock('@/store/serverConfig', () => ({ getServerConfigStoreState: () => undefined }));
+vi.mock('../isCanUseFC', () => ({ isCanUseFC: () => true }));
+
+describe("the conversation's server-listed connector rows", () => {
+ const row = (id: string, toolIdentifier: string, toolName: string, extra = {}) => ({
+ credentials: null,
+ id,
+ identifier: 'github',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example/github',
+ metadata: null,
+ name: 'GitHub',
+ sourceType: 'custom',
+ status: 'connected',
+ toolIdentifier,
+ tools: [
+ {
+ id: `${id}-tool`,
+ inputSchema: { properties: {}, type: 'object' },
+ permission: 'auto',
+ toolName,
+ userConnectorId: id,
+ },
+ ],
+ ...extra,
+ });
+ const toolNames = () =>
+ createToolsEngine({ agentId: 'agt-private', topicId: 'tpc-own' })
+ .generateToolsDetailed({ model: 'gpt-4', provider: 'openai', toolIds: ['github'] })
+ .tools?.map((tool) => tool.function.name)
+ .filter((name) => name.startsWith('github'));
+
+ afterEach(() => {
+ mockRunConnectors = undefined;
+ });
+
+ it("offers a private agent its owner's personal connector, which no workspace list holds", () => {
+ // Regression: client-run chats built connector tools from the workspace
+ // list alone, so the owner's personal connector — which the server runs
+ // in the private agent's own topic — was never offered to the model.
+ mockConnectors = [row('c-shared', 'github', 'list_issues')];
+ mockRunConnectors = [
+ row('c-shared', 'github', 'list_issues'),
+ row('c-personal', 'github-cpersona', 'create_issue', { workspaceId: null }),
+ ];
+
+ expect(toolNames()).toEqual([
+ 'github____list_issues____mcp',
+ 'github-cpersona____create_issue____mcp',
+ ]);
+ });
+
+ it('offers only what the server listed: a link-shared topic keeps private rows out', () => {
+ mockConnectors = [
+ row('c-shared', 'github', 'list_issues'),
+ row('c-mine', 'github-cmine', 'create_issue', { visibility: 'private' }),
+ ];
+ mockRunConnectors = [row('c-shared', 'github', 'list_issues')];
+
+ expect(toolNames()).toEqual(['github____list_issues____mcp']);
+ });
+
+ it('offers no Composio app whose only connection the conversation may not use', () => {
+ // Regression: a shared Composio connection switched to private kept its
+ // projection, so a workspace agent's client-run chat offered tools whose
+ // every call the server refuses.
+ const gmail = {
+ id: 'c-gmail',
+ identifier: 'gmail',
+ metadata: { composio: { connectedAccountId: 'ca-1' } },
+ visibility: 'private',
+ };
+ mockConnectors = [gmail];
+ mockComposioServers = [
+ { identifier: 'gmail', label: 'Gmail', status: 'active', tools: [{ name: 'GMAIL_SEND' }] },
+ ];
+ const gmailTools = () =>
+ createToolsEngine({ agentId: 'agt', topicId: 'tpc' })
+ .generateToolsDetailed({ model: 'gpt-4', provider: 'openai', toolIds: ['gmail'] })
+ .tools?.filter((tool) => tool.function.name.startsWith('gmail')).length ?? 0;
+
+ mockRunConnectors = [];
+ expect(gmailTools()).toBe(0);
+ // The owner's private agent's own conversation lists the connection
+ mockRunConnectors = [gmail];
+ expect(gmailTools()).toBeGreaterThan(0);
+ mockComposioServers = [];
+ mockConnectors = [];
+ });
+});
diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.ts
index b5e94af0c0e..efbe0197019 100644
--- a/src/helpers/toolEngineering/index.test.ts
+++ b/src/helpers/toolEngineering/index.test.ts
@@ -25,9 +25,13 @@ vi.mock(import('@/store/tool/slices/builtin/projection'), async (importOriginal)
}));
// Mock the store and helper dependencies
+let mockConnectors: any[] = [];
+// No conversation listing here: the local lists stand in (see index.runConnectors.test.ts)
+vi.mock('@/services/runConnectors', () => ({ getRunConnectors: () => undefined }));
+
vi.mock('@/store/tool', () => ({
getToolStoreState: () => ({
- connectors: [],
+ connectors: mockConnectors,
// The rows behind `installedPluginManifestList`: an installed plugin is a
// connector, so the agent's on/off switch applies to it.
get installedPlugins() {
@@ -215,6 +219,8 @@ vi.mock('@/store/serverConfig', () => ({
featureFlags: mockFeatureFlags,
serverConfig: mockServerConfig,
}),
+ // Connector manifests ask whether MCP Apps are on (`buildClientConnectorManifests`)
+ serverConfigSelectors: { enableMcpApps: () => false },
}));
let mockIsCanUseFC = true;
@@ -239,6 +245,8 @@ vi.mock('@/store/agent', () => ({
getAgentStoreState: () => ({}),
}));
+let mockCurrentAgentVisibility: 'private' | 'public' | undefined;
+
vi.mock('@/store/agent/selectors', () => ({
agentSelectors: {
currentAgentConfig: () => ({
@@ -250,6 +258,7 @@ vi.mock('@/store/agent/selectors', () => ({
}),
currentAgentDisabledPlugins: () => mockCurrentAgentDisabledPlugins,
currentAgentPlugins: () => mockCurrentAgentPlugins,
+ currentAgentVisibility: () => mockCurrentAgentVisibility,
hasEnabledKnowledgeBases: () => false,
},
agentChatConfigSelectors: {
@@ -303,6 +312,8 @@ describe('toolEngineering', () => {
mockImageOutputSupport = false;
mockServerConfig = {};
mockFeatureFlags = {};
+ mockConnectors = [];
+ mockCurrentAgentVisibility = undefined;
});
describe('feature-flagged tools', () => {
@@ -867,6 +878,135 @@ describe('toolEngineering', () => {
});
});
+ describe('private (私人) workspace connectors', () => {
+ const connector = (identifier: string, visibility: 'private' | 'public') => ({
+ credentials: null,
+ id: `${identifier}-id`,
+ identifier,
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: `https://${identifier}.example.com/mcp`,
+ metadata: null,
+ name: identifier,
+ sourceType: 'custom',
+ status: 'connected',
+ tools: [
+ {
+ crudType: 'read',
+ description: 'Search',
+ displayName: 'Search',
+ id: `${identifier}-search`,
+ inputSchema: { properties: {}, type: 'object' },
+ permission: 'auto',
+ toolName: 'search',
+ userConnectorId: `${identifier}-id`,
+ },
+ ],
+ visibility,
+ });
+
+ const enabledConnectorIds = (manifestContext?: { isSubAgent?: boolean; scope?: string }) => {
+ mockConnectors = [connector('ws-linear', 'public'), connector('my-notion', 'private')];
+ mockCurrentAgentPlugins = ['ws-linear', 'my-notion'];
+ return (
+ createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' }, undefined, manifestContext)
+ // A connector that is on reaches the model through the activator
+ .generateToolsDetailed({
+ context: { isExplicitActivation: true },
+ model: 'gpt-4',
+ provider: 'openai',
+ toolIds: ['ws-linear', 'my-notion'],
+ })
+ .enabledToolIds.filter((id) => id.startsWith('ws-linear') || id.startsWith('my-notion'))
+ .sort()
+ );
+ };
+
+ it('keeps them away from a workspace agent', () => {
+ mockCurrentAgentVisibility = 'public';
+
+ expect(enabledConnectorIds()).toEqual(['ws-linear']);
+ });
+
+ it("offers them in a private agent's own conversation", () => {
+ mockCurrentAgentVisibility = 'private';
+
+ // A private row is a tool set of its own, under its row-suffixed prefix
+ expect(enabledConnectorIds({ scope: 'main' })).toEqual(['my-notion-mynotion', 'ws-linear']);
+ });
+
+ it.each([
+ { scope: 'group' },
+ { scope: 'group_agent' },
+ { isSubAgent: true, scope: 'sub_agent' },
+ ])('keeps them out of a private agent run in %o', (manifestContext) => {
+ mockCurrentAgentVisibility = 'private';
+
+ expect(enabledConnectorIds(manifestContext)).toEqual(['ws-linear']);
+ });
+
+ describe('a private and a shared row of one identifier', () => {
+ // The owner's private connection and the workspace's shared one of the
+ // same identifier, each with its own tool list
+ const withTool = (visibility: 'private' | 'public', toolName: string) => {
+ const row = connector('team-docs', visibility);
+ return {
+ ...row,
+ id: `team-docs-${visibility}`,
+ tools: [{ ...row.tools[0], id: `${visibility}-tool`, toolName }],
+ };
+ };
+ const privateRow = withTool('private', 'search_mine');
+ const sharedRow = withTool('public', 'search_team');
+
+ const toolNames = (rows: unknown[], manifestContext?: { scope?: string }) => {
+ mockConnectors = rows;
+ mockCurrentAgentPlugins = ['team-docs'];
+ return createAgentToolsEngine(
+ { model: 'gpt-4', provider: 'openai' },
+ undefined,
+ manifestContext,
+ )
+ .generateToolsDetailed({
+ context: { isExplicitActivation: true },
+ model: 'gpt-4',
+ provider: 'openai',
+ toolIds: ['team-docs'],
+ })
+ .tools?.map((tool) => tool.function.name);
+ };
+
+ it('offers the private agent both rows, each under its own prefix, in either list order', () => {
+ // Regression: both rows reached the identifier-keyed manifest map and
+ // the last one won, so the model could get one row's schema while the
+ // server ran the other. Each row is now its own tool set.
+ mockCurrentAgentVisibility = 'private';
+
+ for (const rows of [
+ [privateRow, sharedRow],
+ [sharedRow, privateRow],
+ ]) {
+ expect(
+ toolNames(rows, { scope: 'main' })?.filter((name) => name.includes('search')),
+ ).toEqual(
+ expect.arrayContaining([
+ 'team-docs____search_team____mcp',
+ 'team-docs-teamdocs____search_mine____mcp',
+ ]),
+ );
+ }
+ });
+
+ it("builds a workspace agent's manifest from the shared row", () => {
+ mockCurrentAgentVisibility = 'public';
+
+ const names = toolNames([privateRow, sharedRow]);
+ expect(names?.some((name) => name.includes('search_team'))).toBe(true);
+ expect(names?.some((name) => name.includes('search_mine'))).toBe(false);
+ });
+ });
+ });
+
describe('connector discovery', () => {
const connectorManifest = {
api: [
diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.ts
index 133c53dba8f..c6a0b202754 100644
--- a/src/helpers/toolEngineering/index.ts
+++ b/src/helpers/toolEngineering/index.ts
@@ -30,6 +30,7 @@ import {
import { applyToolNameMaxLength } from '@/helpers/applyToolNameMaxLength';
import { isToolAvailableInCurrentEnv } from '@/helpers/toolAvailability';
+import { getRunConnectors } from '@/services/runConnectors';
import { getAgentStoreState } from '@/store/agent';
import {
agentChatConfigSelectors,
@@ -45,7 +46,12 @@ import {
pluginSelectors,
} from '@/store/tool/selectors';
import { runtimeUninstalledBuiltinTools } from '@/store/tool/slices/builtin/projection';
-import { connectorSelectors } from '@/store/tool/slices/connector';
+import {
+ composioIdsOutsideRun,
+ connectorSelectors,
+ pickRunConnectors,
+ pickRunToolSets,
+} from '@/store/tool/slices/connector';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
@@ -64,6 +70,11 @@ import {
export interface ToolsEngineConfig {
/** Additional manifests to include beyond the standard ones */
additionalManifests?: ToolManifest[];
+ /**
+ * The agent the run belongs to: a connector mounted on it outranks a free one
+ * of the same identifier, and one mounted on another agent is left out, as
+ * the server resolves them.
+ */
agentId?: string;
/** Default tool IDs that will always be added to the end of the tools list */
defaultToolIds?: string[];
@@ -77,6 +88,12 @@ export interface ToolsEngineConfig {
disabledPluginIds?: string[];
/** Custom enable checker for plugins */
enableChecker?: PluginEnableChecker;
+ /**
+ * Offer the caller's private (私人) workspace connectors. Only a private
+ * agent's own conversation may load them — the server applies the same rule
+ * when it resolves the call — so every other caller leaves them out.
+ */
+ includePrivateConnectors?: boolean;
/**
* Runtime context for context-aware builtin manifests. When provided, each
* builtin tool with a `resolveManifest` produces its manifest for this context
@@ -84,6 +101,11 @@ export interface ToolsEngineConfig {
* (e.g. UI token estimation) — they get the full static manifests.
*/
manifestContext?: BuiltinToolResolveContext;
+ /**
+ * The conversation's topic: with `agentId`, the connector rows the server
+ * listed for it (`connector.listForRun`) are the run's tool sets.
+ */
+ topicId?: string;
}
/**
@@ -93,8 +115,11 @@ export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine =
const {
enableChecker,
additionalManifests = [],
+ agentId,
+ topicId,
defaultToolIds,
disabledPluginIds = [],
+ includePrivateConnectors = false,
manifestContext,
} = config;
@@ -105,13 +130,53 @@ export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine =
const toolStoreState = getToolStoreState();
+ // The row each identifier runs on for tools another path executes (plugins,
+ // Composio, LobeHub skills), whose permissions are keyed by identifier.
+ const runConnectors = pickRunConnectors(connectorSelectors.connectorList(toolStoreState), {
+ agentId,
+ includePrivate: includePrivateConnectors,
+ });
+
+ // The connector tool sets: one per row the run may use, each under its own
+ // tool prefix. The conversation's server listing decides which rows those
+ // are — only it can tell whether this conversation may run the caller's own
+ // connections, and only it holds their personal ones; without a listing the
+ // local list stands in, split per row the way the server splits it.
+ // An agent-owned connection stands alone for its identifier, as the server's
+ // `pickConnectorToolSets` keeps a row bound to the agent.
+ const agentOwned = agentId
+ ? (toolStoreState.agentConnectors?.[agentId] ?? []).filter((c) => c.agentId === agentId)
+ : [];
+ const ownedIds = new Set(agentOwned.map((c) => c.identifier));
+ const listed = agentId ? getRunConnectors({ agentId, topicId }) : undefined;
+ const connectorToolSets = connectorSelectors
+ .executableMcpConnectors({
+ connectors:
+ listed ??
+ pickRunToolSets(
+ [
+ ...agentOwned,
+ ...(toolStoreState.connectors ?? []).filter((c) => !ownedIds.has(c.identifier)),
+ ],
+ { agentId, includePrivate: includePrivateConnectors },
+ ),
+ installedPlugins: toolStoreState.installedPlugins,
+ })
+ .filter((c) => c.isEnabled && c.status === 'connected');
+
+ // A Composio app whose only connections this run may not use offers no tools
+ const composioOutsideRun = composioIdsOutsideRun(
+ connectorSelectors.connectorList(toolStoreState),
+ { agentId, includePrivate: includePrivateConnectors, listed },
+ );
+
// Per-connector tool permissions, keyed by connector identifier: community-
// MCP plugins execute outside the connector path, so the user's
// needs_approval / disabled settings are patched onto their manifests.
const connectorPermissions = new Map(
- connectorSelectors
- .connectorList(toolStoreState)
- .map((c) => [c.identifier, new Map(c.tools.map((t) => [t.toolName, t.permission]))] as const),
+ runConnectors.map(
+ (c) => [c.identifier, new Map(c.tools.map((t) => [t.toolName, t.permission]))] as const,
+ ),
);
// The pool rules (connector precedence, permission patching, context-aware
@@ -123,12 +188,9 @@ export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine =
builtinTools: toolStoreState.builtinTools,
composio: composioStoreSelectors
.composioAsLobeTools(toolStoreState)
+ .filter((tool) => !composioOutsideRun.has(tool.identifier))
.map((tool) => tool.manifest as LobeToolManifest),
- connectors: buildClientConnectorManifests(
- config.agentId
- ? connectorSelectors.connectedMcpConnectorsForAgent(toolStoreState, config.agentId)
- : connectorSelectors.executableMcpConnectors(toolStoreState),
- ) as LobeToolManifest[],
+ connectors: buildClientConnectorManifests(connectorToolSets) as LobeToolManifest[],
installedPlugins: pluginSelectors.installedPluginManifestList(
toolStoreState,
) as LobeToolManifest[],
@@ -159,6 +221,9 @@ export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine =
});
};
+/** Conversation scopes whose transcript other members can read. */
+const PRIVATE_CONNECTOR_EXCLUDED_SCOPES = new Set(['group', 'group_agent', 'sub_agent']);
+
export const createAgentToolsEngine = (
workingModel: WorkingModel,
/** Runtime-resolved plugin IDs (from agentConfigResolver), may include tools beyond the active agent */
@@ -171,6 +236,8 @@ export const createAgentToolsEngine = (
* `readAttachment` so the preview can be paged, as the server's tool discovery does.
*/
hasOversizedFiles?: boolean;
+ /** The conversation's topic: its server-listed connector rows are the run's tool sets. */
+ topicId?: string;
uninstalledBuiltinTools?: string[];
/** Resolved for the executing agent, which can differ from the agent open in the UI. */
runAgent?: {
@@ -256,9 +323,16 @@ export const createAgentToolsEngine = (
});
return createToolsEngine({
- agentId: targetAgentId,
+ agentId: targetAgentId || undefined,
+ topicId: options.topicId,
defaultToolIds: resolved.defaultToolIds,
disabledPluginIds: [...resolved.excludedIdentifiers],
+ // A private agent's own conversation only: a group or sub-agent run writes
+ // into a conversation other members can read.
+ includePrivateConnectors:
+ agentSelectors.currentAgentVisibility(agentState) === 'private' &&
+ !manifestContext?.isSubAgent &&
+ !PRIVATE_CONNECTOR_EXCLUDED_SCOPES.has(manifestContext?.scope ?? ''),
manifestContext,
enableChecker: createEnableChecker({
allowExplicitActivation: resolved.allowExplicitActivation,
diff --git a/src/hooks/useConnectorManagePolicy.test.ts b/src/hooks/useConnectorManagePolicy.test.ts
index 181baa36fa7..b3a078dac70 100644
--- a/src/hooks/useConnectorManagePolicy.test.ts
+++ b/src/hooks/useConnectorManagePolicy.test.ts
@@ -22,8 +22,11 @@ vi.mock('@/hooks/useResourceManageable', () => {
};
});
-const manageable = (connector?: { agentId?: string | null; userId?: string | null }) =>
- renderHook(() => useConnectorManageable(connector)).result.current;
+const manageable = (connector?: {
+ agentId?: string | null;
+ userId?: string | null;
+ visibility?: string;
+}) => renderHook(() => useConnectorManageable(connector)).result.current;
describe('useConnectorManageable', () => {
beforeEach(() => {
@@ -81,6 +84,22 @@ describe('useConnectorManageable', () => {
expect(manageable({ agentId: 'a1', userId: 'me' })).toMatchObject({ canManage: true });
expect(manageable({ agentId: 'a1', userId: 'arvin' })).toMatchObject({ canManage: false });
});
+
+ it('lets the creator maintain their private connector when the policy restricts members', () => {
+ // Regression: under admins_only a member could add a private connector but
+ // then neither edit nor remove it, though the server lets its creator.
+ mocks.policy = { canEditPolicy: false, canManage: false, memberManage: 'admins_only' };
+
+ expect(manageable({ userId: 'me', visibility: 'private' })).toEqual({
+ canManage: true,
+ canManageCredentials: true,
+ isPending: false,
+ restrictedByPolicy: false,
+ });
+ expect(manageable({ userId: 'arvin', visibility: 'private' })).toMatchObject({
+ canManage: false,
+ });
+ });
});
describe('useConnectorManageableChecker', () => {
diff --git a/src/hooks/useConnectorManagePolicy.ts b/src/hooks/useConnectorManagePolicy.ts
index 1e5496f324c..54e6ff550b8 100644
--- a/src/hooks/useConnectorManagePolicy.ts
+++ b/src/hooks/useConnectorManagePolicy.ts
@@ -35,6 +35,7 @@ export interface ConnectorManageable {
interface ConnectorManageRow {
agentId?: string | null;
userId?: string | null;
+ visibility?: string | null;
}
const resolveConnectorManageable = (
@@ -43,8 +44,10 @@ const resolveConnectorManageable = (
policyError: unknown,
isCreatorOrOwner: boolean,
): ConnectorManageable => {
- // Agent-scoped rows belong to that agent's setup and keep the creator rule.
- if (connector?.agentId)
+ // Agent-scoped rows belong to that agent's setup, and a private row is its
+ // creator's own: both keep the creator rule and skip the member policy, as
+ // the server's `assertConnectorMaintainable` does.
+ if (connector?.agentId || connector?.visibility === 'private')
return {
canManage: isCreatorOrOwner,
canManageCredentials: isCreatorOrOwner,
diff --git a/src/libs/mcp/buildConnectorManifests.ts b/src/libs/mcp/buildConnectorManifests.ts
index af2d112b308..0fbdb41efe1 100644
--- a/src/libs/mcp/buildConnectorManifests.ts
+++ b/src/libs/mcp/buildConnectorManifests.ts
@@ -17,7 +17,12 @@ import type { UserConnectorToolItem } from '@/database/schemas';
* is `humanIntervention: 'always'` unless disabled: auto-run cannot skip it.
*/
export function buildConnectorManifests(
- connectors: DecryptedConnector[],
+ /**
+ * Rows from `ConnectorModel.resolveToolSets` carry their tool prefix
+ * (`toolIdentifier`): each becomes its own manifest under it. Rows without
+ * one are keyed by their identifier.
+ */
+ connectors: (DecryptedConnector & { toolIdentifier?: string })[],
tools: UserConnectorToolItem[],
mcpApps = false,
): ToolManifest[] {
@@ -35,10 +40,12 @@ export function buildConnectorManifests(
// adds the endpoint and credentials the runtime needs to call it.
const manifest = buildConnectorManifest(
{
+ id: connector.id,
identifier: connector.identifier,
isEnabled: connector.isEnabled,
name: connector.name,
links: connector.links,
+ toolIdentifier: connector.toolIdentifier,
tools: toolsByConnector.get(connector.id) ?? [],
},
mcpApps,
diff --git a/src/libs/mcp/connectorPermissionCheck.ts b/src/libs/mcp/connectorPermissionCheck.ts
index 7aa2f288816..368816024d3 100644
--- a/src/libs/mcp/connectorPermissionCheck.ts
+++ b/src/libs/mcp/connectorPermissionCheck.ts
@@ -1,6 +1,8 @@
+import { hasCallableMcpEndpoint } from '@lobechat/const';
import type { LobeChatDatabase } from '@lobechat/database';
+import { connectorIdentifierCandidates } from '@lobechat/types';
-import { ConnectorModel } from '@/database/models/connector';
+import { ConnectorModel, type ConnectorRunTarget } from '@/database/models/connector';
import { ConnectorToolModel } from '@/database/models/connectorTool';
import type { ConnectorToolPermission } from '@/database/schemas';
@@ -12,11 +14,14 @@ export { patchManifestWithPermissions } from './patchManifestPermissions';
*
* @param db - Server DB instance
* @param userId - Authenticated user ID
- * @param identifier - Connector identifier (e.g. 'gmail', 'vercel')
+ * @param identifier - The tool's identifier: an MCP connector row's tool prefix
+ * (`connectorToolIdentifier`, e.g. 'vercel' or a private row's
+ * 'vercel-3f9a1c2e'), or a connector identifier (e.g. 'gmail')
* @param toolName - Tool API name (e.g. 'gmail_search_emails', 'deploy')
* @param workspaceId - Workspace scope (omit for personal mode)
- * @param agentId - Agent scope: prefer the agent-owned connector row for this
- * identifier (Agent > Workspace/Personal), matching runtime resolution.
+ * @param target - The run's agent and topic, so the gate resolves the same
+ * row the run's manifests were built from (agent-owned rows, and a private
+ * agent's own private connectors in its own topic).
*
* Returns the stored permission, or null if no connector/tool entry exists.
*/
@@ -26,14 +31,20 @@ export async function getConnectorToolPermission(
identifier: string,
toolName: string,
workspaceId?: string,
- agentId?: string,
+ target: ConnectorRunTarget = {},
): Promise<ConnectorToolPermission | null> {
try {
const connectorModel = new ConnectorModel(db, userId, workspaceId);
- const [connector] = await connectorModel.resolveByIdentifiers([identifier], agentId);
+ // An MCP connector's tool runs on the row its prefix names; every other
+ // tool (Composio, LobeHub skills, plugins) on the identifier's top row
+ const toolSet = (
+ await connectorModel.resolveToolSets(target, connectorIdentifierCandidates(identifier))
+ ).find((row) => row.toolIdentifier === identifier && hasCallableMcpEndpoint(row));
+ const connector =
+ toolSet ?? (await connectorModel.resolveByIdentifiers([identifier], target))[0];
if (!connector) return null;
- const toolModel = new ConnectorToolModel(db, userId, workspaceId);
+ const toolModel = new ConnectorToolModel(db, userId, workspaceId, { agentRun: true });
const tools = await toolModel.queryByConnector(connector.id);
return (
(tools.find((t) => t.toolName === toolName)?.permission as ConnectorToolPermission) ?? null
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 99027b3edeb..1fbb5e9d4c7 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -437,12 +437,14 @@ export const mcpAppKeys = {
onThisDevice = false,
server,
toolArguments,
+ topicId,
}: {
agentId?: string;
linkId?: string;
onThisDevice?: boolean;
server?: string;
toolArguments?: string;
+ topicId?: string;
},
) => [
'mcpApp:resource',
@@ -453,6 +455,7 @@ export const mcpAppKeys = {
server ?? null,
toolArguments ?? null,
linkId ?? null,
+ topicId ?? null,
],
),
};
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index 9219468c10f..ad97ceb659e 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -15,6 +15,7 @@ import { type ContextSnapshot, gatherContextFacts, runContextEngineering } from
import { historySummaryPrompt } from '@lobechat/prompts';
import {
agentIdentityLabel,
+ manifestBaseIdentifier,
type OpenAIChatMessage,
type RuntimeAdditionalContextFragment,
type RuntimeInitialContext,
@@ -250,8 +251,15 @@ export const contextEngineering = async ({
// engine dropped their manifests, so listing them would only invite an
// activation that cannot succeed.
const disabledIdSet = new Set(disabledPluginIds ?? []);
+ // The run's discovery pool is scoped to the conversation already; a
+ // connector row's tool set is disabled with its connector
const availableTools = Object.values(discoveryManifests ?? {})
- .filter(({ identifier }) => !enabledToolSet.has(identifier) && !disabledIdSet.has(identifier))
+ .filter(
+ (manifest) =>
+ !enabledToolSet.has(manifest.identifier) &&
+ !disabledIdSet.has(manifest.identifier) &&
+ !disabledIdSet.has(manifestBaseIdentifier(manifest)),
+ )
.map(({ identifier, meta }) => ({
description: meta?.description ?? '',
identifier,
diff --git a/src/services/connectorRun.test.ts b/src/services/connectorRun.test.ts
new file mode 100644
index 00000000000..fe779439712
--- /dev/null
+++ b/src/services/connectorRun.test.ts
@@ -0,0 +1,119 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { resolveRunConnector } from './connectorRun';
+
+/**
+ * Which row a conversation's connector call runs on. In a workspace a private
+ * agent's own topic may run its owner's personal connector, which none of the
+ * client's workspace lists hold, so only the server can name it.
+ */
+const { resolveForRun, state } = vi.hoisted(() => ({
+ resolveForRun: vi.fn(),
+ state: {
+ toolStore: { agentConnectors: {}, connectors: [] as unknown[] },
+ workspaceId: null as string | null,
+ },
+}));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => state.workspaceId,
+}));
+vi.mock('@/store/tool/store', () => ({ getToolStoreState: () => state.toolStore }));
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: { connector: { resolveForRun: { query: resolveForRun } } },
+}));
+// The conversation's send-time listing, holding the personal row as it was
+const listed = vi.hoisted(() => ({ rows: [] as unknown[] }));
+vi.mock('@/services/runConnectors', () => ({ getRunConnectors: () => listed.rows }));
+
+const sharedHttp = {
+ agentId: null,
+ id: 'conn-shared',
+ identifier: 'files',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example.com/mcp',
+ metadata: null,
+ tools: [{ permission: 'auto', toolName: 'read_file' }],
+ visibility: 'public',
+};
+const personalStdio = {
+ id: 'conn-personal',
+ identifier: 'files',
+ isEnabled: true,
+ mcpConnectionType: 'stdio',
+ mcpServerUrl: null,
+ tools: [{ permission: 'auto', toolName: 'read_file' }],
+};
+const run = { agentId: 'agt_private', topicId: 'tpc_own' };
+
+describe('resolveRunConnector', () => {
+ beforeEach(() => {
+ resolveForRun.mockReset();
+ state.toolStore.connectors = [];
+ state.workspaceId = 'ws-1';
+ });
+
+ it.each([
+ { connectors: [], lists: 'no row' },
+ { connectors: [sharedHttp], lists: 'only the shared row' },
+ ])(
+ "returns the owner's personal connector the server runs when the lists hold $lists",
+ async ({ connectors }) => {
+ // Regression: both picks agreed (on no row, or on the shared one), so the
+ // server was never asked. A desktop then sent the personal stdio call to
+ // the server, which cannot run a stdio connector.
+ state.toolStore.connectors = connectors;
+ resolveForRun.mockResolvedValue(personalStdio);
+
+ await expect(resolveRunConnector('files', run)).resolves.toEqual(personalStdio);
+ expect(resolveForRun).toHaveBeenCalledWith({ ...run, identifier: 'files' });
+ },
+ );
+
+ it("keeps the lists' copy of a row they hold", async () => {
+ state.toolStore.connectors = [sharedHttp];
+ resolveForRun.mockResolvedValue({ ...sharedHttp, tools: [] });
+
+ await expect(resolveRunConnector('files', run)).resolves.toBe(sharedHttp);
+ });
+
+ it('resolves nothing when the server runs no row', async () => {
+ state.toolStore.connectors = [sharedHttp];
+ resolveForRun.mockResolvedValue(null);
+
+ await expect(resolveRunConnector('files', run)).resolves.toBeUndefined();
+ });
+
+ it('trusts agreeing picks outside a workspace, where nothing is private', async () => {
+ state.workspaceId = null;
+ state.toolStore.connectors = [sharedHttp];
+
+ await expect(resolveRunConnector('files', run)).resolves.toBe(sharedHttp);
+ expect(resolveForRun).not.toHaveBeenCalled();
+ });
+
+ it('never asks the server without a conversation', async () => {
+ state.toolStore.connectors = [sharedHttp];
+
+ await expect(resolveRunConnector('files', { agentId: 'agt_private' })).resolves.toBe(
+ sharedHttp,
+ );
+ expect(resolveForRun).not.toHaveBeenCalled();
+ });
+
+ it("reads the row's current permissions, not the send-time listing's", async () => {
+ // Regression: a listed row was returned as listed, so a tool changed to
+ // needs_approval after the send still ran from an open view unapproved.
+ listed.rows = [{ ...personalStdio, toolIdentifier: 'files-connpers' }];
+ resolveForRun.mockResolvedValue({
+ ...personalStdio,
+ tools: [{ permission: 'needs_approval', toolName: 'read_file' }],
+ });
+
+ const resolved = await resolveRunConnector('files-connpers', run);
+
+ expect(resolveForRun).toHaveBeenCalledWith({ ...run, identifier: 'files-connpers' });
+ expect(resolved?.tools).toEqual([{ permission: 'needs_approval', toolName: 'read_file' }]);
+ });
+});
diff --git a/src/services/connectorRun.ts b/src/services/connectorRun.ts
new file mode 100644
index 00000000000..70ebaea34fc
--- /dev/null
+++ b/src/services/connectorRun.ts
@@ -0,0 +1,78 @@
+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';
+
+/** What routing a call and judging its approval read of the row it runs on. */
+export type RunConnector = Pick<
+ ConnectorWithTools,
+ | 'agentId'
+ | 'id'
+ | 'identifier'
+ | 'isEnabled'
+ | 'links'
+ | 'mcpConnectionType'
+ | 'mcpServerUrl'
+ | 'metadata'
+ | 'sourceType'
+ | 'status'
+ | 'toolIdentifier'
+ | 'tools'
+>;
+
+/**
+ * The connector a conversation's call of `identifier` runs on: the row the
+ * server's `callTool` resolves. A view's call is approved against it and
+ * routed by its transport, so both follow the row that executes.
+ *
+ * The client ranks its lists as the server does
+ * (`connectorByIdentifierForAgent`) except for what only the server can tell:
+ * whether this conversation may use the caller's own connections — a private
+ * agent's own direct topic, not a group, channel, share or another agent's
+ * topic. There the server may pick the caller's private row over a shared one,
+ * or their personal connector (`workspace_id IS NULL`), which no workspace
+ * list here holds. So in a workspace the server names the row
+ * (`connector.resolveForRun`) and its answer carries the transport and tools
+ * of a row these lists lack. Outside a workspace nothing is private or carried
+ * over, so agreeing picks are the server's answer. Without both an agent and a
+ * topic the server never resolves the caller's own rows, so neither does this.
+ *
+ * Never answered from the conversation's send-time listing
+ * (`connector.listForRun`): a view's call is approved against the row's tool
+ * permissions, which may have changed since, and the server only refuses a
+ * disabled tool, so a stale `auto` would skip an approval now required.
+ *
+ * Undefined when the server resolves no row.
+ */
+export const resolveRunConnector = async (
+ /** The tool's identifier: its connector row's tool prefix. */
+ identifier: string,
+ { agentId, topicId }: { agentId?: string; topicId?: string } = {},
+): Promise<RunConnector | undefined> => {
+ // Lazy, as in `mcpService`: the tool store imports the services that use this
+ const [{ getToolStoreState }, { connectorSelectors }] = await Promise.all([
+ import('@/store/tool/store'),
+ import('@/store/tool/slices/connector/selectors'),
+ ]);
+ const s = getToolStoreState();
+ const pick = (includePrivate: boolean) =>
+ connectorSelectors.connectorByIdentifierForAgent(identifier, agentId, { includePrivate })(s);
+
+ const shared = pick(false);
+ if (!agentId || !topicId) return shared;
+
+ const own = pick(true);
+ if (own?.id === shared?.id && !getActiveWorkspaceId()) return shared;
+
+ const { lambdaClient } = await import('@/libs/trpc/client');
+ const resolved = await lambdaClient.connector.resolveForRun.query({
+ agentId,
+ identifier,
+ topicId,
+ });
+ if (!resolved) return undefined;
+
+ // The lists' copy when they hold the row, as the rest of the client shows it
+ return (
+ [own, shared].find((connector) => !!connector && connector.id === resolved.id) ??
+ (resolved as RunConnector)
+ );
+};
diff --git a/src/services/mcp.boundDevice.test.ts b/src/services/mcp.boundDevice.test.ts
index 5b267603e9a..18af07f4a56 100644
--- a/src/services/mcp.boundDevice.test.ts
+++ b/src/services/mcp.boundDevice.test.ts
@@ -42,7 +42,7 @@ vi.mock('@/libs/trpc/client', () => ({
connector: {
callTool: { mutate: vi.fn() },
getDeviceMcpManifest: { mutate: vi.fn() },
- getForEdit: { query: vi.fn() },
+ getForRun: { query: vi.fn() },
getLocalCallToken: { mutate: vi.fn() },
},
},
@@ -124,7 +124,7 @@ describe('a connector bound to a device', () => {
it('runs a call here over IPC when this desktop is the bound device', async () => {
const { lambdaClient } = await import('@/libs/trpc/client');
mockGetToolStoreState.mockReturnValue({ connectors: [lanConnector('this-desktop')] });
- vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue({
+ vi.mocked(lambdaClient.connector.getForRun.query).mockResolvedValue({
...lanConnector('this-desktop'),
credentials: null,
tools: [{ permission: 'auto', toolName: 'list_files' }],
@@ -142,7 +142,7 @@ describe('a connector rebound since this client loaded it', () => {
const { lambdaClient } = await import('@/libs/trpc/client');
// The stored projection is still unbound, so the call looks local
mockGetToolStoreState.mockReturnValue({ connectors: [lanConnector()] });
- vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue({
+ vi.mocked(lambdaClient.connector.getForRun.query).mockResolvedValue({
...lanConnector('office-nas'),
credentials: null,
tools: [{ permission: 'auto', toolName: 'list_files' }],
diff --git a/src/services/mcp.callReport.test.ts b/src/services/mcp.callReport.test.ts
index 8993d27edd5..1a6bb94da79 100644
--- a/src/services/mcp.callReport.test.ts
+++ b/src/services/mcp.callReport.test.ts
@@ -36,7 +36,7 @@ vi.mock('@/store/serverConfig/store', () => ({
}));
vi.mock('@/libs/trpc/client', () => ({
lambdaClient: {
- connector: { callTool: { mutate: vi.fn() }, getForEdit: { query: vi.fn() } },
+ connector: { callTool: { mutate: vi.fn() }, getForRun: { query: vi.fn() } },
},
toolsClient: { mcp: { callTool: { mutate: vi.fn() } } },
}));
@@ -82,7 +82,7 @@ beforeEach(() => {
environment.isDesktop = true;
toolState.current = { connectors: [marketplace] };
pluginLookup.getInstalledPluginById.mockReturnValue(() => undefined);
- vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue(detail as never);
+ vi.mocked(lambdaClient.connector.getForRun.query).mockResolvedValue(detail as never);
ipc.callTool.mockResolvedValue(superjson.serialize(localResult));
});
@@ -128,7 +128,7 @@ describe('Market call reports for connector calls', () => {
sourceType: 'custom',
};
toolState.current = { connectors: [custom] };
- vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue({
+ vi.mocked(lambdaClient.connector.getForRun.query).mockResolvedValue({
...detail,
...custom,
} as never);
diff --git a/src/services/mcp.deviceRoute.test.ts b/src/services/mcp.deviceRoute.test.ts
index 205692f4a1c..61b0d6d4486 100644
--- a/src/services/mcp.deviceRoute.test.ts
+++ b/src/services/mcp.deviceRoute.test.ts
@@ -38,7 +38,7 @@ vi.mock('@/libs/trpc/client', () => ({
connector: {
callTool: { mutate: vi.fn() },
getDeviceMcpManifest: { mutate: vi.fn() },
- getForEdit: { query: vi.fn() },
+ getForRun: { query: vi.fn() },
getLocalCallToken: { mutate: vi.fn() },
},
},
@@ -240,7 +240,7 @@ describe('invokeMcpToolCall routing for HTTP servers', () => {
const { lambdaClient } = await import('@/libs/trpc/client');
environment.isDesktop = true;
useConnector({ connectVia: 'device' });
- vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue({
+ vi.mocked(lambdaClient.connector.getForRun.query).mockResolvedValue({
...connector,
metadata: { connectVia: 'device' },
tools: [{ permission: 'auto', toolName: 'list_files' }],
@@ -248,7 +248,11 @@ describe('invokeMcpToolCall routing for HTTP servers', () => {
await mcpService.invokeMcpToolCall(payload as ChatToolPayload, {});
- expect(lambdaClient.connector.getForEdit.query).toHaveBeenCalledWith({ id: 'nas-id' });
+ expect(lambdaClient.connector.getForRun.query).toHaveBeenCalledWith({
+ agentId: undefined,
+ identifier: 'nas',
+ topicId: undefined,
+ });
const sent = superjson.deserialize(mockElectronIpc.mcp.callTool.mock.calls[0][0]);
expect(sent).toMatchObject({
args: { dir: '/' },
@@ -258,12 +262,12 @@ describe('invokeMcpToolCall routing for HTTP servers', () => {
expect(lambdaClient.connector.callTool.mutate).not.toHaveBeenCalled();
});
- // `getForEdit` leaves OAuth tokens out; the call fetches the current one
+ // `getForRun` leaves OAuth tokens out; the call fetches the current one
it("sends an OAuth connector's access token with a call it runs over IPC", async () => {
const { lambdaClient } = await import('@/libs/trpc/client');
environment.isDesktop = true;
useConnector({ connectVia: 'device' });
- vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue({
+ vi.mocked(lambdaClient.connector.getForRun.query).mockResolvedValue({
...connector,
credentials: null,
metadata: { connectVia: 'device' },
@@ -279,6 +283,7 @@ describe('invokeMcpToolCall routing for HTTP servers', () => {
expect(lambdaClient.connector.getLocalCallToken.mutate).toHaveBeenCalledWith({
id: 'nas-id',
+ run: { agentId: undefined, identifier: 'nas', topicId: undefined },
});
const sent = superjson.deserialize(mockElectronIpc.mcp.callTool.mock.calls[0][0]);
expect(sent).toMatchObject({
@@ -302,7 +307,7 @@ describe('invokeMcpToolCall routing for HTTP servers', () => {
},
],
});
- vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue({
+ vi.mocked(lambdaClient.connector.getForRun.query).mockResolvedValue({
...connector,
credentials: null,
metadata: { connectVia: 'device' },
@@ -324,6 +329,7 @@ describe('invokeMcpToolCall routing for HTTP servers', () => {
expect(lambdaClient.connector.getLocalCallToken.mutate).toHaveBeenCalledWith({
id: 'nas-id',
linkId: 'lnk_b',
+ run: { agentId: undefined, identifier: 'nas', topicId: undefined },
});
const sent = superjson.deserialize(mockElectronIpc.mcp.callTool.mock.calls[0][0]);
expect(sent).toMatchObject({
@@ -367,7 +373,7 @@ describe('invokeMcpToolCall routing for HTTP servers', () => {
await mcpService.invokeMcpToolCall(payload as ChatToolPayload, {});
expect(lambdaClient.connector.callTool.mutate).toHaveBeenCalledOnce();
- expect(lambdaClient.connector.getForEdit.query).not.toHaveBeenCalled();
+ expect(lambdaClient.connector.getForRun.query).not.toHaveBeenCalled();
expect(mockElectronIpc.mcp.callTool).not.toHaveBeenCalled();
});
});
diff --git a/src/services/mcp.mcpApp.test.ts b/src/services/mcp.mcpApp.test.ts
index 1e8a56e2503..cd1d082afce 100644
--- a/src/services/mcp.mcpApp.test.ts
+++ b/src/services/mcp.mcpApp.test.ts
@@ -50,7 +50,7 @@ vi.mock('@/libs/trpc/client', () => ({
lambdaClient: {
connector: {
callTool: { mutate: connectorCall },
- getForEdit: { query: connectorEdit },
+ getForRun: { query: connectorEdit },
readUiResource: { query: connectorRead },
},
},
@@ -178,6 +178,34 @@ describe('mcpService.readMcpAppResource on desktop', () => {
expect(relayRead).toHaveBeenCalledWith(expect.objectContaining({ uri: 'ui://app' }));
});
+ it("hands the conversation's topic to the server, so a private connector's view resolves as its call did", async () => {
+ connectors.set('agt_1:remote', {
+ id: 'conn_1',
+ identifier: 'remote',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example.com/mcp',
+ visibility: 'private',
+ });
+ connectorRead.mockResolvedValue(view);
+
+ await expect(
+ mcpService.readMcpAppResource('remote', 'ui://app', {
+ agentId: 'agt_1',
+ server: REMOTE,
+ topicId: 'tpc_own',
+ }),
+ ).resolves.toEqual(view);
+
+ expect(connectorRead).toHaveBeenCalledWith({
+ agentId: 'agt_1',
+ identifier: 'remote',
+ server: REMOTE,
+ topicId: 'tpc_own',
+ uri: 'ui://app',
+ });
+ });
+
it('reads no view once only the plugin headers changed, which may route to another server', async () => {
plugins.set('remote', {
customParams: {
@@ -334,7 +362,12 @@ describe('mcpService.readMcpAppResource for stdio connectors', () => {
mcpService.readMcpAppResource('files', 'ui://app', { onThisDevice: true, server: STDIO }),
).resolves.toEqual(view);
- expect(connectorEdit).toHaveBeenCalledWith({ id: 'conn_1' });
+ // The row the server resolves for this conversation, as the tool call did
+ expect(connectorEdit).toHaveBeenCalledWith({
+ agentId: undefined,
+ identifier: 'files',
+ topicId: undefined,
+ });
expect(deserializeMcpIpcPayload(ipcRead.mock.calls[0][0])).toEqual({
env: { TOKEN: 'fresh-secret' },
params: { args: ['mcp.js'], command: 'node', name: 'files', type: 'stdio' },
diff --git a/src/services/mcp.runConnector.test.ts b/src/services/mcp.runConnector.test.ts
new file mode 100644
index 00000000000..d942907cdb9
--- /dev/null
+++ b/src/services/mcp.runConnector.test.ts
@@ -0,0 +1,287 @@
+import { type ChatToolPayload } from '@lobechat/types';
+import superjson from 'superjson';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useAgentStore } from '@/store/agent';
+
+import { mcpService } from './mcp';
+
+/**
+ * Which connector row a conversation's call runs on, and so where it runs: a
+ * private agent's own topic may use its owner's private or personal connector,
+ * a group or another agent's topic only the shared one. Only the server can
+ * tell the two apart, so the desktop routes on the row it resolves
+ * (`connector.resolveForRun`), never on the row ranked first here.
+ */
+
+const environment = vi.hoisted(() => ({
+ deviceGatewayConfigured: false as boolean | undefined,
+}));
+// In a workspace the client asks the server which row a private agent's call runs on
+const workspace = vi.hoisted(() => ({ id: null as string | null }));
+const mockElectronIpc = vi.hoisted(() => ({ mcp: { callTool: vi.fn() } }));
+const mockGetToolStoreState = vi.hoisted(() => vi.fn());
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...((await importOriginal()) as Record<string, unknown>),
+ CURRENT_VERSION: '1.0.0',
+ isDesktop: true,
+}));
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => workspace.id,
+ useActiveWorkspaceId: () => workspace.id,
+}));
+vi.mock('@/store/serverConfig/store', () => ({
+ getServerConfigStoreState: () => ({
+ featureFlags: { enableMcpApps: false },
+ serverConfig: { deviceGatewayConfigured: environment.deviceGatewayConfigured },
+ }),
+}));
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ connector: {
+ callTool: { mutate: vi.fn() },
+ getForRun: { query: vi.fn() },
+ getLocalCallToken: { mutate: vi.fn() },
+ resolveForRun: { query: vi.fn() },
+ },
+ },
+ toolsClient: { mcp: { callTool: { mutate: vi.fn() } } },
+}));
+vi.mock('@/utils/electron/ipc', () => ({ ensureElectronIpc: () => mockElectronIpc }));
+vi.mock('./discover', () => ({
+ discoverService: {
+ reportPluginCall: vi.fn().mockResolvedValue(undefined),
+ safeInjectMPToken: vi.fn().mockResolvedValue(undefined),
+ },
+}));
+vi.mock('@/store/tool/store', () => ({ getToolStoreState: () => mockGetToolStoreState() }));
+vi.mock('@/store/tool/selectors', () => ({
+ pluginSelectors: {
+ getCustomPluginById: () => () => undefined,
+ getInstalledPluginById: () => () => undefined,
+ },
+}));
+
+const payload: ChatToolPayload = {
+ id: 'local-call',
+ identifier: 'local-connector',
+ apiName: 'read_file',
+ arguments: '{"path":"test.txt"}',
+ type: 'standalone',
+};
+const connector = {
+ id: 'connector-id',
+ identifier: payload.identifier,
+ isEnabled: true,
+ mcpConnectionType: 'stdio',
+};
+const detail = {
+ ...connector,
+ mcpStdioConfig: { command: 'node', args: ['mcp.js'], env: { TOKEN: 'fresh-secret' } },
+ tools: [{ toolName: 'read_file', permission: 'auto' }],
+};
+
+describe('mcpService.invokeMcpToolCall: the connector a conversation runs on', () => {
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ environment.deviceGatewayConfigured = false;
+ workspace.id = null;
+ mockGetToolStoreState.mockReturnValue({ connectors: [connector] });
+ const { lambdaClient } = await import('@/libs/trpc/client');
+ vi.mocked(lambdaClient.connector.getForRun.query).mockResolvedValue(detail as never);
+ });
+
+ it("runs the shared row's tool on the shared row, the private one beside it", async () => {
+ // Regression: a private agent's private row was picked on the agent's
+ // visibility alone, so in a conversation the server keeps private rows
+ // out of (a group topic) the shared tool ran with the private account.
+ // The private row is now a tool set of its own: the connector's
+ // identifier names the shared row, whose configuration the server reads.
+ const { lambdaClient } = await import('@/libs/trpc/client');
+ mockGetToolStoreState.mockReturnValue({
+ connectors: [
+ { ...connector, id: 'connector-shared', visibility: 'public' },
+ { ...connector, id: 'connector-private', visibility: 'private' },
+ ],
+ });
+ vi.mocked(lambdaClient.connector.resolveForRun.query).mockResolvedValue({
+ id: 'connector-shared',
+ });
+ const shared = {
+ ...detail,
+ id: 'connector-shared',
+ mcpStdioConfig: { command: 'node', args: ['mcp.js'], env: { TOKEN: 'shared-secret' } },
+ };
+ vi.mocked(lambdaClient.connector.getForRun.query).mockResolvedValue(shared as never);
+ mockElectronIpc.mcp.callTool.mockResolvedValue(superjson.serialize({ success: true }));
+
+ await mcpService.invokeMcpToolCall(payload, {
+ agentId: 'agt_private',
+ topicId: 'tpc_group',
+ });
+
+ const run = {
+ agentId: 'agt_private',
+ identifier: payload.identifier,
+ topicId: 'tpc_group',
+ };
+ expect(lambdaClient.connector.getForRun.query).toHaveBeenCalledWith(run);
+ expect(superjson.deserialize(mockElectronIpc.mcp.callTool.mock.calls[0][0])).toMatchObject({
+ env: { TOKEN: 'shared-secret' },
+ });
+ });
+
+ it('sends the call to the server when the conversation runs a shared HTTP row', async () => {
+ // Regression: the private stdio row was ranked first and took the IPC
+ // route, then the server-resolved row turned out to be the shared HTTP
+ // one (a group topic keeps private rows out), and the stdio check threw
+ // instead of running the valid shared tool.
+ const { lambdaClient } = await import('@/libs/trpc/client');
+ // A private agent, whose private row the conversation might use
+ useAgentStore.setState({ agentMap: { agt_private: { visibility: 'private' } } } as never);
+ mockGetToolStoreState.mockReturnValue({
+ connectors: [
+ { ...connector, id: 'connector-private', visibility: 'private' },
+ {
+ ...connector,
+ id: 'connector-shared',
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example.com/mcp',
+ visibility: 'public',
+ },
+ ],
+ });
+ vi.mocked(lambdaClient.connector.resolveForRun.query).mockResolvedValue({
+ id: 'connector-shared',
+ });
+ // What the server resolves: the shared HTTP row
+ vi.mocked(lambdaClient.connector.getForRun.query).mockResolvedValue({
+ ...detail,
+ id: 'connector-shared',
+ mcpConnectionType: 'http',
+ mcpStdioConfig: null,
+ } as never);
+ const result = { content: 'shared result', success: true };
+ vi.mocked(lambdaClient.connector.callTool.mutate).mockResolvedValue(result as never);
+
+ await expect(
+ mcpService.invokeMcpToolCall(payload, { agentId: 'agt_private', topicId: 'tpc_group' }),
+ ).resolves.toEqual(result);
+ expect(lambdaClient.connector.callTool.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agt_private', topicId: 'tpc_group' }),
+ expect.anything(),
+ );
+ expect(lambdaClient.connector.getForRun.query).not.toHaveBeenCalled();
+ expect(mockElectronIpc.mcp.callTool).not.toHaveBeenCalled();
+ });
+
+ it('runs the private stdio row over IPC once the server resolves it', async () => {
+ const { lambdaClient } = await import('@/libs/trpc/client');
+ mockGetToolStoreState.mockReturnValue({
+ connectors: [
+ { ...connector, id: 'connector-private', visibility: 'private' },
+ {
+ ...connector,
+ id: 'connector-shared',
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example.com/mcp',
+ visibility: 'public',
+ },
+ ],
+ });
+ vi.mocked(lambdaClient.connector.resolveForRun.query).mockResolvedValue({
+ id: 'connector-private',
+ });
+ mockElectronIpc.mcp.callTool.mockResolvedValue(superjson.serialize({ success: true }));
+
+ // The private row's tool set, under its row-suffixed prefix
+ await mcpService.invokeMcpToolCall(
+ { ...payload, identifier: 'local-connector-connecto' },
+ { agentId: 'agt_private', topicId: 'tpc_own' },
+ );
+
+ expect(mockElectronIpc.mcp.callTool).toHaveBeenCalledTimes(1);
+ expect(lambdaClient.connector.callTool.mutate).not.toHaveBeenCalled();
+ });
+
+ it('keeps a personal marketplace stdio install the server resolves on this desktop under a gateway', async () => {
+ // A private agent's own topic in a workspace may run its owner's
+ // personal connector, which no workspace list here holds, so the
+ // client routes on the server's answer. Without the row's source in
+ // that answer, a marketplace stdio install (which runs on the desktop
+ // even with a device gateway, as its plugin did) went to the server
+ // route, which cannot run stdio.
+ environment.deviceGatewayConfigured = true;
+ workspace.id = 'ws-1';
+ mockGetToolStoreState.mockReturnValue({ connectors: [] });
+ const { lambdaClient } = await import('@/libs/trpc/client');
+ vi.mocked(lambdaClient.connector.resolveForRun.query).mockResolvedValue({
+ ...connector,
+ agentId: null,
+ id: 'connector-personal',
+ mcpServerUrl: null,
+ metadata: { marketplaceInstalled: true },
+ sourceType: 'marketplace',
+ status: 'connected',
+ tools: detail.tools,
+ } as never);
+ mockElectronIpc.mcp.callTool.mockResolvedValue(superjson.serialize({ success: true }));
+
+ await mcpService.invokeMcpToolCall(payload, { agentId: 'agt_private', topicId: 'tpc_own' });
+
+ expect(lambdaClient.connector.getForRun.query).toHaveBeenCalledWith({
+ agentId: 'agt_private',
+ identifier: payload.identifier,
+ topicId: 'tpc_own',
+ });
+ expect(mockElectronIpc.mcp.callTool).toHaveBeenCalledTimes(1);
+ expect(lambdaClient.connector.callTool.mutate).not.toHaveBeenCalled();
+ });
+
+ it("runs a personal OAuth server set to connect through the device here, with the token of the run's row", async () => {
+ // A private agent's own topic in a workspace may run its owner's personal
+ // HTTP connector, which no workspace list here holds. Its public-looking
+ // address only reaches the server as "connect via device" when the
+ // server's answer carries that choice; its OAuth token is read for the same
+ // conversation, since the workspace scope alone cannot find a personal row.
+ environment.deviceGatewayConfigured = true;
+ workspace.id = 'ws-1';
+ mockGetToolStoreState.mockReturnValue({ connectors: [] });
+ const url = 'https://nas.tail1234.ts.net/mcp';
+ const personal = {
+ ...connector,
+ agentId: null,
+ id: '9f1f6f30-0000-4000-8000-00000000000a',
+ mcpConnectionType: 'http',
+ mcpServerUrl: url,
+ metadata: { connectVia: 'device' },
+ tools: detail.tools,
+ };
+ const { lambdaClient } = await import('@/libs/trpc/client');
+ vi.mocked(lambdaClient.connector.resolveForRun.query).mockResolvedValue(personal as never);
+ vi.mocked(lambdaClient.connector.getForRun.query).mockResolvedValue({
+ ...personal,
+ credentials: null,
+ mcpStdioConfig: null,
+ oidcConfig: { clientId: 'cid', issuer: 'https://auth.example.com' },
+ } as never);
+ vi.mocked(lambdaClient.connector.getLocalCallToken.mutate).mockResolvedValue({
+ accessToken: 'personal-access',
+ type: 'oauth2',
+ });
+ mockElectronIpc.mcp.callTool.mockResolvedValue(superjson.serialize({ success: true }));
+
+ await mcpService.invokeMcpToolCall(payload, { agentId: 'agt_private', topicId: 'tpc_own' });
+
+ const run = { agentId: 'agt_private', identifier: payload.identifier, topicId: 'tpc_own' };
+ expect(lambdaClient.connector.getLocalCallToken.mutate).toHaveBeenCalledWith({
+ id: personal.id,
+ run,
+ });
+ expect(superjson.deserialize(mockElectronIpc.mcp.callTool.mock.calls[0][0])).toMatchObject({
+ http: { auth: { accessToken: 'personal-access', type: 'oauth2' }, url },
+ });
+ expect(lambdaClient.connector.callTool.mutate).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/services/mcp.test.ts b/src/services/mcp.test.ts
index 62edf10ce29..db99162ef7c 100644
--- a/src/services/mcp.test.ts
+++ b/src/services/mcp.test.ts
@@ -54,7 +54,8 @@ vi.mock('@/libs/trpc/client', () => ({
lambdaClient: {
connector: {
callTool: { mutate: vi.fn() },
- getForEdit: { query: vi.fn() },
+ getForRun: { query: vi.fn() },
+ resolveForRun: { query: vi.fn() },
},
},
toolsClient: {
@@ -274,7 +275,7 @@ describe('MCPService', () => {
environment.deviceGatewayConfigured = false;
mockGetToolStoreState.mockReturnValue({ connectors: [connector] });
const { lambdaClient } = await import('@/libs/trpc/client');
- vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue(detail as never);
+ vi.mocked(lambdaClient.connector.getForRun.query).mockResolvedValue(detail as never);
});
it('executes through local IPC with fresh configuration when no gateway is configured', async () => {
@@ -316,7 +317,7 @@ describe('MCPService', () => {
vi.mocked(lambdaClient.connector.callTool.mutate).mockResolvedValue(result as never);
await expect(mcpService.invokeMcpToolCall(payload, {})).resolves.toEqual(result);
- expect(lambdaClient.connector.getForEdit.query).not.toHaveBeenCalled();
+ expect(lambdaClient.connector.getForRun.query).not.toHaveBeenCalled();
expect(mockElectronIpc.mcp.callTool).not.toHaveBeenCalled();
},
);
@@ -347,8 +348,9 @@ describe('MCPService', () => {
mockElectronIpc.mcp.callTool.mockResolvedValue(superjson.serialize(result));
await expect(mcpService.invokeMcpToolCall(payload, {})).resolves.toEqual(result);
- expect(lambdaClient.connector.getForEdit.query).toHaveBeenCalledWith({
- id: connector.id,
+ // The row the server resolves for the call, read with its configuration
+ expect(lambdaClient.connector.getForRun.query).toHaveBeenCalledWith({
+ identifier: payload.identifier,
});
expect(lambdaClient.connector.callTool.mutate).not.toHaveBeenCalled();
},
@@ -381,7 +383,7 @@ describe('MCPService', () => {
},
])('rejects a newly disabled connector or unavailable tool before IPC', async (current) => {
const { lambdaClient } = await import('@/libs/trpc/client');
- vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue(current as never);
+ vi.mocked(lambdaClient.connector.getForRun.query).mockResolvedValue(current as never);
await expect(mcpService.invokeMcpToolCall(payload, {})).rejects.toThrow();
expect(mockElectronIpc.mcp.callTool).not.toHaveBeenCalled();
@@ -390,9 +392,7 @@ describe('MCPService', () => {
it('does not execute when the protected configuration read is denied', async () => {
const { lambdaClient } = await import('@/libs/trpc/client');
- vi.mocked(lambdaClient.connector.getForEdit.query).mockRejectedValue(
- new Error('FORBIDDEN'),
- );
+ vi.mocked(lambdaClient.connector.getForRun.query).mockRejectedValue(new Error('FORBIDDEN'));
await expect(mcpService.invokeMcpToolCall(payload, {})).rejects.toThrow('FORBIDDEN');
expect(mockElectronIpc.mcp.callTool).not.toHaveBeenCalled();
diff --git a/src/services/mcp.ts b/src/services/mcp.ts
index 0c84c770333..4393894806c 100644
--- a/src/services/mcp.ts
+++ b/src/services/mcp.ts
@@ -43,6 +43,7 @@ import { serverConfigSelectors } from '@/store/serverConfig/selectors';
import { getServerConfigStoreState } from '@/store/serverConfig/store';
import { ensureElectronIpc } from '@/utils/electron/ipc';
+import { resolveRunConnector } from './connectorRun';
import { discoverService } from './discover';
/**
@@ -287,8 +288,9 @@ class MCPService {
// for marketplace and protocol-link stdio installs, which ran here as plugins.
// Only connectors with a real MCP endpoint are routed here — Lobehub/Composio
// skills synced into the connector store have no mcpServerUrl and keep their
- // original executor path.
- const { connectorSelectors } = await import('@/store/tool/slices/connector/selectors');
+ // original executor path. The route follows the row the server resolves for
+ // this conversation: a private stdio row the conversation may not use must
+ // not send its call over IPC when the server runs a shared HTTP row.
const installPlugin = pluginSelectors.getInstalledPluginById(identifier)(s);
const customPlugin = pluginSelectors.getCustomPluginById(identifier)(s);
@@ -296,7 +298,7 @@ class MCPService {
// An unfinished marketplace install (an interrupted reinstall over a plugin
// row, a late OAuth callback after a cancel) is not routed to: its tool rows
// may not match its endpoint. A plugin row still serves the call.
- const resolved = connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(s);
+ const resolved = await resolveRunConnector(identifier, { agentId, topicId });
const connector =
resolved && isMarketplaceInstallRunnable(resolved, !!plugin) ? resolved : undefined;
@@ -332,10 +334,12 @@ class MCPService {
if (fromMcpApp && !!runsHere !== !!onThisDevice) throw new Error(VIEW_SITE_MISMATCH);
// Persisted connector projections omit env secrets and may be stale.
// This protected read retains the connector's credential ownership gate,
- // and carries the current binding: a connector rebound to another device
- // since this projection loaded runs there, through the server.
+ // runs the row the server resolves for this conversation (a private
+ // connector the conversation may not use never runs here), and carries
+ // the current binding: a connector rebound to another device since this
+ // projection loaded runs there, through the server.
const detail = runsHere
- ? await lambdaClient.connector.getForEdit.query({ id: connector.id })
+ ? await lambdaClient.connector.getForRun.query({ agentId, identifier, topicId })
: undefined;
const reboundElsewhere =
!!detail && runsOnAnotherDevice(connectorDeviceBinding(detail)?.deviceId);
@@ -351,8 +355,14 @@ class MCPService {
}
if (detail.mcpConnectionType !== 'stdio') {
const account = takeLocalConnectorAccount(connector, detail.tools, args, linkId);
+ // The token of the row this conversation runs, read in its scope: a
+ // private agent's own topic may run its owner's personal connector
const http = await resolveLocalConnectorHttpParams(detail, (id) =>
- lambdaClient.connector.getLocalCallToken.mutate({ id, linkId: account.linkId }),
+ lambdaClient.connector.getLocalCallToken.mutate({
+ id,
+ linkId: account.linkId,
+ run: { agentId, identifier, topicId },
+ }),
);
if (fromMcpApp && !(await isViewServer(server, { ...http, type: 'http' })))
throw new Error(VIEW_SERVER_MOVED);
@@ -512,7 +522,9 @@ class MCPService {
args: isDesktop && isStdio ? (safeParseJSON(args) ?? {}) : args,
env: connection?.type === 'stdio' ? params.env : (pluginSettings ?? connection?.env),
...(fromMcpApp && { fromApp: true }),
- ...(fromEntrypoint && { fromEntrypoint: true, agentId }),
+ // The conversation's agent: the server gates the tool on the row it runs
+ ...((fromMcpApp || fromEntrypoint) && agentId && { agentId }),
+ ...(fromEntrypoint && { fromEntrypoint: true }),
meta,
params,
toolName: apiName,
@@ -621,6 +633,7 @@ class MCPService {
toolArguments,
onThisDevice = false,
server,
+ topicId,
}: {
agentId?: string;
linkId?: string;
@@ -633,6 +646,13 @@ class MCPService {
*/
onThisDevice?: boolean;
server?: string;
+ /**
+ * The conversation the result belongs to. The server resolves the
+ * connector with the same run scope the tool call used, so a private
+ * agent's own conversation can read a view off its owner's private
+ * connector; without it the read resolves the shared rows only.
+ */
+ topicId?: string;
},
): Promise<ReadResourceResult | undefined> {
// A result that doesn't name its server can't be matched to one
@@ -653,8 +673,8 @@ class MCPService {
s = getToolStoreState();
}
- const { connectorSelectors } = await import('@/store/tool/slices/connector/selectors');
- const resolved = connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(s);
+ // The row the conversation's calls run on, as in `invokeMcpToolCall`
+ const resolved = await resolveRunConnector(identifier, { agentId, topicId });
// Resolve only after the agent's confirmed list loads: a cold view may
// otherwise mistake a tool's business link_id for the account selector.
if (!linkId && toolArguments && resolved) {
@@ -694,8 +714,10 @@ class MCPService {
const { lambdaClient } = await import('@/libs/trpc/client');
// Persisted connector projections omit env secrets and may be stale.
- // This protected read retains the connector's credential ownership gate.
- const detail = await lambdaClient.connector.getForEdit.query({ id: connector.id });
+ // This protected read retains the connector's credential ownership gate,
+ // and reads the row the server resolves for this conversation, as the
+ // tool call did.
+ const detail = await lambdaClient.connector.getForRun.query({ agentId, identifier, topicId });
const config = detail.mcpStdioConfig;
if (!detail.isEnabled || detail.mcpConnectionType !== 'stdio' || !config?.command) return;
if (
@@ -731,10 +753,19 @@ class MCPService {
if (onThisDevice) {
if (!isDesktop || !isMcpAppsOn()) return;
const { lambdaClient } = await import('@/libs/trpc/client');
- const detail = await lambdaClient.connector.getForEdit.query({ id: connector.id });
+ // The row the server resolves for this conversation, as the tool call read
+ const detail = await lambdaClient.connector.getForRun.query({
+ agentId,
+ identifier,
+ topicId,
+ });
if (!detail.isEnabled) return;
const http = await resolveLocalConnectorHttpParams(detail, (id) =>
- lambdaClient.connector.getLocalCallToken.mutate({ id, linkId }),
+ lambdaClient.connector.getLocalCallToken.mutate({
+ id,
+ linkId,
+ run: { agentId, identifier, topicId },
+ }),
);
if (!(await reaches({ ...http, type: 'http' }))) return;
return deserializeMcpIpcPayload(
@@ -748,6 +779,7 @@ class MCPService {
identifier,
linkId,
server,
+ topicId,
uri,
})) as ReadResourceResult;
}
diff --git a/src/services/runConnectors.test.ts b/src/services/runConnectors.test.ts
new file mode 100644
index 00000000000..cc3c5ee277f
--- /dev/null
+++ b/src/services/runConnectors.test.ts
@@ -0,0 +1,63 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ getAllRunConnectors,
+ getRunConnectors,
+ refreshRunConnectors,
+ resetRunConnectors,
+} from './runConnectors';
+
+const { listForRun, workspace } = vi.hoisted(() => ({
+ listForRun: vi.fn(),
+ workspace: { id: 'ws-1' as string | null },
+}));
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: { connector: { listForRun: { query: listForRun } } },
+}));
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => workspace.id,
+}));
+
+const target = { agentId: 'agt-private', topicId: 'tpc-own' };
+const rows = [{ id: 'c-personal', identifier: 'github', toolIdentifier: 'github-cpersona' }];
+
+beforeEach(() => {
+ resetRunConnectors();
+ listForRun.mockReset();
+ workspace.id = 'ws-1';
+});
+afterEach(() => vi.useRealTimers());
+
+describe('run connectors', () => {
+ it("lists a conversation's rows once refreshed, by agent and topic", async () => {
+ listForRun.mockResolvedValue(rows);
+
+ expect(getRunConnectors(target)).toBeUndefined();
+ expect(await refreshRunConnectors(target)).toEqual(rows);
+
+ expect(listForRun).toHaveBeenCalledWith(target);
+ expect(getRunConnectors(target)).toEqual(rows);
+ expect(getRunConnectors({ ...target, topicId: 'tpc-other' })).toBeUndefined();
+ expect(getAllRunConnectors()).toEqual(rows);
+ });
+
+ it('asks nothing outside a workspace, where the local lists hold every row', async () => {
+ workspace.id = null;
+
+ expect(await refreshRunConnectors(target)).toBeUndefined();
+ expect(listForRun).not.toHaveBeenCalled();
+ });
+
+ it('keeps the last listing when a refresh fails or takes too long', async () => {
+ listForRun.mockResolvedValueOnce(rows);
+ await refreshRunConnectors(target);
+
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ listForRun.mockRejectedValueOnce(new Error('offline'));
+ expect(await refreshRunConnectors(target)).toEqual(rows);
+
+ listForRun.mockReturnValueOnce(new Promise(() => {}));
+ expect(await refreshRunConnectors(target, { timeoutMs: 10 })).toEqual(rows);
+ });
+});
diff --git a/src/services/runConnectors.ts b/src/services/runConnectors.ts
new file mode 100644
index 00000000000..9f5e9b917f5
--- /dev/null
+++ b/src/services/runConnectors.ts
@@ -0,0 +1,85 @@
+import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';
+
+/** A conversation: the agent it runs and its topic. */
+export interface RunConnectorsTarget {
+ agentId?: string;
+ topicId?: string;
+}
+
+/** A row the server lists for a conversation's run, with its tool prefix. */
+export type RunConnectorRow = ConnectorWithTools & { toolIdentifier: string };
+
+/** How long a send waits for the list before falling back to the local one. */
+const REFRESH_TIMEOUT_MS = 3000;
+
+const cache = new Map<string, RunConnectorRow[]>();
+const inflight = new Map<string, Promise<RunConnectorRow[] | undefined>>();
+
+const keyOf = ({ agentId, topicId }: RunConnectorsTarget) => `${agentId ?? ''}|${topicId ?? ''}`;
+
+/**
+ * The connector rows the server last listed for this conversation
+ * (`connector.listForRun`), or undefined before any listing. Only the server
+ * can tell whether a conversation may run the caller's own connections — a
+ * private agent's own direct topic, not a group, channel, link-shared or
+ * another agent's one — and only it holds their personal rows; a client-run
+ * chat builds its connector tool sets from this list.
+ */
+export const getRunConnectors = (target: RunConnectorsTarget): RunConnectorRow[] | undefined =>
+ cache.get(keyOf(target));
+
+/** Every row any listed conversation runs: tool calls resolve by their prefix. */
+export const getAllRunConnectors = (): RunConnectorRow[] => [...cache.values()].flat();
+
+/**
+ * List the conversation's connector rows again before a send. Waits at most
+ * {@link REFRESH_TIMEOUT_MS}; on a timeout or failure the last listing (or
+ * nothing) stands and the caller falls back to its local lists.
+ */
+export const refreshRunConnectors = async (
+ target: RunConnectorsTarget,
+ { timeoutMs = REFRESH_TIMEOUT_MS }: { timeoutMs?: number } = {},
+): Promise<RunConnectorRow[] | undefined> => {
+ if (!target.agentId) return undefined;
+ // Outside a workspace nothing is private or carried over: the local lists
+ // hold every row a run may use, split the way the server splits them
+ const { getActiveWorkspaceId } = await import('@/business/client/hooks/useActiveWorkspaceId');
+ if (!getActiveWorkspaceId()) return undefined;
+ const key = keyOf(target);
+ let request = inflight.get(key);
+ if (!request) {
+ request = (async () => {
+ try {
+ const { lambdaClient } = await import('@/libs/trpc/client');
+ const rows = (await lambdaClient.connector.listForRun.query({
+ agentId: target.agentId,
+ topicId: target.topicId,
+ })) as unknown as RunConnectorRow[];
+ cache.set(key, rows);
+ return rows;
+ } catch (error) {
+ console.warn('[runConnectors] listing failed, using the local lists:', error);
+ return cache.get(key);
+ } finally {
+ inflight.delete(key);
+ }
+ })();
+ inflight.set(key, request);
+ }
+
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const timeout = new Promise<RunConnectorRow[] | undefined>((resolve) => {
+ timer = setTimeout(() => resolve(cache.get(key)), timeoutMs);
+ });
+ try {
+ return await Promise.race([request, timeout]);
+ } finally {
+ clearTimeout(timer);
+ }
+};
+
+/** Test helper: forget every listing. */
+export const resetRunConnectors = () => {
+ cache.clear();
+ inflight.clear();
+};
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/discoverableManifests.ts b/src/store/chat/slices/agentRun/actions/transports/client/discoverableManifests.ts
index 2d4631d8e90..c45e020f020 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/discoverableManifests.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/discoverableManifests.ts
@@ -1,6 +1,7 @@
import { AttachmentsIdentifier } from '@lobechat/builtin-tool-attachments';
import type { LobeToolManifest } from '@lobechat/context-engine';
+import type { RunConnectorsTarget } from '@/services/runConnectors';
import type { ToolStoreState } from '@/store/tool/initialState';
import { toolSelectors } from '@/store/tool/selectors/tool';
@@ -10,11 +11,13 @@ export const buildRunManifestMap = (
toolState: ToolStoreState,
eligibleManifests: ReadonlyMap<string, LobeToolManifest>,
enabledManifests: LobeToolManifest[],
+ /** The conversation: its connector rows are the ones discoverable. */
+ run: RunConnectorsTarget = {},
): Record<string, LobeToolManifest> => {
const map: Record<string, LobeToolManifest> = {};
const ids = [
- ...toolSelectors.availableToolsForDiscovery(toolState).map((t) => t.identifier),
+ ...toolSelectors.availableToolsForDiscovery(toolState, run).map((t) => t.identifier),
// Oversized attachments need a reader that is hidden from the global catalog.
AttachmentsIdentifier,
];
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
index 58fd52245c2..78f40871239 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
@@ -46,6 +46,7 @@ import { type ResolvedAgentConfig } from '@/services/chat/mecha';
import { composeEnabledTools, resolveAgentConfig } from '@/services/chat/mecha';
import { messageService } from '@/services/message';
import { hydrateProjectedConversation } from '@/services/message/hydrateProjectedTools';
+import { refreshRunConnectors } from '@/services/runConnectors';
import { workService } from '@/services/work';
import { getAgentStoreState } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
@@ -298,6 +299,7 @@ export class StreamingExecutorActionImpl {
{
hasOversizedFiles: hasPreviewableFiles(messages),
runAgent: { ...runAgent, connectors },
+ ...(topicId && { topicId }),
uninstalledBuiltinTools,
},
);
@@ -319,6 +321,8 @@ export class StreamingExecutorActionImpl {
getToolStoreState(),
toolsEngine.getAllPluginManifests(),
enabledManifests,
+ // The conversation's own connector rows are what it may discover
+ { agentId: agentId || undefined, topicId: topicId ?? undefined },
)
: Object.fromEntries(enabledManifests.map((manifest) => [manifest.identifier, manifest]));
@@ -631,6 +635,9 @@ export class StreamingExecutorActionImpl {
// without rechecking capability. Wait (bounded) for the list so a fast first
// send after reload never attaches tools to a model that can't use them.
await getAiInfraStoreState().ensureAiProviderRuntimeStateReady();
+ // The connector rows this conversation may run, as the server resolves
+ // them (bounded; the local lists stand in on a timeout or failure)
+ await refreshRunConnectors({ agentId, topicId: topicId ?? undefined });
// ===========================================
// Step 1: Create Agent State (resolves config once)
diff --git a/src/store/chat/slices/plugin/actions/exector.ts b/src/store/chat/slices/plugin/actions/exector.ts
index ca03af9a8ac..b9f7bd387ac 100644
--- a/src/store/chat/slices/plugin/actions/exector.ts
+++ b/src/store/chat/slices/plugin/actions/exector.ts
@@ -10,6 +10,8 @@ import { safeParseJSON } from '@/utils/safeParseJSON';
* Context for remote tool execution, derived from the invoking message
*/
export interface RemoteToolExecutorContext {
+ /** Agent ID from the message that triggered this tool call */
+ agentId?: string;
/** Stable tool call ID */
sourceToolCallId?: string;
/** Topic ID from the message that triggered this tool call */
@@ -39,7 +41,7 @@ const createFailedResult = (
success: false,
});
-export const composioExecutor: RemoteToolExecutor = async (p, _context) => {
+export const composioExecutor: RemoteToolExecutor = async (p, context) => {
const identifier = p.identifier;
const composioServers = useToolStore.getState().composioServers || [];
const server = composioServers.find((s) => s.identifier === identifier);
@@ -50,10 +52,14 @@ export const composioExecutor: RemoteToolExecutor = async (p, _context) => {
const args = safeParseJSON(p.arguments) || {};
+ // Name the conversation, so the server resolves the connection this agent
+ // loads there (a private agent's own topic may use its owner's private one).
const result = await useToolStore.getState().callComposioTool({
+ agentId: context?.agentId,
identifier,
toolArgs: args,
toolSlug: p.apiName,
+ topicId: context?.topicId,
});
if (!result.success) {
diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.test.ts b/src/store/chat/slices/plugin/actions/pluginTypes.test.ts
index c429c35acd6..8cd16e6e1cf 100644
--- a/src/store/chat/slices/plugin/actions/pluginTypes.test.ts
+++ b/src/store/chat/slices/plugin/actions/pluginTypes.test.ts
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { mcpService } from '@/services/mcp';
import { useChatStore } from '@/store/chat/store';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { useToolStore } from '@/store/tool';
vi.mock('@/utils/localStorage', () => {
class AsyncLocalStorage<State> {
@@ -27,6 +28,11 @@ vi.mock('@/services/message', () => ({
messageService: { updateMessageError: vi.fn(), updateToolMessage: vi.fn() },
}));
+// A result inside a topic is archived through a server call; keep it local.
+vi.mock('@/services/toolResultArchive', () => ({
+ archiveToolResultViaServer: vi.fn(async ({ content }: { content: string }) => content),
+}));
+
const messageId = 'message-id';
const payload = {
apiName: 'list',
@@ -65,3 +71,46 @@ describe('invokeMCPTypePlugin', () => {
expect(invoke).toHaveBeenCalledWith(payload, expect.objectContaining({ agentId: 'agt_1' }));
});
});
+
+describe('invokeComposioTypePlugin', () => {
+ // Regression: the client runtime ran a Composio call without naming its
+ // conversation, so the server resolved only the workspace's shared
+ // connections and a private agent's own Composio connection was unreachable.
+ it("runs the call in the message's agent and topic", async () => {
+ const callComposioTool = vi.fn().mockResolvedValue({
+ data: { content: 'ok', state: {}, success: true },
+ success: true,
+ });
+ vi.spyOn(useToolStore, 'getState').mockReturnValue({
+ callComposioTool,
+ composioServers: [{ identifier: 'gmail' }],
+ } as any);
+ const key = messageMapKey({ agentId: 'agt_private', topicId: 'tpc_direct' });
+ useChatStore.setState({
+ dbMessagesMap: {
+ [key]: [
+ { agentId: 'agt_private', id: messageId, role: 'tool', topicId: 'tpc_direct' } as any,
+ ],
+ },
+ messageOperationMap: {},
+ messagesMap: { [key]: [] },
+ operations: {},
+ optimisticUpdateToolMessage: vi.fn().mockResolvedValue(undefined),
+ replaceMessages: vi.fn(),
+ });
+
+ await useChatStore.getState().invokeComposioTypePlugin(messageId, {
+ ...payload,
+ apiName: 'GMAIL_SEND_EMAIL',
+ identifier: 'gmail',
+ });
+
+ expect(callComposioTool).toHaveBeenCalledWith({
+ agentId: 'agt_private',
+ identifier: 'gmail',
+ toolArgs: {},
+ toolSlug: 'GMAIL_SEND_EMAIL',
+ topicId: 'tpc_direct',
+ });
+ });
+});
diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.ts
index d0c6ba891ab..c3722ea5c1a 100644
--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts
+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts
@@ -422,11 +422,12 @@ export class PluginTypesActionImpl {
);
try {
- // Pass topicId from message context, not global active state
+ // Pass agentId/topicId from message context, not global active state
// This ensures tool calls use the correct topic even if user switches topics
data = await executor(payload, {
+ agentId: message?.agentId ?? undefined,
sourceToolCallId: payload.id,
- topicId: message?.topicId,
+ topicId: message?.topicId ?? undefined,
});
} catch (error) {
console.error(`[${logPrefix}] Error:`, error);
diff --git a/src/store/tool/selectors/tool.test.ts b/src/store/tool/selectors/tool.test.ts
index 67f855d96e0..0746272c1af 100644
--- a/src/store/tool/selectors/tool.test.ts
+++ b/src/store/tool/selectors/tool.test.ts
@@ -1,10 +1,17 @@
import { type ToolManifest } from '@lobechat/types';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { type ToolStoreState } from '../initialState';
import { initialState } from '../initialState';
import { toolSelectors } from './tool';
+// The conversation's server listing (`connector.listForRun`)
+const runListing = vi.hoisted(() => ({ rows: undefined as unknown[] | undefined }));
+vi.mock('@/services/runConnectors', () => ({
+ getAllRunConnectors: () => runListing.rows ?? [],
+ getRunConnectors: () => runListing.rows,
+}));
+
// Mock builtin skill for testing
const mockBuiltinSkill = {
avatar: '🧪',
@@ -270,6 +277,109 @@ describe('MCP connectors in tool discovery', () => {
expect(ids.filter((id) => id === 'plugin-1')).toHaveLength(1);
});
+ it("offers a private row's tool set in place of a same-identifier legacy plugin", () => {
+ // Regression: the plugin's bare entry hid the private row's suffixed tool
+ // set, but the run's pool replaces the plugin with that tool set, so the
+ // advertised bare name had nothing to activate.
+ const s = state([
+ marketplace('plugin-1', {
+ id: '3f9a1c2e-mine',
+ metadata: {},
+ sourceType: 'custom',
+ visibility: 'private',
+ }),
+ ]);
+ runListing.rows = [s.connectors[0]];
+ const ids = toolSelectors
+ .availableToolsForDiscovery(s, { agentId: 'agt-private', topicId: 'tpc-own' })
+ .map((tool) => tool.identifier);
+ runListing.rows = undefined;
+
+ expect(ids).toContain('plugin-1-3f9a1c2e');
+ expect(ids).not.toContain('plugin-1');
+ });
+
+ it('lists a private row beside the shared one of its connector, each under its prefix', () => {
+ // Regression: discovery matched manifests against base identifiers, so a
+ // private row's `identifier-<suffix>` tool set never matched and could not
+ // be discovered or activated.
+ const s = state([
+ marketplace('notes-mcp', { id: 'c-shared', metadata: {}, sourceType: 'custom' }),
+ marketplace('notes-mcp', {
+ id: '3f9a1c2e-mine',
+ metadata: {},
+ sourceType: 'custom',
+ visibility: 'private',
+ }),
+ ]);
+
+ const shared = s.connectors[0];
+ const mine = s.connectors[1];
+ // The conversation's server listing names the rows it may run
+ runListing.rows = [mine, shared];
+ const run = { agentId: 'agt-private', topicId: 'tpc-own' };
+
+ expect(toolSelectors.availableToolsForDiscovery(s, run).map((tool) => tool.identifier)).toEqual(
+ expect.arrayContaining(['notes-mcp', 'notes-mcp-3f9a1c2e']),
+ );
+ });
+
+ it("offers no private row a conversation's listing leaves out, nor any without a listing", () => {
+ // Regression: discovery merged every listed conversation's rows, so a
+ // public agent's chat advertised a private agent's connectors.
+ const s = state([
+ marketplace('notes-mcp', { id: 'c-shared', metadata: {}, sourceType: 'custom' }),
+ marketplace('notes-mcp', {
+ id: '3f9a1c2e-mine',
+ metadata: {},
+ sourceType: 'custom',
+ visibility: 'private',
+ }),
+ ]);
+ runListing.rows = [s.connectors[0]];
+ const ids = (run = {}) =>
+ toolSelectors.availableToolsForDiscovery(s, run).map((tool) => tool.identifier);
+
+ expect(ids({ agentId: 'agt-public', topicId: 'tpc-1' })).not.toContain('notes-mcp-3f9a1c2e');
+ runListing.rows = undefined;
+ expect(ids()).toContain('notes-mcp');
+ expect(ids()).not.toContain('notes-mcp-3f9a1c2e');
+ });
+
+ it('offers no Composio app whose only connection the conversation may not use', () => {
+ // Regression: a shared Composio connection switched to private kept its
+ // projection, so a workspace agent's chat advertised tools it cannot run.
+ const gmail = {
+ identifier: 'gmail',
+ label: 'Gmail',
+ status: 'active',
+ tools: [{ name: 'GMAIL_SEND', inputSchema: {} }],
+ };
+ const s = {
+ ...state([]),
+ composioServers: [gmail],
+ connectors: [
+ {
+ id: 'c-gmail',
+ identifier: 'gmail',
+ metadata: { composio: { connectedAccountId: 'ca-1' } },
+ visibility: 'private',
+ },
+ ],
+ } as unknown as ToolStoreState;
+ const ids = (run = {}) =>
+ toolSelectors.availableToolsForDiscovery(s, run).map((tool) => tool.identifier);
+
+ runListing.rows = [];
+ expect(ids({ agentId: 'agt-public', topicId: 'tpc-1' })).not.toContain('gmail');
+ runListing.rows = undefined;
+ expect(ids()).not.toContain('gmail');
+ // The owner's private agent's own conversation lists it
+ runListing.rows = [s.connectors[0]];
+ expect(ids({ agentId: 'agt-private', topicId: 'tpc-own' })).toContain('gmail');
+ runListing.rows = undefined;
+ });
+
it("reads a connector-only identifier's manifest from its connector", () => {
const s = state([marketplace('notes-mcp'), marketplace('plugin-1')]);
diff --git a/src/store/tool/selectors/tool.ts b/src/store/tool/selectors/tool.ts
index f3ee778114e..1f6a4543ca9 100644
--- a/src/store/tool/selectors/tool.ts
+++ b/src/store/tool/selectors/tool.ts
@@ -4,13 +4,22 @@ import {
getLobehubSkillProviderById,
isDesktop,
} from '@lobechat/const';
-import { type RenderDisplayControl, type ToolManifest } from '@lobechat/types';
+import {
+ manifestBaseIdentifier,
+ type RenderDisplayControl,
+ type ToolManifest,
+} from '@lobechat/types';
import {
isInstalledPluginAvailableInCurrentEnv,
isToolAvailableInCurrentEnv,
} from '@/helpers/toolAvailability';
import { buildClientConnectorManifests } from '@/helpers/toolEngineering/buildClientConnectorManifests';
+import {
+ getAllRunConnectors,
+ getRunConnectors,
+ type RunConnectorsTarget,
+} from '@/services/runConnectors';
import { type MetaData } from '@/types/meta';
import { type LobeToolMeta } from '@/types/tool/tool';
@@ -18,7 +27,7 @@ import { type ToolStoreState } from '../initialState';
import { agentSkillsSelectors } from '../slices/agentSkills/selectors';
import { builtinToolSelectors } from '../slices/builtin/selectors';
import { ComposioServerStatus } from '../slices/composioStore';
-import { connectorSelectors } from '../slices/connector/selectors';
+import { composioIdsOutsideRun, connectorSelectors } from '../slices/connector/selectors';
import { lobehubSkillStoreSelectors } from '../slices/lobehubSkillStore';
import { LobehubSkillStatus } from '../slices/lobehubSkillStore/types';
import { pluginSelectors } from '../slices/plugin/selectors';
@@ -62,10 +71,21 @@ const getMetaById =
/**
* The MCP connectors chat can run, as the tools engine offers them: custom
- * ones and finished marketplace installs (every MCP install lands here now).
+ * ones and finished marketplace installs (every MCP install lands here now),
+ * one manifest per row under its tool prefix. Rows the server listed for a
+ * conversation (`connector.listForRun`, a private agent's owner's personal
+ * connectors among them) join the local ones, so a call naming any row's
+ * prefix resolves.
*/
-const executableConnectorManifests = (s: ToolStoreState): ToolManifest[] =>
- buildClientConnectorManifests(connectorSelectors.executableMcpConnectors(s));
+const executableConnectorManifests = (s: ToolStoreState): ToolManifest[] => {
+ const local = connectorSelectors.executableMcpConnectors(s);
+ const known = new Set(local.map((c) => c.id));
+ const listed = connectorSelectors.executableMcpConnectors({
+ connectors: getAllRunConnectors().filter((c) => !known.has(c.id) && !!known.add(c.id)),
+ installedPlugins: s.installedPlugins,
+ });
+ return buildClientConnectorManifests([...local, ...listed]);
+};
/**
* A connector-only identifier is read from its connector; one that still has
@@ -133,6 +153,11 @@ const getRenderDisplayControl =
};
export interface AvailableToolForDiscovery {
+ /**
+ * The connector a connector row's tool set serves, when it is named apart
+ * from it (a private or personal row): agent switches speak this identifier.
+ */
+ connectorIdentifier?: string;
description: string;
identifier: string;
name: string;
@@ -150,7 +175,17 @@ export interface AvailableToolForDiscovery {
* 5. MCP connectors chat can run (custom, finished marketplace installs) that no
* entry above already lists — stdio ones only on desktop
*/
-const availableToolsForDiscovery = (s: ToolStoreState): AvailableToolForDiscovery[] => {
+const availableToolsForDiscovery = (
+ s: ToolStoreState,
+ /**
+ * The conversation the run belongs to: its connector rows are the ones the
+ * server listed for it (`connector.listForRun`). Without that listing only
+ * the caller's shared rows are discoverable — whether a conversation may run
+ * a private or personal row is the server's call, so none is offered on a
+ * guess.
+ */
+ run: RunConnectorsTarget = {},
+): AvailableToolForDiscovery[] => {
// Build exclusion sets for deduplication
const builtinSkillIds = new Set((s.builtinSkills || []).map((skill) => skill.identifier));
const agentSkillIds = new Set(
@@ -189,9 +224,16 @@ const availableToolsForDiscovery = (s: ToolStoreState): AvailableToolForDiscover
};
});
- // 3. Composio MCP servers (connected only)
+ // 3. Composio MCP servers (connected only), but none whose only connections
+ // the conversation may not use: without its listing, shared ones only
+ const composioOutsideRun = composioIdsOutsideRun(s.connectors ?? [], {
+ agentId: run.agentId,
+ includePrivate: false,
+ listed: run.agentId ? getRunConnectors(run) : undefined,
+ });
const composioItems = (s.composioServers || [])
.filter((server) => server.status === ComposioServerStatus.ACTIVE && server.tools?.length)
+ .filter((server) => !composioOutsideRun.has(server.identifier))
// A connector identifier can have legacy Composio and current LobeHub
// connections at the same time. Tool discovery is identifier-based, so the
// canonical LobeHub connection must own the single visible entry.
@@ -223,21 +265,38 @@ const availableToolsForDiscovery = (s: ToolStoreState): AvailableToolForDiscover
};
});
- // 5. MCP connectors no plugin row serves (every MCP install now), as the
- // tools engine offers them. Stdio servers run only on a desktop.
- const listed = new Set([...builtinItems, ...pluginItems].map((item) => item.identifier));
+ // 5. MCP connectors, as the tools engine offers them: a connector's tool sets
+ // replace a same-identifier plugin row (`assembleManifestPool`), so the
+ // plugin's bare entry gives way to them. Stdio servers run only on a desktop.
+ const builtinIds = new Set(builtinItems.map((item) => item.identifier));
+ // Each row is its own tool set (a private or personal row under its own
+ // prefix), so a manifest is runnable by the row it was built from, and
+ // deduplicated against the other sources by the connector it serves.
+ const listedForRun = run.agentId ? getRunConnectors(run) : undefined;
+ const runRows = listedForRun
+ ? connectorSelectors.executableMcpConnectors({
+ connectors: listedForRun,
+ installedPlugins: s.installedPlugins,
+ })
+ : connectorSelectors
+ .executableMcpConnectors(s)
+ .filter((connector) => connector.visibility !== 'private');
const runnableHere = new Set(
- connectorSelectors
- .executableMcpConnectors(s)
+ runRows
.filter((connector) => isDesktop || connector.mcpConnectionType !== 'stdio')
- .map((connector) => connector.identifier),
+ .map((connector) => connector.id),
);
- const connectorItems = executableConnectorManifests(s)
- .filter((manifest) => runnableHere.has(manifest.identifier))
- .filter((manifest) => !listed.has(manifest.identifier))
- .filter((manifest) => !composioIds.has(manifest.identifier))
- .filter((manifest) => !lobehubSkillIds.has(manifest.identifier))
+ const connectorManifests = executableConnectorManifests(s)
+ .filter((manifest) => !!manifest.connector && runnableHere.has(manifest.connector.id))
+ .filter((manifest) => !builtinIds.has(manifestBaseIdentifier(manifest)));
+ const connectorBaseIds = new Set(connectorManifests.map(manifestBaseIdentifier));
+ const connectorItems = connectorManifests
+ .filter((manifest) => !composioIds.has(manifestBaseIdentifier(manifest)))
+ .filter((manifest) => !lobehubSkillIds.has(manifestBaseIdentifier(manifest)))
.map((manifest) => ({
+ ...(manifestBaseIdentifier(manifest) !== manifest.identifier && {
+ connectorIdentifier: manifestBaseIdentifier(manifest),
+ }),
description: manifest.meta?.description || '',
identifier: manifest.identifier,
name: manifest.meta?.title || manifest.identifier,
@@ -245,7 +304,7 @@ const availableToolsForDiscovery = (s: ToolStoreState): AvailableToolForDiscover
return [
...builtinItems,
- ...pluginItems,
+ ...pluginItems.filter((item) => !connectorBaseIds.has(item.identifier)),
...composioItems,
...lobehubSkillItems,
...connectorItems,
diff --git a/src/store/tool/slices/builtin/executors/lobe-activator.ts b/src/store/tool/slices/builtin/executors/lobe-activator.ts
index 7898d5817f9..0fd72e34fa9 100644
--- a/src/store/tool/slices/builtin/executors/lobe-activator.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-activator.ts
@@ -29,13 +29,14 @@ import { clientSkillCatalog } from './clientSkillCatalog';
const createService = (discoverableIds?: string[]): ActivatorRuntimeService => ({
getActivatedToolIds: () => [],
- getToolManifests: async (identifiers: string[]): Promise<ToolManifestInfo[]> => {
+ getToolManifests: async (identifiers: string[], run): Promise<ToolManifestInfo[]> => {
const s = getToolStoreState();
// Only allow activation of tools that passed discovery filters
- // (discoverable, platform-available, not internal/hidden)
+ // (discoverable, platform-available, not internal/hidden) for the
+ // conversation the activation runs in
const discoverable = new Set(
- discoverableIds ?? toolSelectors.availableToolsForDiscovery(s).map((t) => t.identifier),
+ discoverableIds ?? toolSelectors.availableToolsForDiscovery(s, run).map((t) => t.identifier),
);
const allowedIds = identifiers.filter((id) => discoverable.has(id));
@@ -151,11 +152,12 @@ const createService = (discoverableIds?: string[]): ActivatorRuntimeService => (
// variants. Reuses `getToolManifests` on the same
// `availableToolsForDiscovery` allowlist so scoping and manifest mapping
// cannot drift between the two paths.
- async listToolManifests(): Promise<ToolManifestInfo[]> {
+ async listToolManifests(run): Promise<ToolManifestInfo[]> {
const s = getToolStoreState();
const discoveryIds =
- discoverableIds ?? toolSelectors.availableToolsForDiscovery(s).map((tool) => tool.identifier);
- return this.getToolManifests(discoveryIds);
+ discoverableIds ??
+ toolSelectors.availableToolsForDiscovery(s, run).map((tool) => tool.identifier);
+ return this.getToolManifests(discoveryIds, run);
},
markActivated: () => {},
});
diff --git a/src/store/tool/slices/composioStore/action.ts b/src/store/tool/slices/composioStore/action.ts
index a372c7c585b..e011183f7d6 100644
--- a/src/store/tool/slices/composioStore/action.ts
+++ b/src/store/tool/slices/composioStore/action.ts
@@ -150,7 +150,7 @@ export class ComposioStoreActionImpl {
}
callComposioTool = async (params: CallComposioToolParams): Promise<CallComposioToolResult> => {
- const { identifier, toolSlug, toolArgs } = params;
+ const { agentId, identifier, toolSlug, toolArgs, topicId } = params;
const toolId = `${identifier}:${toolSlug}`;
@@ -164,9 +164,11 @@ export class ComposioStoreActionImpl {
try {
const response = await toolsClient.composio.executeAction.mutate({
+ agentId,
identifier,
toolArgs,
toolSlug,
+ topicId,
});
this.#set(
@@ -203,7 +205,7 @@ export class ComposioStoreActionImpl {
createComposioConnection = async (
params: CreateComposioServerParams,
): Promise<ComposioServer | undefined> => {
- const { appSlug, identifier, label, agentId } = params;
+ const { appSlug, identifier, label, agentId, replacesConnectedAccountId } = params;
// The completion is bound to the identity that started it: the server may
// answer after the user switched scope (see the guard below).
const scope = cacheScope.get();
@@ -223,6 +225,7 @@ export class ComposioStoreActionImpl {
appSlug,
identifier,
label,
+ replacesConnectedAccountId,
});
// The user may have switched identity while the server answered. Writing
@@ -423,36 +426,20 @@ export class ComposioStoreActionImpl {
const { composioServers } = this.#get();
const existing = composioServers.find((s) => s.identifier === identifier);
if (!existing) return undefined;
- // Bound to the identity that started it, like `createComposioConnection`,
- // whose own guard only captures the scope once it starts — after the cleanup
- // below has already awaited.
- const scope = cacheScope.get();
-
- // Clean up the stale connection on Composio's side (the prior link likely
- // expired). Best-effort — if it's already gone we still mint a fresh one.
- try {
- await lambdaClient.composio.deleteConnection.mutate({
- connectedAccountId: existing.connectedAccountId,
- identifier,
- });
- } catch (error) {
- console.error('[Composio] Failed to clean up stale connection:', error);
- // A permission rejection here means minting a new link is rejected too:
- // stop, and let the refetched policy disable the row.
- if (this.#settlePermissionRejection(toConnectorActionError('connect', error)))
- return undefined;
- }
-
- // Identity switched during the cleanup: minting now would create (and
- // persist) this scope's connection under the other identity.
- if (cacheScope.get() !== scope) return undefined;
- // Mint a fresh link; createComposioConnection replaces the record in place
- // (by identifier), so the UI keeps showing the same row with a new redirectUrl.
+ // One server write re-authorizes the connection in place: it drops the stale
+ // account (the prior link likely expired) and links a fresh one on the same
+ // connector row. Removing the row first and creating a new one would lose
+ // its scope: a private connection would come back shared — or land on a
+ // shared sibling — and the new account would run for workspace agents.
+ // createComposioConnection replaces the record in place (by identifier), so
+ // the UI keeps showing the same row with a new redirectUrl.
return this.#get().createComposioConnection({
+ agentId: existing.agentId,
appSlug: existing.appSlug,
identifier,
label: existing.label,
+ replacesConnectedAccountId: existing.connectedAccountId,
});
};
diff --git a/src/store/tool/slices/composioStore/actionError.test.ts b/src/store/tool/slices/composioStore/actionError.test.ts
index 14765335987..a78be65a215 100644
--- a/src/store/tool/slices/composioStore/actionError.test.ts
+++ b/src/store/tool/slices/composioStore/actionError.test.ts
@@ -173,15 +173,35 @@ describe('composio connection errors', () => {
expect(errorOf('gmail')).toBeUndefined();
});
- it('stops re-authorizing when the cleanup is rejected for permission', async () => {
+ it('re-authorizes the connection in place instead of removing and recreating it', async () => {
+ // Removing the row first would lose its visibility: a private connection
+ // would come back as a shared connector the workspace's agents run.
await loadGmail();
- mocks.deleteConnection.mockRejectedValue(forbidden());
+ mocks.createConnection.mockResolvedValue({
+ authConfigId: 'ac_gmail',
+ connectedAccountId: 'ca_gmail_new',
+ identifier: 'gmail',
+ redirectUrl: 'https://composio.dev/redirect',
+ });
+
+ await act(async () => {
+ await useToolStore.getState().reauthorizeComposioConnection('gmail');
+ });
+
+ expect(mocks.deleteConnection).not.toHaveBeenCalled();
+ expect(mocks.createConnection).toHaveBeenCalledWith(
+ expect.objectContaining({ identifier: 'gmail', replacesConnectedAccountId: 'ca_gmail' }),
+ );
+ });
+
+ it('settles a re-authorization rejected for permission without a red reason', async () => {
+ await loadGmail();
+ mocks.createConnection.mockRejectedValue(forbidden());
await act(async () => {
await useToolStore.getState().reauthorizeComposioConnection('gmail');
});
- expect(mocks.createConnection).not.toHaveBeenCalled();
expect(errorOf('gmail')).toBeUndefined();
expect(mocks.refreshConnectorManagePolicy).toHaveBeenCalledTimes(1);
});
diff --git a/src/store/tool/slices/composioStore/callTool.test.ts b/src/store/tool/slices/composioStore/callTool.test.ts
new file mode 100644
index 00000000000..7a9110cea0b
--- /dev/null
+++ b/src/store/tool/slices/composioStore/callTool.test.ts
@@ -0,0 +1,54 @@
+// @vitest-environment happy-dom
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { useToolStore } from '../../store';
+
+const mocks = vi.hoisted(() => ({ executeAction: vi.fn() }));
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {},
+ toolsClient: { composio: { executeAction: { mutate: mocks.executeAction } } },
+}));
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('callComposioTool', () => {
+ it('names the conversation the call belongs to', async () => {
+ mocks.executeAction.mockResolvedValue({ content: 'ok', success: true });
+
+ const result = await useToolStore.getState().callComposioTool({
+ agentId: 'agt_private',
+ identifier: 'gmail',
+ toolArgs: { to: '[email protected]' },
+ toolSlug: 'GMAIL_SEND_EMAIL',
+ topicId: 'tpc_direct',
+ });
+
+ expect(result).toEqual({ data: { content: 'ok', success: true }, success: true });
+ // The server resolves the connection this agent loads in that topic.
+ expect(mocks.executeAction).toHaveBeenCalledWith({
+ agentId: 'agt_private',
+ identifier: 'gmail',
+ toolArgs: { to: '[email protected]' },
+ toolSlug: 'GMAIL_SEND_EMAIL',
+ topicId: 'tpc_direct',
+ });
+ });
+
+ it('leaves the conversation out when the call names none', async () => {
+ mocks.executeAction.mockResolvedValue({ content: 'ok', success: true });
+
+ await useToolStore.getState().callComposioTool({
+ identifier: 'gmail',
+ toolSlug: 'GMAIL_SEND_EMAIL',
+ });
+
+ // Nothing is borrowed from global state: the server resolves shared rows only.
+ expect(mocks.executeAction).toHaveBeenCalledWith({
+ identifier: 'gmail',
+ toolSlug: 'GMAIL_SEND_EMAIL',
+ });
+ });
+});
diff --git a/src/store/tool/slices/composioStore/replica.test.ts b/src/store/tool/slices/composioStore/replica.test.ts
index f1a5f4768af..b04d590acb7 100644
--- a/src/store/tool/slices/composioStore/replica.test.ts
+++ b/src/store/tool/slices/composioStore/replica.test.ts
@@ -643,44 +643,42 @@ describe('composio connections replica', () => {
expect((persisted?.data ?? []).some((s) => s.connectedAccountId === 'ca_slack')).toBe(false);
});
- it('does not mint a reauthorized connection into the scope switched to during cleanup', async () => {
+ it('does not persist a reauthorized connection into the scope switched to while it ran', async () => {
mocks.getComposioPlugins.mockResolvedValue([composioPlugin('slack', { status: 'FAILED' })]);
renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), { wrapper });
await waitFor(() => expect(connectionIds()).toEqual(['slack']));
- let resolveDelete!: (value: unknown) => void;
- mocks.deleteConnection.mockReturnValueOnce(
+ let resolveCreate!: (value: unknown) => void;
+ mocks.createConnection.mockReturnValueOnce(
new Promise((resolve) => {
- resolveDelete = resolve;
+ resolveCreate = resolve;
}),
);
- mocks.createConnection.mockResolvedValue({
- authConfigId: 'ac_slack',
- connectedAccountId: 'ca_slack_new',
- identifier: 'slack',
- redirectUrl: 'https://composio.dev/redirect',
- });
let reauthorized!: Promise<unknown>;
await act(async () => {
reauthorized = useToolStore.getState().reauthorizeComposioConnection('slack');
});
- await waitFor(() => expect(mocks.deleteConnection).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(mocks.createConnection).toHaveBeenCalledTimes(1));
- // The user switches identity while the stale connection is being cleaned up.
+ // The user switches identity while the server re-authorizes the connection.
const nextScope = `composio-user-${randomUUID()}:personal`;
mocks.getComposioPlugins.mockResolvedValue([]);
useScope(nextScope);
await act(async () => {});
await act(async () => {
- resolveDelete({ success: true });
+ resolveCreate({
+ authConfigId: 'ac_slack',
+ connectedAccountId: 'ca_slack_new',
+ identifier: 'slack',
+ redirectUrl: 'https://composio.dev/redirect',
+ });
await reauthorized;
});
- // The reauthorization belongs to the scope that started it: no fresh link is
- // minted for — nor persisted into — the switched-to identity.
- expect(mocks.createConnection).not.toHaveBeenCalled();
+ // The reauthorization belongs to the scope that started it: its fresh link
+ // is not persisted into the switched-to identity.
const persisted = await composioServersResource.storage!.get({
queryKey: SERVERS_STORAGE_KEY,
scope: nextScope,
diff --git a/src/store/tool/slices/composioStore/types.ts b/src/store/tool/slices/composioStore/types.ts
index 53abec44eea..ef439591a30 100644
--- a/src/store/tool/slices/composioStore/types.ts
+++ b/src/store/tool/slices/composioStore/types.ts
@@ -38,12 +38,22 @@ export interface CreateComposioServerParams {
appSlug: string;
identifier: string;
label: string;
+ /** Re-authorize the connection running this account in place (see `reauthorizeComposioConnection`). */
+ replacesConnectedAccountId?: string;
}
export interface CallComposioToolParams {
+ /** The agent the call runs for, from the invoking message. */
+ agentId?: string;
identifier: string;
toolArgs?: Record<string, unknown>;
toolSlug: string;
+ /**
+ * The conversation the call belongs to, from the invoking message. The server
+ * resolves the connection in that conversation's scope (a private agent's own
+ * topic may use its owner's private connection).
+ */
+ topicId?: string;
}
export interface CallComposioToolResult {
diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.ts
index f6ffde42128..5135424b99b 100644
--- a/src/store/tool/slices/connector/action.ts
+++ b/src/store/tool/slices/connector/action.ts
@@ -727,13 +727,14 @@ export class ConnectorActionImpl {
* Sync tools from a client-provided list (for Lobehub OAuth skills / Composio
* that already have their tool list available on the client side).
* Idempotent — safe to call whenever the detail panel opens.
+ * Returns the connectorId, or `null` when no row was produced.
*/
syncToolsFromClient = async (params: {
identifier: string;
name: string;
sourceType: 'builtin' | 'custom' | 'marketplace';
tools: Array<{ description?: string; inputSchema?: Record<string, unknown>; toolName: string }>;
- }): Promise<string> => {
+ }): Promise<string | null> => {
const result = await lambdaClient.connector.syncToolsFromClient.mutate(params);
await this.fetchConnectors();
return result.connectorId;
@@ -742,9 +743,9 @@ export class ConnectorActionImpl {
/**
* Bootstrap connector entry for a builtin tool (reads manifest server-side).
* Idempotent — safe to call whenever the detail panel opens.
- * Returns the connectorId.
+ * Returns the connectorId, or `null` when no row was produced.
*/
- syncBuiltinTool = async (identifier: string): Promise<string> => {
+ syncBuiltinTool = async (identifier: string): Promise<string | null> => {
const result = await lambdaClient.connector.syncBuiltinTool.mutate({ identifier });
await this.fetchConnectors();
return result.connectorId;
@@ -754,7 +755,8 @@ export class ConnectorActionImpl {
* Bootstrap connector entry for an installed marketplace plugin.
* Idempotent — safe to call whenever the detail panel opens.
* Returns the connectorId, or `null` for legacy customPlugin rows that own
- * an MCP endpoint (those go through the frontend migration flow instead).
+ * an MCP endpoint (those go through the frontend migration flow instead) and
+ * for a plugin whose Composio account sits on a teammate's private connector.
*/
syncPluginTools = async (identifier: string): Promise<string | null> => {
const result = await lambdaClient.connector.syncPluginTools.mutate({ identifier });
diff --git a/src/store/tool/slices/connector/replaceConnector.test.ts b/src/store/tool/slices/connector/replaceConnector.test.ts
index c1cd64e14f8..83d190dac50 100644
--- a/src/store/tool/slices/connector/replaceConnector.test.ts
+++ b/src/store/tool/slices/connector/replaceConnector.test.ts
@@ -83,6 +83,49 @@ describe('snapshotReplacedConnector', () => {
snapshot: true,
});
});
+
+ describe("beside the caller's private row of the same identifier", () => {
+ // An install writes the shared row (`connector.create` upserts the row of
+ // the visibility it is given, shared by default)
+ const shared = row({
+ id: 'shared-row',
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://x',
+ sourceType: 'marketplace',
+ visibility: 'public',
+ });
+ const mine = row({
+ id: 'private-row',
+ mcpConnectionType: 'stdio',
+ sourceType: 'custom',
+ visibility: 'private',
+ });
+
+ it('snapshots the shared row the install overwrites, in either list order', async () => {
+ // Regression: the identifier lookup returned whichever row came first, so
+ // a reinstall could be refused over the private row, or snapshot it and
+ // roll back onto it while the shared row stayed half replaced.
+ for (const rows of [
+ [mine, shared],
+ [shared, mine],
+ ]) {
+ const { get, state } = makeStore(rows);
+
+ await expect(snapshotReplacedConnector('gmail', 'marketplace', get)).resolves.toEqual({
+ id: 'shared-row',
+ snapshot: true,
+ });
+ expect(state.getConnectorForEdit).toHaveBeenCalledWith('shared-row');
+ }
+ });
+
+ it('snapshots nothing when only the private row exists: the install creates the shared one', async () => {
+ const { get, state } = makeStore([mine]);
+
+ await expect(snapshotReplacedConnector('gmail', 'marketplace', get)).resolves.toBe(undefined);
+ expect(state.getConnectorForEdit).not.toHaveBeenCalled();
+ });
+ });
});
describe('restoreConnector', () => {
diff --git a/src/store/tool/slices/connector/replaceConnector.ts b/src/store/tool/slices/connector/replaceConnector.ts
index 4605f1251c6..b25b7eb67d1 100644
--- a/src/store/tool/slices/connector/replaceConnector.ts
+++ b/src/store/tool/slices/connector/replaceConnector.ts
@@ -33,7 +33,7 @@ export const snapshotReplacedConnector = async (
get: () => ToolStore,
): Promise<ConnectorSnapshot | undefined> => {
await get().fetchConnectors();
- const existing = connectorSelectors.connectorByIdentifier(identifier)(get());
+ const existing = connectorSelectors.sharedConnectorByIdentifier(identifier)(get());
if (!existing) return;
if (!isReplaceableBy(existing, sourceType)) {
throw new Error(
diff --git a/src/store/tool/slices/connector/selectors.connectorTab.test.ts b/src/store/tool/slices/connector/selectors.connectorTab.test.ts
new file mode 100644
index 00000000000..7cb05fcd70b
--- /dev/null
+++ b/src/store/tool/slices/connector/selectors.connectorTab.test.ts
@@ -0,0 +1,276 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ToolStore } from '@/store/tool/store';
+
+import {
+ connectorSelectors,
+ isInConnectorTab,
+ isIntegrationInConnectorTab,
+ pickRunConnectors,
+ pickRunToolSets,
+} from './selectors';
+import type { ConnectorWithTools } from './types';
+
+const connector = (patch: Partial<ConnectorWithTools>): ConnectorWithTools => ({
+ credentials: null,
+ id: 'c1',
+ identifier: 'linear',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example/linear',
+ metadata: null,
+ name: 'Linear',
+ sourceType: 'custom',
+ status: 'connected',
+ tools: [],
+ ...patch,
+});
+
+const sharedRow = connector({ id: 'shared-row', visibility: 'public' });
+const privateRow = connector({ id: 'private-row', visibility: 'private' });
+// A row from a server that predates visibility is shared
+const legacyRow = connector({ id: 'legacy-row' });
+
+describe('isInConnectorTab', () => {
+ it('lists private rows under the private tab and every other row under the shared one', () => {
+ expect(isInConnectorTab(privateRow, 'private')).toBe(true);
+ expect(isInConnectorTab(sharedRow, 'private')).toBe(false);
+ expect(isInConnectorTab(legacyRow, 'private')).toBe(false);
+
+ expect(isInConnectorTab(sharedRow, 'public')).toBe(true);
+ expect(isInConnectorTab(legacyRow, 'public')).toBe(true);
+ expect(isInConnectorTab(privateRow, 'public')).toBe(false);
+ });
+
+ it('lists every row without a tab (outside a workspace)', () => {
+ expect([sharedRow, privateRow, legacyRow].every((c) => isInConnectorTab(c))).toBe(true);
+ });
+});
+
+describe('connectorSelectors.connectorByIdentifier', () => {
+ const state = (connectors: ConnectorWithTools[]) => ({ connectors }) as unknown as ToolStore;
+
+ it('opens the row of the tab it was picked from when two rows share an identifier', () => {
+ for (const rows of [
+ [sharedRow, privateRow],
+ [privateRow, sharedRow],
+ ]) {
+ expect(connectorSelectors.connectorByIdentifier('linear', 'private')(state(rows))?.id).toBe(
+ 'private-row',
+ );
+ expect(connectorSelectors.connectorByIdentifier('linear', 'public')(state(rows))?.id).toBe(
+ 'shared-row',
+ );
+ }
+ });
+
+ it('falls back to the first row without a tab or a row of that tab', () => {
+ expect(connectorSelectors.connectorByIdentifier('linear')(state([privateRow]))?.id).toBe(
+ 'private-row',
+ );
+ expect(
+ connectorSelectors.connectorByIdentifier('linear', 'private')(state([sharedRow]))?.id,
+ ).toBe('shared-row');
+ expect(connectorSelectors.connectorByIdentifier('missing')(state([sharedRow]))).toBe(undefined);
+ });
+});
+
+describe('isIntegrationInConnectorTab', () => {
+ // A Composio connection's row: endpoint-less, named by the app identifier
+ const gmail = (id: string, visibility: 'private' | 'public') =>
+ connector({
+ id,
+ identifier: 'gmail',
+ mcpServerUrl: null,
+ sourceType: 'composio' as never,
+ visibility,
+ });
+
+ it('lists an integration whose only row is private under the private tab alone', () => {
+ // Regression: the private tab hid every OAuth integration, so a Composio
+ // connection made private showed the empty state there and stayed listed
+ // under the shared tab.
+ const rows = [gmail('my-gmail', 'private')];
+
+ expect(isIntegrationInConnectorTab('gmail', rows, 'private')).toBe(true);
+ expect(isIntegrationInConnectorTab('gmail', rows, 'public')).toBe(false);
+ });
+
+ it('lists an integration with a shared row under the shared tab', () => {
+ expect(isIntegrationInConnectorTab('gmail', [gmail('ws-gmail', 'public')], 'public')).toBe(
+ true,
+ );
+ expect(isIntegrationInConnectorTab('gmail', [gmail('ws-gmail', 'public')], 'private')).toBe(
+ false,
+ );
+ });
+
+ it('lists an integration with both rows under both tabs', () => {
+ const rows = [gmail('ws-gmail', 'public'), gmail('my-gmail', 'private')];
+
+ expect(isIntegrationInConnectorTab('gmail', rows, 'public')).toBe(true);
+ expect(isIntegrationInConnectorTab('gmail', rows, 'private')).toBe(true);
+ });
+
+ it('keeps an integration nobody connected with the shared pool, and lists all without a tab', () => {
+ expect(isIntegrationInConnectorTab('gmail', [], 'public')).toBe(true);
+ expect(isIntegrationInConnectorTab('gmail', [], 'private')).toBe(false);
+ expect(isIntegrationInConnectorTab('gmail', [gmail('my-gmail', 'private')])).toBe(true);
+ });
+});
+
+describe('isIntegrationInConnectorTab: an entry bound to one account', () => {
+ const composioRow = (id: string, visibility: 'private' | 'public', accountId: string) =>
+ connector({
+ id,
+ identifier: 'gmail',
+ mcpServerUrl: null,
+ metadata: { composio: { connectedAccountId: accountId } },
+ visibility,
+ });
+ const rows = [
+ composioRow('ws-gmail', 'public', 'ca_team'),
+ composioRow('my-gmail', 'private', 'ca_mine'),
+ ];
+
+ it('lists under the tab of the row holding the account its actions act on, never both', () => {
+ // Regression: with a private and a shared row, the entry listed under both
+ // tabs, but the store holds one connection per identifier, so Disconnect in
+ // the Private tab could remove the shared workspace connection.
+ expect(isIntegrationInConnectorTab('gmail', rows, 'private', 'ca_mine')).toBe(true);
+ expect(isIntegrationInConnectorTab('gmail', rows, 'public', 'ca_mine')).toBe(false);
+
+ expect(isIntegrationInConnectorTab('gmail', rows, 'public', 'ca_team')).toBe(true);
+ expect(isIntegrationInConnectorTab('gmail', rows, 'private', 'ca_team')).toBe(false);
+ });
+
+ it('keeps an account no row names with the shared pool', () => {
+ expect(isIntegrationInConnectorTab('gmail', rows, 'public', 'ca_legacy')).toBe(true);
+ expect(isIntegrationInConnectorTab('gmail', rows, 'private', 'ca_legacy')).toBe(false);
+ });
+});
+
+describe('connectorSelectors.sharedConnectorByIdentifier', () => {
+ const state = (connectors: ConnectorWithTools[]) => ({ connectors }) as unknown as ToolStore;
+
+ it('reads the shared row whichever order the list holds them in, and never a private one', () => {
+ for (const rows of [
+ [sharedRow, privateRow],
+ [privateRow, sharedRow],
+ ]) {
+ expect(connectorSelectors.sharedConnectorByIdentifier('linear')(state(rows))?.id).toBe(
+ 'shared-row',
+ );
+ }
+ expect(connectorSelectors.sharedConnectorByIdentifier('linear')(state([privateRow]))).toBe(
+ undefined,
+ );
+ expect(connectorSelectors.sharedConnectorByIdentifier('linear')(state([legacyRow]))?.id).toBe(
+ 'legacy-row',
+ );
+ });
+});
+
+describe('pickRunConnectors', () => {
+ const ids = (rows: ConnectorWithTools[]) => rows.map((c) => c.id);
+
+ it("runs the owner's private row of an identifier the workspace also shares, in either order", () => {
+ for (const rows of [
+ [sharedRow, privateRow],
+ [privateRow, sharedRow],
+ ]) {
+ expect(ids(pickRunConnectors(rows, { includePrivate: true }))).toEqual(['private-row']);
+ expect(ids(pickRunConnectors(rows, { includePrivate: false }))).toEqual(['shared-row']);
+ }
+ });
+
+ it('keeps the lowest id among rows of equal rank, as the server orders them', () => {
+ const a = connector({ id: 'a-row', visibility: 'public' });
+ const b = connector({ id: 'b-row', visibility: 'public' });
+
+ expect(ids(pickRunConnectors([b, a], { includePrivate: true }))).toEqual(['a-row']);
+ expect(ids(pickRunConnectors([a, b], { includePrivate: true }))).toEqual(['a-row']);
+ });
+
+ it('leaves out a row mounted on another agent, so the shared row still serves', () => {
+ // Regression: a private row mounted on another agent shadowed the shared
+ // row here, then dropped out as disabled, leaving the agent without tools.
+ const mountedElsewhere = connector({
+ id: 'a-private',
+ metadata: { mountedByAgentId: 'agt-other' },
+ visibility: 'private',
+ });
+
+ expect(
+ ids(
+ pickRunConnectors([mountedElsewhere, sharedRow], {
+ agentId: 'agt-me',
+ includePrivate: true,
+ }),
+ ),
+ ).toEqual(['shared-row']);
+ // Without an agent no mounted row runs
+ expect(ids(pickRunConnectors([mountedElsewhere, sharedRow], { includePrivate: true }))).toEqual(
+ ['shared-row'],
+ );
+ });
+
+ it('runs the row mounted on the agent over a free one, as the server ranks them', () => {
+ const mountedHere = connector({
+ id: 'z-mounted',
+ metadata: { mountedByAgentId: 'agt-me' },
+ visibility: 'public',
+ });
+
+ expect(
+ ids(
+ pickRunConnectors([privateRow, mountedHere], { agentId: 'agt-me', includePrivate: true }),
+ ),
+ ).toEqual(['z-mounted']);
+ });
+
+ it('keeps one row per identifier in list order', () => {
+ const notion = connector({ id: 'notion-row', identifier: 'notion', visibility: 'private' });
+
+ expect(ids(pickRunConnectors([sharedRow, notion], { includePrivate: true }))).toEqual([
+ 'shared-row',
+ 'notion-row',
+ ]);
+ expect(ids(pickRunConnectors([sharedRow, notion], { includePrivate: false }))).toEqual([
+ 'shared-row',
+ ]);
+ });
+});
+
+describe('pickRunToolSets', () => {
+ const prefixes = (rows: { toolIdentifier: string }[]) => rows.map((c) => c.toolIdentifier);
+ const mine = connector({ id: '3f9a1c2e-mine', visibility: 'private' });
+
+ it('keeps the shared and the private row each as its own tool set', () => {
+ expect(prefixes(pickRunToolSets([mine, sharedRow], { includePrivate: true }))).toEqual([
+ 'linear-3f9a1c2e',
+ 'linear',
+ ]);
+ expect(prefixes(pickRunToolSets([mine, sharedRow], { includePrivate: false }))).toEqual([
+ 'linear',
+ ]);
+ });
+
+ it("lets a row mounted on the run's agent stand alone, and leaves out other agents' mounts", () => {
+ const mountedHere = connector({ id: 'z-here', metadata: { mountedByAgentId: 'agt-me' } });
+ const mountedElsewhere = connector({ id: 'a-else', metadata: { mountedByAgentId: 'agt-x' } });
+
+ expect(
+ pickRunToolSets([mine, sharedRow, mountedHere, mountedElsewhere], {
+ agentId: 'agt-me',
+ includePrivate: true,
+ }).map((c) => c.id),
+ ).toEqual(['z-here']);
+ expect(
+ pickRunToolSets([sharedRow, mountedElsewhere], {
+ agentId: 'agt-me',
+ includePrivate: true,
+ }).map((c) => c.id),
+ ).toEqual(['shared-row']);
+ });
+});
diff --git a/src/store/tool/slices/connector/selectors.runtime.test.ts b/src/store/tool/slices/connector/selectors.runtime.test.ts
index 6d512257f94..934e11cd3bc 100644
--- a/src/store/tool/slices/connector/selectors.runtime.test.ts
+++ b/src/store/tool/slices/connector/selectors.runtime.test.ts
@@ -142,6 +142,18 @@ describe('marketplace MCPs installed as connectors', () => {
).toBe(marked);
});
+ it('keeps a private reinstall over a legacy row listed, a tool set of its own', () => {
+ // Regression: made private, the reinstall vanished from the Private tab:
+ // the list hid it behind its legacy plugin, which only the Workspace tab shows
+ const privateRow = { ...marked, visibility: 'private' as const };
+ const withLegacyRow = state({
+ connectors: [privateRow],
+ installedPlugins: [{ identifier: 'oauth-market' }] as never,
+ });
+
+ expect(connectorSelectors.marketplaceMcpConnectors(withLegacyRow)).toEqual([privateRow]);
+ });
+
it('resolves no connector for a row that only projects a plugin or comes from another source', () => {
const projection = connector({ mcpConnectionType: null, mcpServerUrl: null });
const custom = connector({ sourceType: 'custom' });
@@ -172,6 +184,50 @@ describe('connectorSelectors.connectorByIdentifierForAgent', () => {
expect(connectorSelectors.connectorByIdentifierForAgent('oauth-market')(s)).toBe(undefined);
});
+ it("resolves each row by its own tool prefix: the shared one's and the private one's", () => {
+ const privateRow = connector({ id: '3f9a1c2e-private', visibility: 'private' });
+ const sharedRow = connector({ id: 'shared-row', visibility: 'public' });
+ // The shared row listed first: physical order is not a ranking
+ const s = state([sharedRow, privateRow]);
+
+ // The connector's identifier names the shared row's tool set, in any run
+ for (const includePrivate of [true, false]) {
+ expect(
+ connectorSelectors.connectorByIdentifierForAgent('oauth-market', 'agt_a', {
+ includePrivate,
+ })(s)?.id,
+ ).toBe('shared-row');
+ }
+ // The private row is a tool set of its own, under its suffixed prefix
+ expect(
+ connectorSelectors.connectorByIdentifierForAgent('oauth-market-3f9a1c2e', 'agt_a', {
+ includePrivate: true,
+ })(s)?.id,
+ ).toBe('3f9a1c2e-private');
+ // ... which a run that may not use it never resolves
+ expect(
+ connectorSelectors.connectorByIdentifierForAgent('oauth-market-3f9a1c2e', 'agt_a', {
+ includePrivate: false,
+ })(s),
+ ).toBe(undefined);
+ });
+
+ it('resolves a private row mounted on the agent by its own prefix, never the bare one', () => {
+ const mounted = connector({
+ id: '3f9a1c2e-mounted',
+ metadata: { mountedByAgentId: 'agt_a' },
+ visibility: 'private',
+ });
+ const s = { ...state([mounted]), agentConnectors: { agt_a: [mounted] } } as never;
+
+ expect(
+ connectorSelectors.connectorByIdentifierForAgent('oauth-market-3f9a1c2e', 'agt_a')(s)?.id,
+ ).toBe('3f9a1c2e-mounted');
+ expect(connectorSelectors.connectorByIdentifierForAgent('oauth-market', 'agt_a')(s)).toBe(
+ undefined,
+ );
+ });
+
it('resolves a base connector that is free or mounted by this agent', () => {
expect(
connectorSelectors.connectorByIdentifierForAgent(
diff --git a/src/store/tool/slices/connector/selectors.ts b/src/store/tool/slices/connector/selectors.ts
index 4565c1dba36..e112e2c2179 100644
--- a/src/store/tool/slices/connector/selectors.ts
+++ b/src/store/tool/slices/connector/selectors.ts
@@ -3,6 +3,7 @@ import {
isMarketplaceInstallCompleted,
isMarketplaceInstallRunnable,
} from '@lobechat/const';
+import { connectorToolIdentifier, type ConnectorVisibility } from '@lobechat/types';
import type { ToolStoreState } from '../../initialState';
import type { ToolStore } from '../../store';
@@ -30,10 +31,198 @@ const connectorById =
(s: ToolStore): ConnectorWithTools | undefined =>
allById(id)(s);
+/**
+ * Whether `connector` lists under a workspace connector page's tab: the
+ * caller's private rows under `private`, every other row under `public` (the
+ * shared pool). Without a tab (outside a workspace) every row lists.
+ */
+export const isInConnectorTab = (
+ connector: Pick<ConnectorWithTools, 'visibility'>,
+ visibility?: ConnectorVisibility,
+): boolean => !visibility || (connector.visibility === 'private') === (visibility === 'private');
+
+/** The Composio account a connector row connects (`metadata.composio.connectedAccountId`). */
+const composioAccountId = (
+ metadata: Record<string, unknown> | null | undefined,
+): string | undefined => {
+ const composio = metadata?.composio;
+ if (!composio || typeof composio !== 'object') return;
+ const id = (composio as { connectedAccountId?: unknown }).connectedAccountId;
+ return typeof id === 'string' && id ? id : undefined;
+};
+
+/**
+ * Whether an OAuth integration (a Composio or LobeHub catalog entry) lists under
+ * a workspace connector page's tab. The entry carries no visibility; its
+ * connector rows do.
+ *
+ * An entry whose actions act on one account (`accountId`, the Composio
+ * connection the store holds for the identifier) lists under that account's
+ * row's tab alone: the store keeps one connection per identifier, so with a
+ * private and a shared row the entry in the other tab would disconnect,
+ * re-authorize or refresh the wrong account. An account no row names stays
+ * with the shared pool.
+ *
+ * Otherwise it lists under `private` when the caller has a private row of it,
+ * and under `public` unless its only rows are private: an entry nobody
+ * connected stays with the shared pool, where it can be connected.
+ */
+export const isIntegrationInConnectorTab = (
+ identifier: string,
+ connectors: Pick<ConnectorWithTools, 'identifier' | 'metadata' | 'visibility'>[],
+ visibility?: ConnectorVisibility,
+ accountId?: string,
+): boolean => {
+ if (!visibility) return true;
+ const rows = connectors.filter((c) => c.identifier === identifier);
+ if (accountId) {
+ const accountRow = rows.find((c) => composioAccountId(c.metadata) === accountId);
+ return accountRow ? isInConnectorTab(accountRow, visibility) : visibility !== 'private';
+ }
+ if (rows.length === 0) return visibility !== 'private';
+
+ return rows.some((c) => isInConnectorTab(c, visibility));
+};
+
+/**
+ * The connectors a run loads from the caller's list, one per identifier, ranked
+ * as the server's `ConnectorModel.pickByPriority` ranks base rows: a row
+ * mounted on the run's agent outranks a free one, the owner's private row
+ * shadows the shared one, and equal ranks keep the lowest id (the server's
+ * `resolutionOrder`), never the list order. A row mounted on another agent
+ * takes no part (the server's `agentNarrowing`), nor does any mounted row
+ * without an agent. Without `includePrivate` (any run but a private agent's
+ * own conversation) private rows take no part.
+ *
+ * Whatever is built per identifier (a tool manifest, its permissions, a menu
+ * row) must come from this row: the server executes it.
+ */
+export const pickRunConnectors = <
+ T extends Pick<ConnectorWithTools, 'id' | 'identifier' | 'metadata' | 'visibility'>,
+>(
+ connectors: T[],
+ { agentId, includePrivate }: { agentId?: string; includePrivate: boolean },
+): T[] => {
+ const mountedBy = (c: T) => {
+ const value = c.metadata?.mountedByAgentId;
+ return typeof value === 'string' && value ? value : undefined;
+ };
+ const rank = (c: T) => (mountedBy(c) ? 3 : 0) + (c.visibility === 'private' ? 1 : 0);
+ const byIdentifier = new Map<string, T>();
+ for (const connector of connectors) {
+ if (!includePrivate && connector.visibility === 'private') continue;
+ const mount = mountedBy(connector);
+ if (mount && mount !== agentId) continue;
+ const current = byIdentifier.get(connector.identifier);
+ if (
+ !current ||
+ rank(connector) > rank(current) ||
+ (rank(connector) === rank(current) && connector.id < current.id)
+ )
+ byIdentifier.set(connector.identifier, connector);
+ }
+ return [...byIdentifier.values()];
+};
+
+/**
+ * The connectors a run turns into tool sets from the caller's list, each with
+ * its tool prefix: the client mirror of `ConnectorModel.resolveToolSets` for a
+ * run the server has not listed (`connector.listForRun`). A row mounted on the
+ * run's agent stands alone for its identifier; otherwise each row the run may
+ * use — the shared one and, with `includePrivate`, the caller's private one —
+ * is its own tool set. Rows mounted on another agent take no part.
+ */
+export const pickRunToolSets = <
+ T extends Pick<ConnectorWithTools, 'id' | 'identifier' | 'metadata' | 'visibility'>,
+>(
+ connectors: T[],
+ { agentId, includePrivate }: { agentId?: string; includePrivate: boolean },
+): (T & { toolIdentifier: string })[] => {
+ const eligible = connectors.filter((c) => {
+ if (!includePrivate && c.visibility === 'private') return false;
+ const mount = c.metadata?.mountedByAgentId;
+ return !(typeof mount === 'string' && mount && mount !== agentId);
+ });
+ const mounted = new Set(
+ eligible
+ .filter((c) => agentId && c.metadata?.mountedByAgentId === agentId)
+ .map((c) => c.identifier),
+ );
+ const reserved = new Set(connectors.map((c) => c.identifier));
+ const prefixOf = (c: T) => connectorToolIdentifier(c, undefined, reserved);
+ const byPrefix = new Map<string, T & { toolIdentifier: string }>();
+ for (const connector of [...eligible].sort((a, b) => (a.id < b.id ? -1 : 1))) {
+ if (mounted.has(connector.identifier) && connector.metadata?.mountedByAgentId !== agentId)
+ continue;
+ const toolIdentifier = prefixOf(connector);
+ if (!byPrefix.has(toolIdentifier))
+ byPrefix.set(toolIdentifier, { ...connector, toolIdentifier });
+ }
+ // Keep the list's order
+ return eligible.flatMap((c) => {
+ const kept = byPrefix.get(prefixOf(c));
+ return kept && kept.id === c.id ? [kept] : [];
+ });
+};
+
+/**
+ * The Composio apps a run must not offer: those whose connection rows the
+ * caller's list holds, none of which the run may use — a private connection
+ * outside its owner's private agent's own conversation. Their tools come from
+ * the Composio projection, which no run scope filters, while the execution
+ * lookup only serves a connection the run may use, so every call would fail.
+ * The server's listing for the conversation (`connector.listForRun`) decides
+ * when present; otherwise the run's rows are picked the way the server picks
+ * them ({@link pickRunConnectors}). An app with no connection row (a legacy
+ * plugin-only connection) is left to its projection.
+ */
+export const composioIdsOutsideRun = <
+ T extends Pick<ConnectorWithTools, 'id' | 'identifier' | 'metadata' | 'visibility'>,
+>(
+ connectors: T[],
+ {
+ agentId,
+ includePrivate,
+ listed,
+ }: { agentId?: string; includePrivate: boolean; listed?: Pick<T, 'identifier' | 'metadata'>[] },
+): Set<string> => {
+ const isComposio = (c: Pick<T, 'metadata'>) => !!c.metadata?.composio;
+ const local = connectors.filter(isComposio);
+ const usable = new Set(
+ (listed
+ ? listed.filter(isComposio)
+ : pickRunConnectors(local, { agentId, includePrivate })
+ ).map((c) => c.identifier),
+ );
+ return new Set(local.map((c) => c.identifier).filter((id) => !usable.has(id)));
+};
+
const connectorByIdentifier =
+ (
+ identifier: string,
+ /**
+ * The workspace connector page's tab. A private and a shared connector may
+ * share an identifier; the tab a row was opened from names the one meant.
+ */
+ visibility?: ConnectorVisibility,
+ ) =>
+ (s: ToolStore): ConnectorWithTools | undefined => {
+ const rows = (s.connectors ?? []).filter((c) => c.identifier === identifier);
+
+ return rows.find((c) => isInConnectorTab(c, visibility)) ?? rows[0];
+ };
+
+/**
+ * The shared (workspace) row of `identifier`, never a private one. A
+ * marketplace or custom MCP install writes the shared row (`connector.create`
+ * upserts the row of the visibility it is given, shared by default), so what
+ * it replaces, rolls back or reads after authorizing is that row, whichever
+ * order the list holds a private row of the same identifier in.
+ */
+const sharedConnectorByIdentifier =
(identifier: string) =>
(s: ToolStore): ConnectorWithTools | undefined =>
- (s.connectors ?? []).find((c) => c.identifier === identifier);
+ (s.connectors ?? []).find((c) => c.identifier === identifier && c.visibility !== 'private');
const enabledConnectors = (s: ToolStore): ConnectorWithTools[] =>
(s.connectors ?? []).filter((c) => c.isEnabled);
@@ -65,10 +254,14 @@ const isMarketplaceConnectorInstalled =
/**
* Finished marketplace installs that have no legacy plugin row. Lists show
* them beside installed plugins; one with a legacy row is listed as that plugin.
+ * A legacy row stands in for the shared install only: a private install is a
+ * tool set of its own (under its own prefix) and is always listed.
*/
const marketplaceMcpConnectors = (s: ToolStoreState): ConnectorWithTools[] => {
const legacy = new Set((s.installedPlugins ?? []).map((plugin) => plugin.identifier));
- return installedMarketplaceConnectors(s).filter((c) => !legacy.has(c.identifier));
+ return installedMarketplaceConnectors(s).filter(
+ (c) => c.visibility === 'private' || !legacy.has(c.identifier),
+ );
};
/**
@@ -170,26 +363,53 @@ const connectedMcpConnectorsForAgent = (
};
/**
- * The connector a conversation of `agentId` resolves `identifier` to, mirroring
- * the server's agent-aware resolution: the agent's own row first (agent-owned
- * over mounted), else the base connector. Agent tools are only known once that
- * agent's list has loaded.
+ * The connector a conversation of `agentId` runs a tool of `identifier` on,
+ * mirroring the server's resolution: the agent's own row first (agent-owned
+ * over mounted), else the base row whose tool prefix is `identifier`
+ * (`connectorToolIdentifier`) — a private row is its own tool set beside the
+ * shared one of its connector, so the prefix names the row. Agent tools are
+ * only known once that agent's list has loaded.
*/
const connectorByIdentifierForAgent =
- (identifier: string, agentId?: string) =>
+ (
+ /** A tool's identifier: its connector row's tool prefix. */
+ identifier: string,
+ agentId?: string,
+ /**
+ * Whether the caller's private rows take part. Only the server can tell
+ * whether a conversation may run one (`connectorRunScope`), so executors
+ * resolve through `resolveRunConnector`, which asks it when this decides
+ * the row; management surfaces leave the default. A private row the run
+ * may not use must not shadow the shared row of the same identifier, or a
+ * public agent would execute a connection its scope explicitly excludes.
+ */
+ { includePrivate = true }: { includePrivate?: boolean } = {},
+ ) =>
(s: ToolStore): ConnectorWithTools | undefined => {
+ // Named as the server names them: no own row reads as a listed identifier
+ const reserved = new Set((s.connectors ?? []).map((c) => c.identifier));
+ // An agent-owned row keeps its identifier; a row mounted on the agent keeps
+ // the prefix of its own visibility (a mounted private row is suffixed)
const agentRows = agentId
- ? (s.agentConnectors?.[agentId] ?? []).filter((c) => c.identifier === identifier)
+ ? (s.agentConnectors?.[agentId] ?? []).filter(
+ (c) => connectorToolIdentifier(c, undefined, reserved) === identifier,
+ )
: [];
+ // A base connector another agent mounted serves only that agent, as the
+ // server's scope rule has it (`ConnectorModel.scopePredicate`).
+ const baseRows = (s.connectors ?? []).filter(
+ (c) =>
+ connectorToolIdentifier(c, undefined, reserved) === identifier &&
+ isLibraryConnectorForAgent(c, agentId) &&
+ (includePrivate || c.visibility !== 'private'),
+ );
+
+ // Duplicate shared rows of one identifier: the lowest id, as the server keeps
return (
agentRows.find((c) => c.agentId === agentId) ??
agentRows[0] ??
- // A base connector another agent mounted serves only that agent, as the
- // server's scope rule has it (`ConnectorModel.scopePredicate`)
- (s.connectors ?? []).find(
- (c) => c.identifier === identifier && isLibraryConnectorForAgent(c, agentId),
- )
+ baseRows.sort((a, b) => (a.id < b.id ? -1 : 1))[0]
);
};
@@ -240,6 +460,7 @@ export const connectorSelectors = {
connectedMcpConnectorsForAgent,
marketplaceMcpConnectorByIdentifier,
marketplaceMcpConnectors,
+ sharedConnectorByIdentifier,
connectorToolsGroupedByIdentifier:
(identifier: string) =>
(s: ToolStore): GroupedTools => {
diff --git a/src/store/tool/slices/connector/types.ts b/src/store/tool/slices/connector/types.ts
index 56e26a125cc..8d023942121 100644
--- a/src/store/tool/slices/connector/types.ts
+++ b/src/store/tool/slices/connector/types.ts
@@ -1,4 +1,9 @@
-import type { ConnectorAuthKind, ConnectorLinkProfile, ConnectorLinkStatus } from '@lobechat/types';
+import type {
+ ConnectorAuthKind,
+ ConnectorLinkProfile,
+ ConnectorLinkStatus,
+ ConnectorVisibility,
+} from '@lobechat/types';
import type { ConnectorToolPermission } from '@/database/schemas';
@@ -38,9 +43,19 @@ export interface ConnectorWithTools {
name: string;
sourceType: string;
status: string;
+ /**
+ * The row's tool prefix, when the server resolved it for a run
+ * (`connector.listForRun`); otherwise derived with `connectorToolIdentifier`.
+ */
+ toolIdentifier?: string;
tools: ConnectorTool[];
/** Creator attribution — drives the workspace row-level manage gate. */
userId?: string | null;
+ /**
+ * Workspace only: `private` is the creator's own connector, offered only to
+ * their private agents. Absent on rows from older servers (shared).
+ */
+ visibility?: ConnectorVisibility;
}
export interface ConnectorLinkSummary {
diff --git a/src/store/tool/slices/mcpStore/installMarketplaceConnector.ts b/src/store/tool/slices/mcpStore/installMarketplaceConnector.ts
index 87cd713d789..c1cbeebd283 100644
--- a/src/store/tool/slices/mcpStore/installMarketplaceConnector.ts
+++ b/src/store/tool/slices/mcpStore/installMarketplaceConnector.ts
@@ -124,7 +124,7 @@ export const installMarketplaceConnector = async (
let snapshot: ConnectorSnapshot | undefined;
if (isOAuth) {
- const connector = connectorSelectors.connectorByIdentifier(identifier)(get());
+ const connector = connectorSelectors.sharedConnectorByIdentifier(identifier)(get());
if (!connector) throw new Error('The MCP connector did not finish authorization');
connectorId = connector.id;
// Authorization already wrote the row: a cancel while finishing removes the
diff --git a/src/store/tool/slices/mcpStore/installOAuthPlugin.ts b/src/store/tool/slices/mcpStore/installOAuthPlugin.ts
index afb76c2454e..72d7c2694eb 100644
--- a/src/store/tool/slices/mcpStore/installOAuthPlugin.ts
+++ b/src/store/tool/slices/mcpStore/installOAuthPlugin.ts
@@ -59,7 +59,7 @@ export const installOAuthPlugin = async (
signal.throwIfAborted();
await fetchConnectors();
signal.throwIfAborted();
- const connector = connectorSelectors.connectorByIdentifier(identifier)(get());
+ const connector = connectorSelectors.sharedConnectorByIdentifier(identifier)(get());
if (!connector || connector.status !== 'connected') {
throw new Error('The MCP connector did not finish authorization');
}
diff --git a/src/store/tool/slices/plugin/action.ts b/src/store/tool/slices/plugin/action.ts
index 66db603eb1e..9cb1e66c177 100644
--- a/src/store/tool/slices/plugin/action.ts
+++ b/src/store/tool/slices/plugin/action.ts
@@ -231,6 +231,7 @@ export class PluginActionImpl {
onThisDevice = false,
server,
toolArguments,
+ topicId,
}: {
agentId?: string;
/** The account the view acts as, when its arguments cannot name one. */
@@ -238,6 +239,7 @@ export class PluginActionImpl {
onThisDevice?: boolean;
server?: string;
toolArguments?: string;
+ topicId?: string;
},
): SWRResponse<ReadResourceResult | undefined> =>
useClientDataSWR(
@@ -247,6 +249,7 @@ export class PluginActionImpl {
onThisDevice,
server,
toolArguments,
+ topicId,
}),
() =>
mcpService.readMcpAppResource(identifier, resourceUri, {
@@ -255,6 +258,7 @@ export class PluginActionImpl {
onThisDevice,
server,
toolArguments,
+ topicId,
}),
{ revalidateOnFocus: false, revalidateOnReconnect: false },
);