π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat: make connected tools available to agents on demand by default (#23466)
AmAzing-591a2b0617a1
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.tsindex 59876aed5a6..0d675e23377 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts@@ -14,7 +14,7 @@ import {CONTEXT_ENGINEERING_SPAN_NAME,tracer as agentRuntimeTracer,} from '@lobechat/observability-otel/modules/agent-runtime';-import { getOptedInPluginIds, type UIChatMessage } from '@lobechat/types';+import { type UIChatMessage } from '@lobechat/types';import { serverMessagesEngine } from '@/server/modules/Mecha/ContextEngineering';import {@@ -145,12 +145,6 @@ export const buildServerCallLlmContext = async ({isSubAgent: state.origin?.lineage?.isSubAgent === true,mentionedAgents: (state as any).initialContext?.initialContext?.mentionedAgents,messages: messagesForContext,- // `agent.plugins` is collapsed to pinned ids; the `auto` entries ride on- // the world. Together they are what the agent turned on.- optedInPluginIds: [- ...getOptedInPluginIds(agentConfig.plugins ?? undefined),- ...(state.world?.autoSkillIds ?? []),- ],shareVisitor: state.principal?.actor?.shareVisitor ?? ctx.agentShareVisitor,topicId,workspaceId: state.origin?.workspaceId ?? ctx.workspaceId,diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.tsindex 5f0a8640428..e57ecae947f 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts@@ -4,7 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { AiAgentService } from '../index';const {- mockConnectorQueryByIdentifiers,+ mockResolveAllConnectors,mockConnectorToolQueryAll,mockCreateOperation,mockCreateServerAgentToolsEngine,@@ -12,7 +12,7 @@ const {mockMessageCreate,mockPluginQuery,} = vi.hoisted(() => ({- mockConnectorQueryByIdentifiers: vi.fn().mockResolvedValue([]),+ mockResolveAllConnectors: vi.fn().mockResolvedValue([]),mockConnectorToolQueryAll: vi.fn().mockResolvedValue([]),mockCreateOperation: vi.fn(),mockCreateServerAgentToolsEngine: vi.fn().mockReturnValue({@@ -72,8 +72,8 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/connector', () => ({ConnectorModel: vi.fn().mockImplementation(function () {return {- queryByIdentifiers: mockConnectorQueryByIdentifiers,- resolveByIdentifiers: mockConnectorQueryByIdentifiers,+ resolveAll: mockResolveAllConnectors,+ resolveByIdentifiers: vi.fn().mockResolvedValue([]),};}),}));@@ -177,6 +177,7 @@ const connectorOf = (over: Record<string, unknown>) => ({mcpServerUrl: 'https://mcp.example.com',mcpStdioConfig: null,name: 'Plugin A connector',+ status: 'connected',...over,});@@ -199,7 +200,7 @@ describe('AiAgentService.execAgent - connector/plugin overlap', () => {chatConfig: {},id: 'agent-1',model: 'gpt-4',- plugins: ['plugin-a'],+ plugins: [],provider: 'openai',systemRole: 'You are a helper',});@@ -208,7 +209,7 @@ describe('AiAgentService.execAgent - connector/plugin overlap', () => {});it('keeps a same-named plugin when the connector is disabled', async () => {- mockConnectorQueryByIdentifiers.mockResolvedValue([connectorOf({ isEnabled: false })]);+ mockResolveAllConnectors.mockResolvedValue([connectorOf({ isEnabled: false })]);mockConnectorToolQueryAll.mockResolvedValue([{ permission: 'auto', toolName: 'x', userConnectorId: 'c1' },]);@@ -219,7 +220,7 @@ describe('AiAgentService.execAgent - connector/plugin overlap', () => {});it('keeps a same-named plugin when the connector has no synced tools', async () => {- mockConnectorQueryByIdentifiers.mockResolvedValue([connectorOf({ isEnabled: true })]);+ mockResolveAllConnectors.mockResolvedValue([connectorOf({ isEnabled: true })]);mockConnectorToolQueryAll.mockResolvedValue([]);await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);@@ -228,7 +229,7 @@ describe('AiAgentService.execAgent - connector/plugin overlap', () => {});it('replaces the plugin when the connector actually produces tools', async () => {- mockConnectorQueryByIdentifiers.mockResolvedValue([connectorOf({ isEnabled: true })]);+ mockResolveAllConnectors.mockResolvedValue([connectorOf({ isEnabled: true })]);mockConnectorToolQueryAll.mockResolvedValue([{ permission: 'auto', toolName: 'x', userConnectorId: 'c1' },]);diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.tsindex 460d6ff2185..b98ec6095d9 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts@@ -240,13 +240,13 @@ describe('AiAgentService.execAgent - agent plugin entries (on / off / disabled)'expect(disabledPluginIdsArg()).toEqual(expect.arrayContaining(onDemandBuiltinToolIds));});- it('keeps only the installed plugins that are on, in a mixed-shape array: a disabled entry and a missing entry are both left out', async () => {+ it('offers installed plugins except explicit opt-outs in mixed-shape configurations', async () => {mockGetAgentConfig.mockResolvedValue({chatConfig: {},id: 'agent-1',model: 'gpt-4',// legacy string (implicit pinned) + explicit disabled object + explicit- // auto object; plugin-d has no entry, which is off+ // auto object; plugin-d inherits on-demand discoveryplugins: ['plugin-a',{ identifier: 'plugin-b', mode: 'disabled' },@@ -259,15 +259,15 @@ describe('AiAgentService.execAgent - agent plugin entries (on / off / disabled)'await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);const installed = installedPluginsArg().map((p) => p.identifier);- expect(installed).toEqual(['plugin-a', 'plugin-c']);+ expect(installed).toEqual(['plugin-a', 'plugin-c', 'plugin-d']);expect(installed).not.toContain('plugin-b');- expect(installed).not.toContain('plugin-d');+ expect(installed).toContain('plugin-d');// The activator's map follows the same cut.expect(Object.keys(toolManifestMapArg())).toEqual(- expect.arrayContaining(['plugin-a', 'plugin-c']),+ expect.arrayContaining(['plugin-a', 'plugin-c', 'plugin-d']),);expect(toolManifestMapArg()).not.toHaveProperty('plugin-b');- expect(toolManifestMapArg()).not.toHaveProperty('plugin-d');+ expect(toolManifestMapArg()).toHaveProperty('plugin-d');});it('keeps pinned plugins and pinned on-demand builtins out of the engine agentConfig.plugins in Agent mode', async () => {@@ -288,7 +288,11 @@ describe('AiAgentService.execAgent - agent plugin entries (on / off / disabled)'// A pinned entry is on: found through the activator, not invoked up front.expect(agentConfigPluginsArg()).toEqual([]);- expect(installedPluginsArg().map((p) => p.identifier)).toEqual(['plugin-a']);+ expect(installedPluginsArg().map((p) => p.identifier)).toEqual([+ 'plugin-a',+ 'plugin-c',+ 'plugin-d',+ ]);expect(toolManifestMapArg()).toHaveProperty('plugin-a');expect(disabledPluginIdsArg()).toContain('plugin-b');// Both the legacy pin and the implicit default remain discoverable.@@ -330,13 +334,17 @@ describe('AiAgentService.execAgent - agent plugin entries (on / off / disabled)'await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);expect(agentConfigPluginsArg()).toEqual([]);- expect(installedPluginsArg().map((p) => p.identifier)).toEqual(['plugin-a', 'plugin-c']);+ expect(installedPluginsArg().map((p) => p.identifier)).toEqual([+ 'plugin-a',+ 'plugin-c',+ 'plugin-d',+ ]);expect(disabledPluginIdsArg()).toContain('plugin-b');expect(disabledPluginIdsArg()).not.toContain('plugin-a');expect(disabledPluginIdsArg()).not.toContain('plugin-c');});- it('reads a pure string array as the plugins that are on, leaving every other installed plugin off', async () => {+ it('keeps unlisted installed plugins discoverable alongside legacy string entries', async () => {mockGetAgentConfig.mockResolvedValue({chatConfig: {},id: 'agent-1',@@ -349,14 +357,14 @@ describe('AiAgentService.execAgent - agent plugin entries (on / off / disabled)'await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);const installed = installedPluginsArg().map((p) => p.identifier);- expect(installed).toEqual(['plugin-a']);+ expect(installed).toEqual(['plugin-a', 'plugin-b', 'plugin-c', 'plugin-d']);expect(agentConfigPluginsArg()).toEqual([]);expect(disabledPluginIdsArg()).not.toContain('plugin-a');expect(disabledPluginIdsArg()).not.toContain('lobe-creds');});- it('brings in a plugin the agent has off on the turn that @-mentions it', async () => {+ it('injects the mentioned plugin while other inherited plugins stay discoverable', async () => {mockGetAgentConfig.mockResolvedValue({chatConfig: {},id: 'agent-1',@@ -372,7 +380,12 @@ describe('AiAgentService.execAgent - agent plugin entries (on / off / disabled)'selectedToolIds: ['plugin-d'],} as any);- expect(installedPluginsArg().map((p) => p.identifier)).toEqual(['plugin-d']);+ expect(installedPluginsArg().map((p) => p.identifier)).toEqual([+ 'plugin-a',+ 'plugin-b',+ 'plugin-c',+ 'plugin-d',+ ]);expect(agentConfigPluginsArg()).toEqual(['plugin-d']);});@@ -416,12 +429,12 @@ describe('AiAgentService.execAgent - agent plugin entries (on / off / disabled)'mockGetComposioManifests.mockResolvedValue([toolManifest('composio-disabled'),toolManifest('composio-on'),- toolManifest('composio-off'),+ toolManifest('composio-inherited'),]);mockGetLobehubSkillManifests.mockResolvedValue([toolManifest('skill-disabled'),toolManifest('skill-on'),- toolManifest('skill-off'),+ toolManifest('skill-inherited'),]);await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);@@ -430,9 +443,9 @@ describe('AiAgentService.execAgent - agent plugin entries (on / off / disabled)'// the disabled entry's doing rather than an empty source.expect(toolManifestMapArg()).toHaveProperty('composio-on');expect(toolManifestMapArg()).toHaveProperty('skill-on');- // No entry is off, the same as disabled for a connector.- expect(toolManifestMapArg()).not.toHaveProperty('composio-off');- expect(toolManifestMapArg()).not.toHaveProperty('skill-off');+ // Connections without an entry are available on demand.+ expect(toolManifestMapArg()).toHaveProperty('composio-inherited');+ expect(toolManifestMapArg()).toHaveProperty('skill-inherited');// The disabled entries must not resurface in the map the activator uses// to build <available_tools> β even though they're excluded from thediff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorTokenRefresh.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorTokenRefresh.test.tsindex 2221f854fc2..a92de45440e 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@@ -72,6 +72,7 @@ const oauthConnector = {mcpServerUrl: 'https://app.xmind.com/api/mcp',metadata: {},name: 'XMind',+ status: 'connected',oidcConfig: { clientId: 'client', scheme: 'dcr' },};@@ -88,6 +89,7 @@ const connectorTools = [interface RunOptions {/** The agent's `auto` entries: on without a legacy pin. */autoSkillIds?: string[];+ disabledPluginIds?: string[];/** The agent's legacy pinned entries, which also read as on. */plugins?: string[];/** This turn's @-mention picks. */@@ -137,7 +139,7 @@ const run = (options: RunOptions = {}) => {},} as never,{- disabledPluginIds: [],+ disabledPluginIds: options.disabledPluginIds ?? [],globalMemoryEnabled: false,hasMentionedAgents: false,isFixedDeviceTarget: false,@@ -172,13 +174,17 @@ describe('discoverTools β connector OAuth token refresh', () => {},);- it('neither resolves nor refreshes a connector the agent never turned on', async () => {+ it('excludes a disabled connector before refreshing credentials', async () => {vi.mocked(refreshExpiredLinkTokens).mockClear();- const result = await run();+ const result = await run({ disabledPluginIds: [XMIND] });expect(result.toolManifestMap[XMIND]).toBeUndefined();- expect(connectorModel.resolveAll).not.toHaveBeenCalled();+ expect(connectorModel.resolveAll).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ expect.arrayContaining([XMIND]),+ );expect(connectorModel.resolveByIdentifiers).not.toHaveBeenCalled();expect(refreshExpiredLinkTokens).not.toHaveBeenCalled();});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.tsindex e71fe46e34e..38b2b8fffc6 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@@ -74,6 +74,7 @@ interface RunOptions {chatConfig?: Record<string, unknown>;/** Override the connector's transport (`http` by default). */connection?: { mcpConnectionType: string; mcpServerUrl: string | null };+ disabledPluginIds?: string[];installed?: boolean;metadata?: Record<string, unknown>;/** The agent's legacy pinned entries, which also read as on. */@@ -139,7 +140,7 @@ const run = (options: RunOptions = {}) => {shareGate: options.shareGate,} as never,{- disabledPluginIds: [],+ disabledPluginIds: options.disabledPluginIds ?? [],globalMemoryEnabled: false,hasMentionedAgents: false,isFixedDeviceTarget: false,@@ -165,7 +166,7 @@ const offeredToolNames = (result: { tools?: { function: { name: string } }[] })/** The agent turned the connector on: an `auto` entry in its plugins. */const ON = { autoSkillIds: [YINGMI] };-describe('discoverTools β custom MCP connectors are opt-in per agent', () => {+describe('discoverTools β custom MCP connector discovery', () => {it.each([ON,{ plugins: [YINGMI] },@@ -295,14 +296,17 @@ describe('discoverTools β custom MCP connectors are opt-in per agent', () => {expect(result.toolManifestMap[YINGMI]).toBeUndefined();});- it('keeps a connector the agent never turned on out of the run', async () => {- const result = await run();+ it('keeps an explicitly disabled connector out of the run', async () => {+ const result = await run({ disabledPluginIds: [YINGMI] });expect(result.toolManifestMap[YINGMI]).toBeUndefined();expect(result.toolSourceMap[YINGMI]).toBeUndefined();expect(result.toolsResult.enabledToolIds).not.toContain(YINGMI);- // Off means never read: its credentials are not decrypted for this run.- expect(connectorModel.resolveAll).not.toHaveBeenCalled();+ expect(connectorModel.resolveAll).toHaveBeenCalledWith(+ expect.anything(),+ gateKeeper,+ expect.arrayContaining([YINGMI]),+ );expect(connectorModel.resolveByIdentifiers).not.toHaveBeenCalled();// β¦and a previous turn's activation cannot bring it back.const restored = result.toolsEngine!.generateToolsDetailed(explicitConnectorInput(YINGMI));@@ -310,6 +314,7 @@ describe('discoverTools β custom MCP connectors are opt-in per agent', () => {});it.each([+ { label: 'inherits', options: {} },{ label: 'turned on', options: ON },{ label: 'pinned', options: { plugins: [YINGMI] } },])('keeps a connector the agent $label discoverable without enabling it', async ({ options }) => {@@ -317,11 +322,6 @@ describe('discoverTools β custom MCP connectors are opt-in per agent', () => {// activator used to answer "Not found: yingmi" here.const result = await run(options);- // Resolved by identifier only β never the user's whole connector list.- expect(connectorModel.resolveAll).not.toHaveBeenCalled();- expect(connectorModel.resolveByIdentifiers).toHaveBeenCalledTimes(1);- expect(connectorModel.resolveByIdentifiers.mock.calls[0][0]).toEqual([YINGMI]);-expect(result.toolManifestMap[YINGMI]).toBeDefined();expect(result.toolSourceMap[YINGMI]).toBe('mcp');expect(availableToolIds(result.toolManifestMap, result.toolsResult.enabledToolIds)).toContain(@@ -374,10 +374,10 @@ describe('discoverTools β custom MCP connectors are opt-in per agent', () => {).toEqual([]);});- it('keeps a connector the agent never turned on out of a manual-mode run too', async () => {+ it('keeps an inherited connector discoverable with the retired manual preference', async () => {const result = await run({ chatConfig: { skillActivateMode: 'manual' } });- expect(result.toolManifestMap[YINGMI]).toBeUndefined();+ expect(result.toolManifestMap[YINGMI]).toBeDefined();expect(result.toolsResult.enabledToolIds).not.toContain(YINGMI);});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.tsindex 149f0e4ceb6..9917d981722 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@@ -185,7 +185,7 @@ describe('Agent first-turn tool payload', () => {);});-describe('discoverTools β installed plugins are opt-in per agent', () => {+describe('discoverTools β installed plugin discovery', () => {// This server fixture has no device and no optional feature flags.const availableBuiltins = onDemandBuiltinToolIds.filter((id) => id !== AuvManifest.identifier && isToolEnabledByFeatureFlags(id, {}),@@ -213,8 +213,8 @@ describe('discoverTools β installed plugins are opt-in per agent', () => {expect(activate(off.toolsEngine).enabledToolIds).not.toContain(id);});- it('keeps an installed plugin the agent never turned on out of the run', async () => {- const result = await run();+ it('keeps a disabled installed plugin out of the run', async () => {+ const result = await run({ disabledPluginIds: [FEISHU] });expect(result.toolManifestMap[FEISHU]).toBeUndefined();expect(result.toolsResult.enabledToolIds).not.toContain(FEISHU);@@ -225,6 +225,7 @@ describe('discoverTools β installed plugins are opt-in per agent', () => {});it.each([+ { label: 'inherits', options: {} },{ label: 'turned on', options: ON },{ label: 'turned on with an old manual preference', options: { ...ON, ...MANUAL } },{ label: 'pinned with an old manual preference', options: { ...MANUAL, plugins: [FEISHU] } },@@ -268,7 +269,7 @@ describe('discoverTools β installed plugins are opt-in per agent', () => {});it('keeps an installed plugin that is off out of a manual-mode run', async () => {- const result = await run(MANUAL);+ const result = await run({ ...MANUAL, disabledPluginIds: [FEISHU] });expect(result.toolManifestMap[FEISHU]).toBeUndefined();expect(result.toolsResult.enabledToolIds).not.toContain(FEISHU);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.tsindex a5d0a4c72ad..5fac4bfbd45 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@@ -133,8 +133,8 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/connector', () => ({ConnectorModel: vi.fn().mockImplementation(function () {return {- queryByIdentifiers: vi.fn().mockResolvedValue([]),- resolveByIdentifiers: reads.connectors,+ resolveAll: reads.connectors,+ resolveByIdentifiers: vi.fn().mockResolvedValue([]),};}),}));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.tsindex 6d92e9041d7..b46d68cf353 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@@ -324,7 +324,7 @@ describe('discoverTools β connector permissions and ownership', () => {});});-describe('discoverTools β connectors are opt-in per agent', () => {+describe('discoverTools β connector discovery', () => {const plugin = (identifier: string) => ({customParams: {},identifier,@@ -342,14 +342,12 @@ describe('discoverTools β connectors are opt-in per agent', () => {(p: any) => p.identifier,);- it('keeps a connector the agent never turned on out of the run', async () => {+ it('offers connected services and installed plugins to an ordinary agent by default', async () => {const result = await run(sources).promise;-- expect(engineManifestIds()).toEqual([]);- expect(engineInstalledIds()).toEqual([]);- expect(result.lobehubSkillManifests).toEqual([]);- expect(result.composioManifests).toEqual([]);- expect(Object.keys(result.toolManifestMap)).not.toContain('community-mcp');+ for (const id of ['lobehub-notion', 'composio-gmail', 'community-mcp']) {+ expect(result.toolManifestMap).toHaveProperty(id);+ expect(result.toolsResult.enabledToolIds).not.toContain(id);+ }});it('lets a connector that is on be discovered without invoking it up front', async () => {@@ -371,23 +369,23 @@ describe('discoverTools β connectors are opt-in per agent', () => {agentConfig: { plugins: ['lobehub-notion', 'community-mcp', 'lobe-image-generation'] },}).promise;- expect(engineManifestIds()).toEqual(['lobehub-notion']);+ expect(engineManifestIds()).toEqual(['lobehub-notion', 'composio-gmail']);expect(engineInstalledIds()).toEqual(['community-mcp']);// A pinned builtin tool keeps its pin; only connectors lost that state.expect(result.agentPlugins).toEqual(['lobe-image-generation']);});- it('resolves only the connectors that are on as discoverable', async () => {+ it('limits connector discovery to the custom toolset', async () => {const resolveByIdentifiers = vi.fn((_ids: string[]) => []);await run({...sources,+ agentConfig: { chatConfig: { toolMode: 'custom' }, plugins: ['lobe-activator'] },autoSkillIds: ['custom-mcp'],connectorResolve: resolveByIdentifiers,}).promise;- expect(resolveByIdentifiers).toHaveBeenCalledTimes(1);- expect(resolveByIdentifiers.mock.calls[0][0]).toEqual(['custom-mcp']);+ expect(resolveByIdentifiers).toHaveBeenCalledWith(['lobe-activator', 'custom-mcp']);});it('keeps opted-in connectors discoverable despite a legacy manual preference', async () => {@@ -399,7 +397,7 @@ describe('discoverTools β connectors are opt-in per agent', () => {expect(result.agentPlugins).toEqual([]);expect(engineInstalledIds()).toEqual(['community-mcp']);- expect(engineManifestIds()).toEqual(['lobehub-notion']);+ expect(engineManifestIds()).toEqual(['lobehub-notion', 'composio-gmail']);});it('invokes a connector that is on directly in custom mode, which has no activator either', async () => {diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.tsindex 6077d6b06e2..cbbd06e1d17 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts@@ -29,7 +29,7 @@ import {resolveInvocationToolIds,} from '@lobechat/mecha';import type { BuiltinToolResolveContext, FrozenCredentialFacts } from '@lobechat/types';-import { getActivePluginIds } from '@lobechat/types';+import { getActivePluginIds, resolveToolMode } from '@lobechat/types';import debug from 'debug';import { loadModels } from '@/business/client/model-bank/loadModels';@@ -217,15 +217,18 @@ export const discoverTools = async (agentPlugins = filterPluginsByShareGate(agentPlugins, shareGate);}- // Connectors are opt-in per agent and two-state (see- // `resolveConnectorActivation`): on is every entry that is not disabled, off- // is everything else. An exact toolset (verify agent, goal supervisor) names+ // Connected tools are discoverable by default in ordinary agent runs.+ // An exact toolset (verify agent, goal supervisor) names// its tools itself, so the agent's switches do not apply to it.const optedInIds = [...getActivePluginIds(agentConfig?.plugins), ...(ctx.autoSkillIds ?? [])];+ const discoverByDefault =+ resolveToolMode(agentConfig.chatConfig) === 'agent' && !evalConnectorSnapshots;const connectorActivation =exclusivePluginIds || isGoalTurn? undefined: resolveConnectorActivation({+ disabledIds: disabledPluginIds,+ discoverByDefault,hasActivator: hasConnectorActivator(agentConfig.chatConfig,agentPlugins,@@ -282,8 +285,9 @@ export const discoverTools = async (exclusivePluginIds ?? (evalConnectorSnapshots ? agentPlugins : undefined),isGoalTurn,// A share run reads what the share grants instead.+ disabledPluginIds,optedInExtensionIds:- connectorActivation && !shareGate+ connectorActivation && !shareGate && !discoverByDefault? new Set(optedInIds.filter((identifier) => !disabledPluginIds.includes(identifier))): undefined,projectId: appContext?.projectId,@@ -314,8 +318,7 @@ export const discoverTools = async (// A share run keeps only granted plugins, so an ungranted one never reaches// the connector permission lookup or the activator pool below.const disabledPluginIdSet = new Set(disabledPluginIds);- // A connector the agent has not turned on is off for it: it leaves every- // connector source here, so neither the engine nor the activator sees it.+ // Apply per-agent overrides to every connector source.// A share run is cut to its grants above instead.const isConnectorOn = (identifier: string) =>!connectorActivation || !!shareGate || connectorActivation.isAllowed(identifier);diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.tsindex e4c0da45a3c..ec0297bc610 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts@@ -59,13 +59,12 @@ export interface ToolReadsContext {* resolution or the stale-tools refresh.*/candidateIds: string[];+ disabledPluginIds?: string[];exclusivePluginIds?: string[];isGoalTurn: boolean;/**- * The identifiers the agent turned on. A connector is opt-in per agent, so- * only these are resolved as discoverable; an off connector never has its- * credentials decrypted. `undefined` = no opt-in cut (an exact toolset, or a- * share run, which reads `shareGrantedExtensionIds` instead).+ * Explicit connector allowlist for custom toolsets. Ordinary agents use their+ * scoped connections, and shared agents use their grants.*/optedInExtensionIds?: Set<string>;/** Project the run belongs to (`appContext.projectId`). */@@ -285,11 +284,19 @@ const readDiscoverableConnectors = async (const [resolved, installedIds] = await Promise.all([unresolvedIds? deps.connectorModel.resolveByIdentifiers(unresolvedIds, ctx.resolvedAgentId, gateKeeper)- : deps.connectorModel.resolveAll(ctx.resolvedAgentId, gateKeeper),+ : deps.connectorModel.resolveAll(ctx.resolvedAgentId, gateKeeper, [+ ...candidates,+ ...(ctx.disabledPluginIds ?? []),+ ]),installedPluginIds,]);const connectorsMcp = filterInstalledMarketplaceConnectors(resolved, installedIds).filter(- (c) => !candidates.has(c.identifier) && hasCallableMcpEndpoint(c),+ (c) =>+ !candidates.has(c.identifier) &&+ !ctx.disabledPluginIds?.includes(c.identifier) &&+ c.isEnabled &&+ c.status === 'connected' &&+ hasCallableMcpEndpoint(c),);if (connectorsMcp.length === 0) return none;diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pluginResolution.marketInstall.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pluginResolution.marketInstall.test.tsindex 5e53877c34c..c5f1cd9c110 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pluginResolution.marketInstall.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pluginResolution.marketInstall.test.ts@@ -90,6 +90,7 @@ const installFromServer = ();interface NextRunOptions {+ disabledPluginIds?: string[];/** Manual skill-activate mode: the run has no activator. */manual?: boolean;/** The agent's `plugins`; the install pins the MCP on the agent by default. */@@ -129,7 +130,7 @@ const nextRun = (options: NextRunOptions = {}) =>},} as never,{- disabledPluginIds: [],+ disabledPluginIds: options.disabledPluginIds ?? [],globalMemoryEnabled: false,hasMentionedAgents: false,isFixedDeviceTarget: false,@@ -248,14 +249,20 @@ describe('resolveOrInstallMarketPlugin β server-side marketplace install', ()},);- it('keeps the install out of the run of an agent that has not turned it on', async () => {+ it('offers an inherited install on demand and honors an explicit opt-out', async () => {await installFromServer();const run = await nextRun({ plugins: [] });- expect(run.toolManifestMap[IDENTIFIER]).toBeUndefined();+ expect(run.toolManifestMap[IDENTIFIER]?.api).toEqual([+ expect.objectContaining({ name: 'fetch' }),+ ]);expect(run.toolsResult.enabledToolIds).not.toContain(IDENTIFIER);expect(offeredToolNames(run.tools)).not.toContain(TOOL_NAME);++ const off = await nextRun({ disabledPluginIds: [IDENTIFIER], plugins: [] });+ expect(off.toolManifestMap[IDENTIFIER]).toBeUndefined();+ expect(offeredToolNames(off.tools)).not.toContain(TOOL_NAME);});it('refuses a stdio MCP the market does not host, writing nothing', async () => {diff --git a/packages/database/src/models/__tests__/connectorAgentScope.test.ts b/packages/database/src/models/__tests__/connectorAgentScope.test.tsindex 33c4a0372b2..6348fc2897f 100644--- a/packages/database/src/models/__tests__/connectorAgentScope.test.ts+++ b/packages/database/src/models/__tests__/connectorAgentScope.test.ts@@ -243,6 +243,8 @@ 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']);+ expect(optedOut.map((r) => r.identifier)).toEqual(['notion']);});});diff --git a/packages/database/src/models/connector.ts b/packages/database/src/models/connector.tsindex 5f42585fdca..72d688375e5 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, or, sql } from 'drizzle-orm';+import { and, asc, eq, inArray, isNotNull, isNull, notInArray, or, sql } from 'drizzle-orm';import pMap from 'p-map';import type { ConnectorCredentials, NewUserConnector, UserConnectorItem } from '../schemas';@@ -654,12 +654,20 @@ 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(this.scopePredicate(target))+ .where(+ and(+ this.scopePredicate(target),+ excludedIdentifiers.length+ ? notInArray(userConnectors.identifier, excludedIdentifiers)+ : undefined,+ ),+ ).orderBy(...this.resolutionOrder());return pMap(this.pickByPriority(rows, target.agentId), (r) => decryptRow(r, gateKeeper), {diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.tsindex 5778b26310d..7b223a8eb58 100644--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts@@ -147,7 +147,7 @@ describe('gatherContextFacts', () => {expect(off.variables.COMPOSIO_SERVICES_LIST).toBe('');const on = await gatherContextFacts(- request({ disabledPluginIds: ['slack'], enabledToolIds: ['lobe-creds'] }),+ request({ disabledPluginIds: ['slack'], enabledToolIds: ['lobe-creds', 'gmail'] }),{ listConnectedConnectorIds },);const list = on.variables.COMPOSIO_SERVICES_LIST as string;@@ -155,11 +155,11 @@ describe('gatherContextFacts', () => {expect(list).not.toContain('slack');});- it('does not offer a connected Composio service the agent has not turned on', async () => {+ it('lists connected Composio services available for this run to activate', async () => {const listConnectedConnectorIds = vi.fn(async () => ['gmail', 'slack']);const facts = await gatherContextFacts(- request({ enabledToolIds: ['lobe-creds'], optedInPluginIds: ['gmail'] }),+ request({ enabledToolIds: ['lobe-creds'], discoverableTools: [{ identifier: 'gmail' }] }),{ listConnectedConnectorIds },);const list = facts.variables.COMPOSIO_SERVICES_LIST as string;diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.tsindex d906ad64f2c..c5daf59ce65 100644--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts@@ -332,12 +332,13 @@ const gatherComposioServices = async (// Disabled services are dropped from both lists β neither "connected, use// directly" nor "available to connect" β the agent isn't meant to see them.const disabledIdSet = new Set(request.disabledPluginIds ?? []);- // A connector is opt-in per agent: a service that is connected but that this- // agent has not turned on cannot be reached, so it is not listed as usable.- const optedIn = request.optedInPluginIds && new Set(request.optedInPluginIds);+ const reachable = new Set([+ ...request.enabledToolIds,+ ...(request.discoverableTools ?? []).map((tool) => tool.identifier),+ ]);const connected: ComposioServiceSummary[] = excludeDisabledComposioServices(COMPOSIO_APP_TYPES.filter(- (tool) => connectedIds.has(tool.identifier) && (!optedIn || optedIn.has(tool.identifier)),+ (tool) => connectedIds.has(tool.identifier) && reachable.has(tool.identifier),),disabledIdSet,).map((tool) => ({ identifier: tool.identifier, name: tool.label }));diff --git a/packages/mecha/src/contextEngineering/facts/types.ts b/packages/mecha/src/contextEngineering/facts/types.tsindex 3ad5b995431..aeba6cf200f 100644--- a/packages/mecha/src/contextEngineering/facts/types.ts+++ b/packages/mecha/src/contextEngineering/facts/types.ts@@ -116,12 +116,6 @@ export interface ContextFactRequest {mentionedAgents?: RuntimeMentionedAgent[];/** Conversation as the engine will see it (history hints already applied). */messages: UIChatMessage[];- /**- * Identifiers the agent turned on (every `plugins` entry that is not- * disabled). A connector is opt-in per agent, so a connected service absent- * from it is not offered as usable. Omitted = no opt-in cut.- */- optedInPluginIds?: string[];/** Present only on a shared-agent visitor run. */shareVisitor?: Pick<AgentShareVisitorContext, 'agentId' | 'visitorUserId'>;topicId?: string;diff --git a/packages/mecha/src/toolSet/connectorActivation.test.ts b/packages/mecha/src/toolSet/connectorActivation.test.tsindex ed2e4313e62..0654629a31f 100644--- a/packages/mecha/src/toolSet/connectorActivation.test.ts+++ b/packages/mecha/src/toolSet/connectorActivation.test.ts@@ -28,7 +28,19 @@ describe('hasConnectorActivator', () => {});describe('resolveConnectorActivation', () => {- it('leaves a connector the agent never turned on out of reach', () => {+ it('offers inherited connections on demand and respects an explicit opt-out', () => {+ const activation = resolveConnectorActivation({+ disabledIds: ['slack'],+ discoverByDefault: true,+ hasActivator: true,+ optedInIds: [],+ });+ expect(activation.isAllowed('notion')).toBe(true);+ expect(activation.isInjected('notion')).toBe(false);+ expect(activation.isAllowed('slack')).toBe(false);+ });++ it('requires an explicit entry for a custom toolset', () => {const activation = resolveConnectorActivation({ hasActivator: true, optedInIds: ['gmail'] });expect(activation.isAllowed('gmail')).toBe(true);diff --git a/packages/mecha/src/toolSet/connectorActivation.ts b/packages/mecha/src/toolSet/connectorActivation.tsindex d884e6b3e34..9e23c7346cf 100644--- a/packages/mecha/src/toolSet/connectorActivation.ts+++ b/packages/mecha/src/toolSet/connectorActivation.ts@@ -16,6 +16,9 @@ export const hasConnectorActivator = (};export interface ConnectorActivationRequest {+ disabledIds?: Iterable<string>;+ /** Ordinary agent runs can discover connections without a saved switch. */+ discoverByDefault?: boolean;/*** The run has the activator, so a connector can be found on demand (see* {@link hasConnectorActivator}). Without it a connector that is on has no@@ -24,7 +27,7 @@ export interface ConnectorActivationRequest {hasActivator: boolean;/*** Identifiers the agent turned on β every `plugins` entry that is not- * disabled. A connector absent from it is off for this agent.+ * disabled. Exact toolsets only allow these and turn-scoped additions.*/optedInIds: Iterable<string>;/**@@ -44,7 +47,7 @@ export interface ConnectorActivation {/*** Connectors β MCP connectors, Composio and LobeHub connections, installed- * plugins β are opt-in per agent and have two states. On means the model finds+ * plugins β have two states. On means the model finds* the connector on demand through the activator; off means the run never sees* it. Both runtimes apply this one rule to the connector identifiers they hold;* builtin tools and skills keep their own three-state policy.@@ -53,12 +56,16 @@ export const resolveConnectorActivation = (request: ConnectorActivationRequest,): ConnectorActivation => {const optedIn = new Set(request.optedInIds);+ const disabled = new Set(request.disabledIds);const turn = new Set(request.turnIds ?? []);return {- isAllowed: (identifier) => optedIn.has(identifier) || turn.has(identifier),+ isAllowed: (identifier) =>+ turn.has(identifier) ||+ (!disabled.has(identifier) && (optedIn.has(identifier) || !!request.discoverByDefault)),isInjected: (identifier) =>- turn.has(identifier) || (!request.hasActivator && optedIn.has(identifier)),+ turn.has(identifier) ||+ (!request.hasActivator && !disabled.has(identifier) && optedIn.has(identifier)),};};diff --git a/packages/types/src/agent/pluginConfig.test.ts b/packages/types/src/agent/pluginConfig.test.tsindex 820f8a2b6da..0525a302afc 100644--- a/packages/types/src/agent/pluginConfig.test.ts+++ b/packages/types/src/agent/pluginConfig.test.ts@@ -10,6 +10,7 @@ import {getPinnedPluginIds,getPluginMode,parsePluginEntry,+ shouldEnableConnectorOnConnect,upsertConnectorEnabled,upsertPluginMode,} from './pluginConfig';@@ -190,9 +191,23 @@ describe('library skills', () => {});describe('connectors', () => {- it('resolves a connector the agent has no entry for as off', () => {- expect(getConnectorMode(undefined, 'gmail')).toBe('disabled');- expect(getConnectorMode(['other'], 'gmail')).toBe('disabled');+ it('only enrolls a newly connected tool for an exact toolset without a saved choice', () => {+ expect(shouldEnableConnectorOnConnect([], 'notion')).toBe(false);+ const custom = { toolMode: 'custom' } as const;+ expect(shouldEnableConnectorOnConnect([], 'notion', custom)).toBe(true);+ expect(+ shouldEnableConnectorOnConnect(+ [{ identifier: 'notion', mode: 'disabled' }],+ 'notion',+ custom,+ ),+ ).toBe(false);+ });++ it('defaults a connected tool to on demand in Agent mode and preserves custom toolsets', () => {+ expect(getConnectorMode(undefined, 'gmail')).toBe('auto');+ expect(getConnectorMode(undefined, 'gmail', { toolMode: 'custom' })).toBe('disabled');+ expect(getConnectorMode(['other'], 'gmail')).toBe('auto');});it('reads an explicit auto entry as on and a disabled entry as off', () => {diff --git a/packages/types/src/agent/pluginConfig.ts b/packages/types/src/agent/pluginConfig.tsindex d09184e2d6b..a2b2ec6d3bc 100644--- a/packages/types/src/agent/pluginConfig.ts+++ b/packages/types/src/agent/pluginConfig.ts@@ -1,5 +1,7 @@import { z } from 'zod';+import { resolveToolMode } from './executionTargetRules';+/*** Three-state per-agent plugin config.*@@ -75,11 +77,10 @@ export const getLibrarySkillMode = (/*** Connectors β the user's MCP connectors, Composio and LobeHub connections and- * installed plugins β are opt-in per agent and have two states. The agent's- * profile is where one is turned on, so a connector the agent has no entry for- * is off there, exactly like a library skill.+ * installed plugins β are discoverable by default in agent mode. Custom+ * toolsets only include their explicitly configured connectors.*/-export const CONNECTOR_IMPLICIT_MODE: AgentPluginMode = 'disabled';+export const CONNECTOR_IMPLICIT_MODE = 'auto' as const;/** The mode the two-state connector switch writes for "on". */export const CONNECTOR_ON_MODE: AgentPluginMode = 'auto';@@ -92,12 +93,22 @@ export const CONNECTOR_ON_MODE: AgentPluginMode = 'auto';export const getConnectorMode = (plugins: AgentPluginEntry[] | undefined,identifier: string,+ chatConfig?: Parameters<typeof resolveToolMode>[0],): 'auto' | 'disabled' => {const entry = plugins?.find((item) => parsePluginEntry(item).identifier === identifier);- if (!entry) return 'disabled';+ if (!entry) return resolveToolMode(chatConfig) === 'agent' ? CONNECTOR_IMPLICIT_MODE : 'disabled';return parsePluginEntry(entry).mode === 'disabled' ? 'disabled' : 'auto';};+/** A connection initiated from an exact toolset needs an entry unless the agent already chose a mode. */+export const shouldEnableConnectorOnConnect = (+ plugins: AgentPluginEntry[] | undefined,+ identifier: string,+ chatConfig?: Parameters<typeof resolveToolMode>[0],+): boolean =>+ resolveToolMode(chatConfig) !== 'agent' &&+ !plugins?.some((entry) => parsePluginEntry(entry).identifier === identifier);+const getPluginIdsByMode = (plugins: AgentPluginEntry[] | undefined,mode: AgentPluginMode,@@ -110,11 +121,7 @@ const getPluginIdsByMode = (export const getPinnedPluginIds = (plugins: AgentPluginEntry[] | undefined): string[] =>getPluginIdsByMode(plugins, 'pinned');-/**- * Identifiers carrying an explicit `{ mode: 'auto' }` entry. Only library- * skills persist one (see {@link LIBRARY_SKILL_IMPLICIT_MODE}); for everything- * else `'auto'` is the absence of an entry.- */+/** Identifiers explicitly configured for on-demand activation. */export const getAutoPluginIds = (plugins: AgentPluginEntry[] | undefined): string[] =>getPluginIdsByMode(plugins, 'auto');@@ -123,8 +130,7 @@ export const getDisabledPluginIds = (plugins: AgentPluginEntry[] | undefined): s/*** Every identifier the agent turned on, pinned or `auto`. This is the opt-in- * list for the kinds that are off without an entry β library skills and- * connectors ({@link CONNECTOR_IMPLICIT_MODE}).+ * list for library skills and explicitly configured toolsets.*/export const getOptedInPluginIds = (plugins: AgentPluginEntry[] | undefined): string[] =>(plugins ?? [])@@ -181,7 +187,7 @@ export const upsertPluginMode = (/*** Writes the two-state connector switch. On is an explicit `auto` entry β- * without one the connector is off. Off keeps a `disabled` entry rather than+ * including for custom toolsets. Off keeps a `disabled` entry rather than* dropping it, so the connector stays listed on the agent and can be turned* back on; removing it from the agent is `upsertPluginMode(β¦, 'auto')`.*/@@ -191,5 +197,5 @@ export const upsertConnectorEnabled = (enabled: boolean,): AgentPluginEntry[] =>enabled- ? upsertPluginMode(plugins, identifier, CONNECTOR_ON_MODE, CONNECTOR_IMPLICIT_MODE)+ ? upsertPluginMode(plugins, identifier, CONNECTOR_ON_MODE, 'disabled'): upsertPluginMode(plugins, identifier, 'disabled');diff --git a/src/features/AgentSetting/AgentConnectors/index.tsx b/src/features/AgentSetting/AgentConnectors/index.tsxindex 4d840993dc6..fd4f85fab78 100644--- a/src/features/AgentSetting/AgentConnectors/index.tsx+++ b/src/features/AgentSetting/AgentConnectors/index.tsx@@ -1,4 +1,4 @@-import { getConnectorMode } from '@lobechat/types';+import { getConnectorMode, upsertConnectorEnabled } from '@lobechat/types';import { Switch } from '@lobehub/ui';import { LinkIcon } from 'lucide-react';import { memo, useEffect } from 'react';@@ -12,9 +12,10 @@ import { useStore } from '../store';const AgentConnectors = memo(() => {const { t } = useTranslation('setting');- const [agentPlugins, toggleAgentPlugin] = useStore((s) => [+ const [agentPlugins, chatConfig, setAgentConfig] = useStore((s) => [s.config.plugins,- s.toggleAgentPlugin,+ s.config.chatConfig,+ s.setAgentConfig,]);const connectors = useToolStore(connectorSelectors.connectorList);@@ -38,8 +39,9 @@ const AgentConnectors = memo(() => {return (<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>{connectors.map((connector) => {- // A connector is two-state: on is any entry that is not disabled.- const isEnabled = getConnectorMode(agentPlugins, connector.identifier) === 'auto';+ const isConnected = connector.isEnabled && connector.status === 'connected';+ const isEnabled =+ getConnectorMode(agentPlugins, connector.identifier, chatConfig) === 'auto';const enabledCount = connector.tools.filter((t) => t.permission !== 'disabled').length;return (@@ -61,9 +63,14 @@ const AgentConnectors = memo(() => {</div></div><Switch- checked={isEnabled}+ checked={isConnected && isEnabled}+ disabled={!isConnected}size="small"- onChange={() => toggleAgentPlugin(connector.identifier, !isEnabled)}+ onChange={() =>+ setAgentConfig({+ plugins: upsertConnectorEnabled(agentPlugins, connector.identifier, !isEnabled),+ })+ }/></div>);diff --git a/src/features/ChatInput/ActionBar/Tools/ComposioServerItem.tsx b/src/features/ChatInput/ActionBar/Tools/ComposioServerItem.tsxindex a2e081e8573..410fef7cf26 100644--- a/src/features/ChatInput/ActionBar/Tools/ComposioServerItem.tsx+++ b/src/features/ChatInput/ActionBar/Tools/ComposioServerItem.tsx@@ -1,4 +1,8 @@-import { getConnectorMode, upsertConnectorEnabled, upsertPluginMode } from '@lobechat/types';+import {+ getConnectorMode,+ shouldEnableConnectorOnConnect,+ upsertConnectorEnabled,+} from '@lobechat/types';import { Checkbox, Flexbox, Icon, Spin, stopPropagation } from '@lobehub/ui';import { SquareArrowOutUpRight } from 'lucide-react';import type { ReactNode } from 'react';@@ -192,23 +196,22 @@ const ComposioServerItem = memo<ComposioServerItemProps>(// Get plugin ID for this server (use identifier as pluginId)const pluginId = server ? server.identifier : '';- const plugins = useAgentStore(agentSelectors.getAgentConfigById(effectiveAgentId))?.plugins;- // A connector is two-state: on is any entry that is not disabled.- const checked = getConnectorMode(plugins, pluginId) === 'auto';+ const config = useAgentStore(agentSelectors.getAgentConfigById(effectiveAgentId));+ const plugins = config?.plugins;+ const checked = getConnectorMode(plugins, pluginId, config?.chatConfig) === 'auto';const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);// Toggle plugin for the effective agentconst togglePlugin = useCallback(- async (pluginIdToToggle: string) => {+ async (pluginIdToToggle: string, enabled: boolean) => {if (!effectiveAgentId) return;- // Turning it on writes the explicit entry; turning it off here takes it off the agent.- const isOn = getConnectorMode(plugins, pluginIdToToggle) === 'auto';- const newPlugins = isOn- ? upsertPluginMode(plugins, pluginIdToToggle, 'auto')- : upsertConnectorEnabled(plugins, pluginIdToToggle, true);+ const current = agentSelectors.getAgentConfigById(effectiveAgentId)(+ useAgentStore.getState(),+ );+ const newPlugins = upsertConnectorEnabled(current?.plugins, pluginIdToToggle, enabled);await updateAgentConfigById(effectiveAgentId, { plugins: newPlugins });},- [effectiveAgentId, plugins, updateAgentConfigById],+ [effectiveAgentId, updateAgentConfigById],);const handleConnect = async () => {@@ -234,7 +237,11 @@ const ComposioServerItem = memo<ComposioServerItemProps>(if (newServer) {// Auto-enable plugin after installation (using identifier)const newPluginId = newServer.identifier;- await togglePlugin(newPluginId);+ const current = agentSelectors.getAgentConfigById(effectiveAgentId)(+ useAgentStore.getState(),+ );+ if (shouldEnableConnectorOnConnect(current?.plugins, newPluginId, current?.chatConfig))+ await togglePlugin(newPluginId, true);// If already authenticated, refresh tool list directly, skip OAuthif (newServer.status === ComposioServerStatus.ACTIVE) {@@ -254,7 +261,7 @@ const ComposioServerItem = memo<ComposioServerItemProps>(const handleToggle = async () => {if (!canEdit || !server) return;setIsToggling(true);- await togglePlugin(pluginId);+ await togglePlugin(pluginId, !checked);setIsToggling(false);};diff --git a/src/features/ChatInput/ActionBar/Tools/LobehubSkillServerItem.tsx b/src/features/ChatInput/ActionBar/Tools/LobehubSkillServerItem.tsxindex 7dc6975bfb3..d22fc24f9df 100644--- a/src/features/ChatInput/ActionBar/Tools/LobehubSkillServerItem.tsx+++ b/src/features/ChatInput/ActionBar/Tools/LobehubSkillServerItem.tsx@@ -1,4 +1,8 @@-import { getConnectorMode, upsertConnectorEnabled, upsertPluginMode } from '@lobechat/types';+import {+ getConnectorMode,+ shouldEnableConnectorOnConnect,+ upsertConnectorEnabled,+} from '@lobechat/types';import { Checkbox, Flexbox, Icon, Spin, stopPropagation } from '@lobehub/ui';import { SquareArrowOutUpRight } from 'lucide-react';import type { ReactNode } from 'react';@@ -154,23 +158,23 @@ const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>();const pluginId = server ? server.identifier : '';- const plugins = useAgentStore(agentSelectors.getAgentConfigById(effectiveAgentId))?.plugins;- // A connector is two-state: on is any entry that is not disabled.- const checked = getConnectorMode(plugins, pluginId) === 'auto';+ const config = useAgentStore(agentSelectors.getAgentConfigById(effectiveAgentId));+ const plugins = config?.plugins;+ const checked = getConnectorMode(plugins, pluginId, config?.chatConfig) === 'auto';const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);// Toggle plugin for the effective agent- const togglePlugin = useCallback(- async (pluginIdToToggle: string) => {+ const setPluginEnabled = useCallback(+ async (identifier: string, enabled: boolean) => {if (!effectiveAgentId) return;- // Turning it on writes the explicit entry; turning it off here takes it off the agent.- const isOn = getConnectorMode(plugins, pluginIdToToggle) === 'auto';- const newPlugins = isOn- ? upsertPluginMode(plugins, pluginIdToToggle, 'auto')- : upsertConnectorEnabled(plugins, pluginIdToToggle, true);- await updateAgentConfigById(effectiveAgentId, { plugins: newPlugins });+ const current = agentSelectors.getAgentConfigById(effectiveAgentId)(+ useAgentStore.getState(),+ );+ await updateAgentConfigById(effectiveAgentId, {+ plugins: upsertConnectorEnabled(current?.plugins, identifier, enabled),+ });},- [effectiveAgentId, plugins, updateAgentConfigById],+ [effectiveAgentId, updateAgentConfigById],);// Listen for OAuth success message from popup window@@ -198,13 +202,18 @@ const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>(.lobehubSkillServers?.find((s) => s.identifier === provider);if (latestServer?.status === LobehubSkillStatus.CONNECTED) {const newPluginId = latestServer.identifier;- const currentAgentPlugins = agentSelectors.getAgentConfigById(effectiveAgentId)(+ const currentAgentConfig = agentSelectors.getAgentConfigById(effectiveAgentId)(useAgentStore.getState(),- )?.plugins;- const isAlreadyEnabled = getConnectorMode(currentAgentPlugins, newPluginId) === 'auto';- if (canEdit && !isAlreadyEnabled) {- console.info('[LobehubSkill] Auto-enabling plugin:', newPluginId);- togglePlugin(newPluginId);+ );+ if (+ canEdit &&+ shouldEnableConnectorOnConnect(+ currentAgentConfig?.plugins,+ newPluginId,+ currentAgentConfig?.chatConfig,+ )+ ) {+ await setPluginEnabled(newPluginId, true);}}}@@ -212,7 +221,7 @@ const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>(window.addEventListener('message', handleMessage);return () => window.removeEventListener('message', handleMessage);- }, [canEdit, provider, cleanup, checkStatus, togglePlugin, effectiveAgentId]);+ }, [canEdit, provider, cleanup, checkStatus, setPluginEnabled, effectiveAgentId]);const handleConnect = async () => {if (!canCreate || !canEdit) return;@@ -238,7 +247,7 @@ const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>(const handleToggle = async () => {if (!canEdit || !server) return;setIsToggling(true);- await togglePlugin(pluginId);+ await setPluginEnabled(pluginId, !checked);setIsToggling(false);};diff --git a/src/features/ChatInput/ActionBar/Tools/useActivationSets.test.ts b/src/features/ChatInput/ActionBar/Tools/useActivationSets.test.tsindex 8c5bebb9603..91ecec048c3 100644--- a/src/features/ChatInput/ActionBar/Tools/useActivationSets.test.ts+++ b/src/features/ChatInput/ActionBar/Tools/useActivationSets.test.ts@@ -5,6 +5,7 @@ import { resolveActivationSets } from './useActivationSets';const resolve = (rawPlugins: Parameters<typeof resolveActivationSets>[0]['rawPlugins']) =>resolveActivationSets({+ connectedConnectorIds: ['gmail', 'slack', 'linear'],connectorIds: ['gmail', 'slack', 'linear'],librarySkillIds: ['excalidraw'],// What `getActivePluginIds` yields: the entries that carry a pin.@@ -15,12 +16,10 @@ const resolve = (rawPlugins: Parameters<typeof resolveActivationSets>[0]['rawPlu});describe('resolveActivationSets', () => {- it('lists a connector the agent never turned on under Disabled', () => {+ it('puts inherited connectors under Auto and keeps library skills off', () => {const { checkedSet, disabledIdSet } = resolve([]);- expect([...disabledIdSet]).toEqual(- expect.arrayContaining(['excalidraw', 'gmail', 'linear', 'slack']),- );+ expect([...disabledIdSet]).toEqual(['excalidraw']);expect(disabledIdSet.has('lobe-creds')).toBe(false);expect(checkedSet.size).toBe(0);});@@ -48,10 +47,10 @@ describe('resolveActivationSets', () => {expect(disabledIdSet.has('slack')).toBe(true);});- it('writes Auto explicitly for a connector, since no entry means off', () => {+ it('inherits Auto for a connector in agent mode', () => {const { optInIds } = resolve([]);- expect(resolveImplicitMode('gmail', optInIds)).toBe('disabled');+ expect(resolveImplicitMode('gmail', optInIds)).toBe('auto');expect(resolveImplicitMode('lobe-image-generation', optInIds)).toBe('auto');});});diff --git a/src/features/ChatInput/ActionBar/Tools/useActivationSets.ts b/src/features/ChatInput/ActionBar/Tools/useActivationSets.tsindex 9322c5ae0e4..9b83ff065e0 100644--- a/src/features/ChatInput/ActionBar/Tools/useActivationSets.ts+++ b/src/features/ChatInput/ActionBar/Tools/useActivationSets.ts@@ -3,7 +3,10 @@ import { type AgentPluginEntry, type AgentPluginMode } from '@lobechat/types';import isEqual from 'fast-deep-equal';import { useMemo } from 'react';-import { getConnectorIdentifiers } from '@/helpers/toolEngineering/connectorActivation';+import {+ getConnectedConnectorIds,+ getConnectorIdentifiers,+} from '@/helpers/toolEngineering/connectorActivation';import { useToolStore } from '@/store/tool';import { agentSkillsSelectors } from '@/store/tool/slices/agentSkills/selectors';@@ -15,13 +18,13 @@ export const CONNECTOR_MODES: AgentPluginMode[] = ['auto', 'disabled'];/*** The identifier sets the Tools popover groups its rows by.*- * Library skills and connectors are opt-in per agent β the profile is where one- * is turned on β so having no entry means Disabled for them, where it means- * Auto for a builtin tool or a builtin skill. A connector also has no Pinned+ * Library skills require an explicit entry. Connected tools default to Auto in+ * agent mode and require an entry in custom toolsets. A connector also has no Pinned* state: an entry pinned before it lost that state reads as on, so it is listed* under Auto rather than Pinned.*/export const resolveActivationSets = ({+ connectedConnectorIds,connectorIds: connectorIdList,librarySkillIds,discoverBuiltins = true,@@ -29,6 +32,7 @@ export const resolveActivationSets = ({rawPlugins,}: {discoverBuiltins?: boolean;+ connectedConnectorIds: readonly string[];connectorIds: readonly string[];librarySkillIds: readonly string[];/** The agent's pinned identifiers. */@@ -37,19 +41,23 @@ export const resolveActivationSets = ({rawPlugins: AgentPluginEntry[] | undefined;}) => {const connectorIds = new Set(connectorIdList);- const optInIds = new Set([...librarySkillIds, ...connectorIdList]);+ const connected = new Set(connectedConnectorIds);+ const optInIds = new Set(+ discoverBuiltins ? librarySkillIds : [...librarySkillIds, ...connectorIdList],+ );return {checkedSet: new Set(pinnedIds.filter((id) => !connectorIds.has(id) && !onDemandBuiltinToolIds.includes(id)),),connectorIds,- disabledIdSet: new Set(- resolveDisabledIds(+ disabledIdSet: new Set([+ ...connectorIdList.filter((id) => !connected.has(id)),+ ...resolveDisabledIds(rawPlugins,discoverBuiltins ? optInIds : [...optInIds, ...onDemandBuiltinToolIds],),- ),+ ]),/** Identifiers that are off without an entry, so Auto must be written explicitly. */optInIds,};@@ -57,17 +65,25 @@ export const resolveActivationSets = ({/** {@link resolveActivationSets} over the tool store. */export const useActivationSets = (+ agentId: string,pinnedIds: string[],rawPlugins: AgentPluginEntry[] | undefined,discoverBuiltins: boolean,) => {- const connectorIds = useToolStore(getConnectorIdentifiers, isEqual);+ const { connectorIds, connectedConnectorIds } = useToolStore((state) => {+ const connectorIds = getConnectorIdentifiers(state);+ return {+ connectorIds,+ connectedConnectorIds: getConnectedConnectorIds(state, agentId, connectorIds),+ };+ }, isEqual);const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);return useMemo(() =>resolveActivationSets({+ connectedConnectorIds,connectorIds,discoverBuiltins,librarySkillIds: [...marketAgentSkills, ...userAgentSkills].map(@@ -76,6 +92,14 @@ export const useActivationSets = (pinnedIds,rawPlugins,}),- [connectorIds, discoverBuiltins, marketAgentSkills, userAgentSkills, pinnedIds, rawPlugins],+ [+ connectedConnectorIds,+ connectorIds,+ discoverBuiltins,+ marketAgentSkills,+ userAgentSkills,+ pinnedIds,+ rawPlugins,+ ],);};diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.test.ts b/src/features/ChatInput/ActionBar/Tools/useControls.test.tsindex 03711c75be2..23ea6132436 100644--- a/src/features/ChatInput/ActionBar/Tools/useControls.test.ts+++ b/src/features/ChatInput/ActionBar/Tools/useControls.test.ts@@ -227,8 +227,7 @@ describe('chat input tool picker', () => {},];mocks.plugins = [- { identifier: 'gmail', mode: 'auto' },- { identifier: 'vercel', mode: 'auto' },+ { identifier: 'slack', mode: 'auto' },{ identifier: 'google-drive', mode: 'disabled' },];const { result } = renderHook(() => useControls());diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsxindex 5ce58e99d35..00f4c34e23b 100644--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx@@ -159,7 +159,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =(s) =>resolveToolMode(agentByIdSelectors.getAgentConfigById(agentId)(s)?.chatConfig) === 'agent',);- const activationSets = useActivationSets(checked, rawPlugins, discoverBuiltins);+ const activationSets = useActivationSets(agentId, checked, rawPlugins, discoverBuiltins);const { disabledIdSet, optInIds } = activationSets;const builtinList = useToolStore(builtinToolSelectors.metaListIncludingHidden, isEqual);diff --git a/src/features/ProfileEditor/AgentTool.tsx b/src/features/ProfileEditor/AgentTool.tsxindex 4763ee14b79..f1028c3ac08 100644--- a/src/features/ProfileEditor/AgentTool.tsx+++ b/src/features/ProfileEditor/AgentTool.tsx@@ -31,7 +31,10 @@ import ToolItem from '@/features/ChatInput/ActionBar/Tools/ToolItem';import ToolItemDetailPopover from '@/features/ChatInput/ActionBar/Tools/ToolItemDetailPopover';import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';import { createSkillStoreModal } from '@/features/SkillStore';-import { getConnectorIdentifiers } from '@/helpers/toolEngineering/connectorActivation';+import {+ getConnectedConnectorIds,+ getConnectorIdentifiers,+} from '@/helpers/toolEngineering/connectorActivation';import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';import { usePermission } from '@/hooks/usePermission';import { useAgentStore } from '@/store/agent';@@ -159,12 +162,19 @@ const AgentTool = memo<AgentToolProps>(: builtinToolSelectors.metaList,isEqual,);+ const connectedIds = useToolStore(+ (s) => getConnectedConnectorIds(s, effectiveAgentId),+ isEqual,+ );const implicitToolIds = useMemo(() =>resolveToolMode(config?.chatConfig) === 'agent'- ? profileBuiltinList.map((tool) => tool.identifier).filter(isOnDemandBuiltinTool)+ ? [+ ...profileBuiltinList.map((tool) => tool.identifier).filter(isOnDemandBuiltinTool),+ ...connectedIds,+ ]: [],- [config?.chatConfig, profileBuiltinList],+ [config?.chatConfig, profileBuiltinList, connectedIds],);const enabledIds = useMemo(() => {const ids = new Set([...implicitToolIds, ...getOptedInPluginIds(config?.plugins)]);@@ -279,11 +289,12 @@ const AgentTool = memo<AgentToolProps>(// so an existing disabled entry is flipped in place instead of being// dropped from the array.await updateAgentConfigById(effectiveAgentId, {- plugins: isOnDemandBuiltinTool(pluginId)- ? upsertConnectorEnabled(config?.plugins, pluginId, shouldEnable)- : shouldEnable && (allSkillIdentifiers.has(pluginId) || connectorIds.has(pluginId))- ? upsertConnectorEnabled(config?.plugins, pluginId, true)- : upsertPluginMode(config?.plugins, pluginId, shouldEnable ? 'pinned' : 'auto'),+ plugins:+ isOnDemandBuiltinTool(pluginId) || connectorIds.has(pluginId)+ ? upsertConnectorEnabled(config?.plugins, pluginId, shouldEnable)+ : shouldEnable && allSkillIdentifiers.has(pluginId)+ ? upsertConnectorEnabled(config?.plugins, pluginId, true)+ : upsertPluginMode(config?.plugins, pluginId, shouldEnable ? 'pinned' : 'auto'),});},[@@ -453,7 +464,13 @@ const AgentTool = memo<AgentToolProps>(if (!canEdit) return;const identifier = typeof pluginId === 'string' ? pluginId : pluginId?.identifier;- await togglePlugin(identifier, false);+ if (connectorIds.has(identifier) && !implicitToolIds.includes(identifier)) {+ await updateAgentConfigById(effectiveAgentId, {+ plugins: upsertPluginMode(config?.plugins, identifier, 'auto'),+ });+ } else {+ await togglePlugin(identifier, false);+ }};// Builtin Agent Skills list items (grouped under LobeHub)@@ -1032,6 +1049,7 @@ const AgentTool = memo<AgentToolProps>(isSkill={kind === 'skills'}key={pluginId}pluginId={pluginId}+ removable={!implicitToolIds.includes(pluginId)}showAuthor={showAuthor}showDesktopOnlyLabel={filterAvailableInWeb}tagLabel={kind === 'skills' ? skillSource.get(pluginId) : undefined}diff --git a/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsx b/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsxindex a22ac0e0c04..bd831af418c 100644--- a/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsx+++ b/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsx@@ -90,7 +90,8 @@ const AgentToolsSection = memo<{</DropdownMenu>);- const agentPlugins = useAgentStore((s) => agentSelectors.getAgentConfigById(agentId)(s)?.plugins);+ const config = useAgentStore(agentSelectors.getAgentConfigById(agentId));+ const agentPlugins = config?.plugins;const setEnabled = (identifier: string, enabled: boolean) =>updateAgentConfigById(agentId, {plugins: upsertConnectorEnabled(agentPlugins, identifier, enabled),@@ -109,12 +110,14 @@ const AgentToolsSection = memo<{<PluginTagagentId={agentId}disabled={!canEdit}- enabled={getConnectorMode(agentPlugins, connector.identifier) === 'auto'}key={connector.id}pluginId={connector.identifier}removable={canManageRow}showAuthor={!!activeWorkspaceId}variant={isList ? 'row' : 'chip'}+ enabled={+ getConnectorMode(agentPlugins, connector.identifier, config?.chatConfig) === 'auto'+ }onOpen={isList ? onOpenDetail : undefined}onToggle={isList ? (next) => void setEnabled(connector.identifier, next) : undefined}onRemove={() => {@@ -133,7 +136,8 @@ const AgentToolsSection = memo<{rows={tags}activeCount={agentConnectors.filter(- (connector) => getConnectorMode(agentPlugins, connector.identifier) === 'auto',+ (connector) =>+ getConnectorMode(agentPlugins, connector.identifier, config?.chatConfig) === 'auto',).length}/>diff --git a/src/features/ProfileEditor/AgentUserTools/UserToolsSection.test.tsx b/src/features/ProfileEditor/AgentUserTools/UserToolsSection.test.tsxindex b1804637d33..97528fa8e7b 100644--- a/src/features/ProfileEditor/AgentUserTools/UserToolsSection.test.tsx+++ b/src/features/ProfileEditor/AgentUserTools/UserToolsSection.test.tsx@@ -128,6 +128,15 @@ describe('UserToolsSection β Workspace/User tool count', () => {expect(labelText()).toContain('Β· 1');});+ it('counts a newly connected tool without an agent configuration entry', () => {+ mocks.toolState.connectors = [+ { identifier: 'notion', sourceType: 'custom', status: 'connected', isEnabled: true },+ { identifier: 'slack', sourceType: 'custom', status: 'pending', isEnabled: true },+ ];+ renderSection();+ expect(labelText()).toContain('Β· 1');+ });+it('counts a connector turned on with an auto entry and leaves out one turned off', () => {// A connector is two-state: on is an explicit `auto` entry, never a pin.mocks.agentConfig = {diff --git a/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsx b/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsxindex 42895a59159..753f6fd1696 100644--- a/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsx+++ b/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsx@@ -1,6 +1,6 @@'use client';-import { getOptedInPluginIds } from '@lobechat/types';+import { getConnectorMode, getOptedInPluginIds } from '@lobechat/types';import { Button, Flexbox, Text } from '@lobehub/ui';import isEqual from 'fast-deep-equal';import { memo, useMemo } from 'react';@@ -11,6 +11,7 @@ import type { AgentToolProps } from '@/features/ProfileEditor/AgentTool';import SharedAgentTool from '@/features/ProfileEditor/AgentTool';import PluginTag from '@/features/ProfileEditor/PluginTag';import { getVisibleProfileToolIds } from '@/features/ProfileEditor/profileToolVisibility';+import { getConnectedConnectorIds } from '@/helpers/toolEngineering/connectorActivation';import { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';import { useToolStore } from '@/store/tool';@@ -69,10 +70,21 @@ const UserToolsSection = memo<Props>(() => new Set(nonProfileConfigurableBuiltinToolIds),[nonProfileConfigurableBuiltinToolIds],);- const userToolCount = getVisibleProfileToolIds(getOptedInPluginIds(config?.plugins), {- agentConnectorIdentifiers,- nonConfigurableBuiltinToolIdentifiers: nonProfileConfigurableBuiltinToolIdentifiers,- }).length;+ const connectedIds = useToolStore((s) => getConnectedConnectorIds(s, agentId), isEqual);+ const userToolCount = getVisibleProfileToolIds(+ [+ ...new Set([+ ...getOptedInPluginIds(config?.plugins),+ ...connectedIds.filter(+ (id) => getConnectorMode(config?.plugins, id, config?.chatConfig) === 'auto',+ ),+ ]),+ ],+ {+ agentConnectorIdentifiers,+ nonConfigurableBuiltinToolIdentifiers: nonProfileConfigurableBuiltinToolIdentifiers,+ },+ ).length;// In a workspace, this section's base tools are the WORKSPACE dimension// (`connector.list` is workspace-scoped), not the caller's personal tools β// label it so the user knows the tools are shared workspace-scoped, notdiff --git a/src/helpers/toolEngineering/connectorActivation.test.ts b/src/helpers/toolEngineering/connectorActivation.test.tsindex 5f6bcf4590f..53538ceac84 100644--- a/src/helpers/toolEngineering/connectorActivation.test.ts+++ b/src/helpers/toolEngineering/connectorActivation.test.ts@@ -9,14 +9,21 @@ import {} from './connectorActivation';const toolState = {- agentConnectors: { 'agent-1': [{ identifier: 'agent-only-mcp' }] },+ agentConnectors: {+ 'agent-1': [+ { identifier: 'agent-only-mcp', sourceType: 'custom', isEnabled: true, status: 'connected' },+ ],+ },agentSkillListMap: { all: [{ identifier: 'library-skill' }] },builtinSkills: [{ identifier: 'builtin-skill' }],builtinTools: [{ identifier: 'lobe-image-generation' }],- composioServers: [{ identifier: 'gmail' }],- connectors: [{ identifier: 'custom-mcp' }, { identifier: 'lobe-image-generation' }],+ composioServers: [{ identifier: 'gmail', status: 'active' }],+ connectors: [+ { identifier: 'custom-mcp', sourceType: 'custom', isEnabled: true, status: 'connected' },+ { identifier: 'lobe-image-generation' },+ ],installedPlugins: [{ identifier: 'community-mcp' }, { identifier: 'library-skill' }],- lobehubSkillServers: [{ identifier: 'linear' }],+ lobehubSkillServers: [{ identifier: 'linear', status: 'connected' }],} as unknown as ToolStoreState;describe('getConnectorIdentifiers', () => {@@ -32,16 +39,22 @@ describe('getConnectorIdentifiers', () => {});describe('resolveAgentConnectorActivation', () => {- it('turns every connector off for an agent that has no entry for it', () => {- const { offIds } = resolveAgentConnectorActivation({ plugins: [] }, [], toolState);+ it('offers a new connection to ordinary agents without injecting it', () => {+ const { activation, offIds } = resolveAgentConnectorActivation({ plugins: [] }, [], toolState);+ expect(offIds).toEqual(['agent-only-mcp']);+ expect(resolveAgentConnectorActivation({ id: 'agent-1' }, [], toolState).offIds).toEqual([]);+ expect(activation.isAllowed('linear')).toBe(true);+ expect(activation.isInjected('linear')).toBe(false);+ });- expect(offIds.sort()).toEqual([- 'agent-only-mcp',- 'community-mcp',- 'custom-mcp',- 'gmail',- 'linear',- ]);+ it('keeps another agentβs scoped connector out even when mentioned', () => {+ const { activation } = resolveAgentConnectorActivation(+ { id: 'agent-2' },+ ['agent-only-mcp'],+ toolState,+ );+ expect(activation.isAllowed('agent-only-mcp')).toBe(false);+ expect(activation.isInjected('agent-only-mcp')).toBe(false);});it('keeps a connector on for an auto entry and for one pinned before the switch', () => {diff --git a/src/helpers/toolEngineering/connectorActivation.ts b/src/helpers/toolEngineering/connectorActivation.tsindex 44e6d817c2d..dca96ca677d 100644--- a/src/helpers/toolEngineering/connectorActivation.ts+++ b/src/helpers/toolEngineering/connectorActivation.ts@@ -5,11 +5,19 @@ import {hasConnectorActivator,resolveConnectorActivation,} from '@lobechat/mecha';-import { type AgentPluginEntry, getActivePluginIds, getOptedInPluginIds } from '@lobechat/types';+import {+ type AgentPluginEntry,+ getActivePluginIds,+ getOptedInPluginIds,+ resolveToolMode,+} from '@lobechat/types';import { getToolStoreState } from '@/store/tool';import type { ToolStoreState } from '@/store/tool/initialState';import { agentSkillsSelectors } from '@/store/tool/slices/agentSkills/selectors';+import { ComposioServerStatus } from '@/store/tool/slices/composioStore/types';+import { connectorSelectors } from '@/store/tool/slices/connector/selectors';+import { lobehubSkillStoreSelectors } from '@/store/tool/slices/lobehubSkillStore/selectors';import type { LobeAgentChatConfig } from '@/types/agent';/**@@ -38,6 +46,25 @@ export const getConnectorIdentifiers = (s: ToolStoreState = getToolStoreState())].filter((identifier) => !notConnectors.has(identifier));};+/** Connected tools visible to this agent in the current account or workspace. */+export const getConnectedConnectorIds = (+ s: ToolStoreState,+ agentId: string,+ connectorIds = getConnectorIdentifiers(s),+): string[] => {+ const connected = new Set([+ ...connectorSelectors.connectedMcpConnectorsForAgent(s, agentId).map((c) => c.identifier),+ ...(s.installedPlugins ?? []).filter((p) => !p.customParams?.composio).map((p) => p.identifier),+ ...(s.composioServers ?? [])+ .filter(+ (c) => c.status === ComposioServerStatus.ACTIVE && (!c.agentId || c.agentId === agentId),+ )+ .map((c) => c.identifier),+ ...lobehubSkillStoreSelectors.getConnectedServers(s).map((c) => c.identifier),+ ]);+ return connectorIds.filter((id) => connected.has(id));+};+export interface AgentConnectorActivation {activation: ConnectorActivation;connectorIds: string[];@@ -47,11 +74,11 @@ export interface AgentConnectorActivation {/*** The connector rule (`resolveConnectorActivation`) over the browser's stores:- * a connector is on only when the agent's `plugins` carries an entry for it- * that is not disabled.+ * uses the executing agent's mode and explicit overrides.*/export const resolveAgentConnectorActivation = (agent: {+ id?: string;chatConfig?: Pick<LobeAgentChatConfig, 'enableAgentMode' | 'skillActivateMode' | 'toolMode'>;enabledPluginIds?: readonly string[];/** The raw `plugins` field, before it is collapsed to pinned identifiers. */@@ -61,16 +88,21 @@ export const resolveAgentConnectorActivation = (turnIds: readonly string[] = [],toolState: ToolStoreState = getToolStoreState(),): AgentConnectorActivation => {+ const disabledIds = getUserDisabledToolIds(agent.plugins, agent.chatConfig);+ const connectorIds = getConnectorIdentifiers(toolState);+ const available = new Set(getConnectedConnectorIds(toolState, agent.id ?? '', connectorIds));+ const unavailable = connectorIds.filter((id) => !available.has(id));const activation = resolveConnectorActivation({+ disabledIds: [...disabledIds, ...unavailable],+ discoverByDefault: resolveToolMode(agent.chatConfig) === 'agent',hasActivator: hasConnectorActivator(agent.chatConfig,[...(agent.enabledPluginIds ?? getActivePluginIds(agent.plugins)), ...turnIds],- getUserDisabledToolIds(agent.plugins, agent.chatConfig),+ disabledIds,),optedInIds: getOptedInPluginIds(agent.plugins),- turnIds,+ turnIds: turnIds.filter((id) => !unavailable.includes(id)),});- const connectorIds = getConnectorIdentifiers(toolState);return {activation,diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.tsindex 39eda2f418b..b5e94af0c0e 100644--- a/src/helpers/toolEngineering/index.test.ts+++ b/src/helpers/toolEngineering/index.test.ts@@ -867,7 +867,7 @@ describe('toolEngineering', () => {});});- describe('connectors are opt-in per agent', () => {+ describe('connector discovery', () => {const connectorManifest = {api: [{@@ -899,9 +899,9 @@ describe('toolEngineering', () => {mockInstalledPluginManifestList = () => [connectorManifest];});- it('keeps a connector the agent never turned on out of reach, even for the activator', () => {+ it('offers an unconfigured connector only after activation', () => {expect(generate().enabledToolIds).toEqual([]);- expect(generate({ explicit: true }).enabledToolIds).toEqual([]);+ expect(generate({ explicit: true }).enabledToolIds).toEqual(['gmail-mcp']);});it('leaves a connector that is on to the activator instead of invoking it up front', () => {@@ -958,7 +958,7 @@ describe('toolEngineering', () => {{ model: 'gpt-4', provider: 'openai' },undefined,undefined,- { runAgent: { plugins: [] } },+ { runAgent: { plugins: [{ identifier: 'gmail-mcp', mode: 'disabled' }] } },).generateToolsDetailed({context: { isExplicitActivation: true },model: 'gpt-4',diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.tsindex c2f90dcad1d..133c53dba8f 100644--- a/src/helpers/toolEngineering/index.ts+++ b/src/helpers/toolEngineering/index.ts@@ -64,6 +64,7 @@ import {export interface ToolsEngineConfig {/** Additional manifests to include beyond the standard ones */additionalManifests?: ToolManifest[];+ agentId?: string;/** Default tool IDs that will always be added to the end of the tools list */defaultToolIds?: string[];/**@@ -124,7 +125,9 @@ export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine =.composioAsLobeTools(toolStoreState).map((tool) => tool.manifest as LobeToolManifest),connectors: buildClientConnectorManifests(- connectorSelectors.executableMcpConnectors(toolStoreState),+ config.agentId+ ? connectorSelectors.connectedMcpConnectorsForAgent(toolStoreState, config.agentId)+ : connectorSelectors.executableMcpConnectors(toolStoreState),) as LobeToolManifest[],installedPlugins: pluginSelectors.installedPluginManifestList(toolStoreState,@@ -187,6 +190,7 @@ export const createAgentToolsEngine = (const agentState = getAgentStoreState();const targetAgentId = options.runAgent?.id ?? agentState.activeAgentId ?? '';const agent = options.runAgent ?? {+ id: targetAgentId,chatConfig: agentChatConfigSelectors.currentChatConfig(agentState),plugins: agentSelectors.currentAgentConfig(agentState)?.plugins,};@@ -252,6 +256,7 @@ export const createAgentToolsEngine = (});return createToolsEngine({+ agentId: targetAgentId,defaultToolIds: resolved.defaultToolIds,disabledPluginIds: [...resolved.excludedIdentifiers],manifestContext,diff --git a/src/services/chat/index.ts b/src/services/chat/index.tsindex ca6fd1a0fb3..d5243120817 100644--- a/src/services/chat/index.ts+++ b/src/services/chat/index.ts@@ -238,8 +238,7 @@ class ChatService {// `agentConfig.plugins` is the raw (pre-filter) field β `plugins` below// is already pinned-only (resolved upstream in agentConfigResolver).autoSkillIds: getAutoPluginIds(agentConfig.plugins),- // A connector the agent has not turned on is off for it, so it leaves the- // discovery list too; one this turn already enabled (an @-mention) stays.+ // Apply the executing agent's connector preferences and scope to discovery.disabledPluginIds: [...getUserDisabledToolIds(agentConfig.plugins, chatConfig),...getUnavailableBuiltinToolIds(@@ -249,7 +248,7 @@ class ChatService {discoveryManifests ? [] : runtimeUninstalledBuiltinTools(getToolStoreState()),),...resolveAgentConnectorActivation(- { chatConfig, plugins: agentConfig.plugins },+ { id: targetAgentId, chatConfig, plugins: agentConfig.plugins },enabledToolIds,).offIds,],diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.discoverableManifests.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.discoverableManifests.test.tsindex 7054a41c41e..2d97c4211a3 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.discoverableManifests.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.discoverableManifests.test.ts@@ -70,7 +70,7 @@ describe('internal_createAgentState manifest map', () => {});describe('connectors on the executing client agent', () => {- const ids = ['target-connector', 'parent-connector'];+ const ids = ['target-connector', 'parent-connector', 'new-connector'];beforeEach(() => {resetTestEnvironment();useAgentStore.setState({@@ -101,7 +101,11 @@ describe('connectors on the executing client agent', () => {const chatConfig = createMockChatConfig({ toolMode });const agentConfig = createMockAgentConfig({chatConfig,- plugins: [...pinned, { identifier: ids[0], mode: 'auto' }],+ plugins: [+ ...pinned,+ { identifier: ids[0], mode: 'auto' },+ { identifier: ids[1], mode: 'disabled' },+ ],});useAgentStore.setState((s) => ({ agentMap: { ...s.agentMap, target: agentConfig } }));return useChatStore.getState().internal_createAgentState({@@ -113,11 +117,11 @@ describe('connectors on the executing client agent', () => {};it.each(['agent', 'custom'] as const)(- 'activates only the targetβs connector in %s mode',+ 'applies the targetβs overrides and %s mode when activating connectors',(mode) => {const run = startTarget(mode, mode === 'custom' ? ['lobe-activator'] : []);expect(run.agentConfig.enabledToolIds).toContain('lobe-activator');- expect(run.agentConfig.enabledToolIds).not.toContain(ids[0]);+ for (const id of ids) expect(run.agentConfig.enabledToolIds).not.toContain(id);const activated = run.toolsEngine.generateToolsDetailed({context: { isExplicitActivation: true },model: run.agentConfig.agentConfig.model,@@ -127,6 +131,7 @@ describe('connectors on the executing client agent', () => {});expect(activated.tools?.map((tool) => tool.function.name)).toEqual(['target-connector____read',+ ...(mode === 'agent' ? ['new-connector____read'] : []),]);},);diff --git a/src/store/tool/slices/connector/selectors.ts b/src/store/tool/slices/connector/selectors.tsindex 3ad4ff133f8..df7b40ebd9d 100644--- a/src/store/tool/slices/connector/selectors.ts+++ b/src/store/tool/slices/connector/selectors.ts@@ -144,12 +144,6 @@ const agentConnectors =(s: ToolStore): ConnectorWithTools[] =>s.agentConnectors?.[agentId] ?? [];-/**- * 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.- *//** Mounted (locked) to an agent other than `agentId`; without one, to any agent. */const isMountedByAnotherAgent = (connector: ConnectorWithTools, agentId?: string) => {const mountedBy = connector.metadata?.mountedByAgentId;@@ -157,6 +151,28 @@ const isMountedByAnotherAgent = (connector: ConnectorWithTools, agentId?: stringreturn typeof mountedBy === 'string' && mountedBy !== '' && mountedBy !== agentId;};+/** Connected MCP rows a particular agent can use, with its own rows taking precedence. */+const connectedMcpConnectorsForAgent = (+ s: ToolStoreState,+ agentId: string,+): ConnectorWithTools[] => {+ const agentRows = s.agentConnectors?.[agentId] ?? [];+ const overridden = new Set(agentRows.map((row) => row.identifier));+ const baseRows = (s.connectors ?? []).filter(+ (row) => !overridden.has(row.identifier) && !isMountedByAnotherAgent(row, agentId),+ );+ return executableMcpConnectors({+ connectors: [...agentRows, ...baseRows],+ installedPlugins: s.installedPlugins,+ }).filter((row) => row.isEnabled && row.status === 'connected');+};++/**+ * 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.+ */const connectorByIdentifierForAgent =(identifier: string, agentId?: string) =>(s: ToolStore): ConnectorWithTools | undefined => {@@ -247,6 +263,7 @@ export const connectorSelectors = {executableMcpConnectors,installedMarketplaceConnectors,isMarketplaceConnectorInstalled,+ connectedMcpConnectorsForAgent,marketplaceMcpConnectorByIdentifier,marketplaceMcpConnectors,connectorToolsGroupedByIdentifier: