🤯 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
🐛 fix(agent): keep unpinned custom MCP connectors discoverable after the mention turn (#20885)
LiJianb8e4c2627f55
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.tsnew file mode 100644index 00000000000..8797de35b4f--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts@@ -0,0 +1,205 @@+import { type LobeToolManifest, ToolNameResolver } from '@lobechat/context-engine';+import { describe, expect, it, vi } from 'vitest';++import { buildToolDiscoveryConfig } from '@/server/modules/AgentRuntime/executorHelpers';+import { scheduleStaleConnectorToolsRefresh } from '@/server/services/connector/refresh';++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([]) },+}));++const YINGMI = 'yingmi';++/** A user-created custom MCP: stored as a connector row, not a plugin row. */+const customConnector = {+ credentials: null,+ id: 'conn-yingmi',+ identifier: YINGMI,+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://stargate.yingmi.com/mcp/v2',+ metadata: {},+ name: 'yingmi',+};++const connectorTools = [+ {+ description: 'Batch get fund NAV history',+ inputSchema: { properties: {}, type: 'object' },+ permission: 'auto',+ toolName: 'BatchGetFundNavHistory',+ userConnectorId: customConnector.id,+ },+];++interface RunOptions {+ /** The agent's own `plugins` config — i.e. what the user pinned. */+ plugins?: string[];+ /** This turn's @-mention picks. */+ selectedToolIds?: string[];+ shareGate?: unknown;+}++const run = (options: RunOptions = {}) => {+ const candidates = new Set([...(options.plugins ?? []), ...(options.selectedToolIds ?? [])]);++ return discoverTools(+ {+ agentDocumentsService: { hasDocuments: vi.fn().mockResolvedValue(false) },+ composioService: { getComposioManifests: vi.fn().mockResolvedValue([]) },+ connectorModel: {+ resolveAll: vi.fn().mockResolvedValue([customConnector]),+ resolveByIdentifiers: vi.fn(async (ids: string[]) =>+ ids.includes(YINGMI) && candidates.has(YINGMI) ? [customConnector] : [],+ ),+ },+ connectorToolModel: {+ queryAllByConnectorIds: vi.fn().mockResolvedValue(connectorTools),+ 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: 'user-1',+ } as never,+ {+ agentConfig: { chatConfig: {}, plugins: options.plugins ?? [] },+ appContext: undefined,+ canUseDevice: false,+ model: 'test-model',+ prompt: '470008 呢',+ provider: 'test-provider',+ resolvedAgentId: 'agent-1',+ runFacts: {+ deviceSystemInfo: vi.fn().mockResolvedValue(undefined),+ userPreference: vi.fn().mockResolvedValue(undefined),+ },+ shareGate: options.shareGate,+ } as never,+ {+ disabledPluginIds: [],+ globalMemoryEnabled: false,+ hasMentionedAgents: false,+ isFixedDeviceTarget: false,+ loadHistoryMessages: vi.fn().mockResolvedValue([]),+ selectedToolIds: options.selectedToolIds,+ throwIfExecutionAborted: vi.fn(),+ } as never,+ );+};++/** Exactly what the model reads in `<available_tools>`. */+const availableToolIds = (+ manifestMap: Record<string, LobeToolManifest>,+ enabledToolIds: string[],+): string[] =>+ (buildToolDiscoveryConfig({ manifestMap } as never, enabledToolIds)?.availableTools ?? []).map(+ (tool) => tool.identifier,+ );++const offeredToolNames = (result: { tools?: { function: { name: string } }[] }) =>+ (result.tools ?? []).map((tool) => tool.function.name);++describe('discoverTools — unpinned custom MCP connectors', () => {+ it('keeps an unmentioned, unpinned connector discoverable without enabling it', async () => {+ // The follow-up turn after an @-mention: no mention, nothing pinned. The+ // activator used to answer "Not found: yingmi" here.+ const result = await run();++ expect(result.toolManifestMap[YINGMI]).toBeDefined();+ expect(result.toolSourceMap[YINGMI]).toBe('mcp');+ expect(availableToolIds(result.toolManifestMap, result.toolsResult.enabledToolIds)).toContain(+ YINGMI,+ );+ expect(result.toolsResult.enabledToolIds).not.toContain(YINGMI);+ expect(offeredToolNames(result).some((name) => name.startsWith(`${YINGMI}____`))).toBe(false);+ });++ it('lets the next operation restore a previous turn’s activation', async () => {+ const result = await run();++ // The cross-turn restore in `operationPrep` re-checks historical+ // activations through the engine with explicit activation.+ const restored = result.toolsEngine!.generateToolsDetailed({+ context: { isExplicitActivation: true },+ model: 'test-model',+ provider: 'test-provider',+ skipDefaultTools: true,+ toolIds: [YINGMI],+ });++ expect(restored.enabledToolIds).toContain(YINGMI);+ // …and the wire name the model copies from history resolves again.+ const [call] = new ToolNameResolver().resolve(+ [+ {+ function: { arguments: '{}', name: `${YINGMI}____BatchGetFundNavHistory____mcp` },+ id: 'call_1',+ type: 'function',+ },+ ],+ result.toolManifestMap,+ );+ expect(call).toMatchObject({ apiName: 'BatchGetFundNavHistory', identifier: YINGMI });+ });++ it('still enables the connector on the turn that @-mentions it', async () => {+ const result = await run({ selectedToolIds: [YINGMI] });++ expect(result.toolsResult.enabledToolIds).toContain(YINGMI);+ expect(+ offeredToolNames(result).some((name) =>+ name.startsWith(`${YINGMI}____BatchGetFundNavHistory`),+ ),+ ).toBe(true);+ });++ it('schedules the stale-tool refresh for an unpinned connector too', async () => {+ vi.mocked(scheduleStaleConnectorToolsRefresh).mockClear();++ await run();++ // An activatable connector whose upstream tools changed must not keep+ // offering the old list until someone re-syncs it by hand.+ expect(scheduleStaleConnectorToolsRefresh).toHaveBeenCalledTimes(1);+ const [connectors] = vi.mocked(scheduleStaleConnectorToolsRefresh).mock.calls[0];+ expect(connectors.map((c) => c.identifier)).toContain(YINGMI);+ });++ it('does not decrypt unpinned connectors for a share visitor run', async () => {+ const result = await run({+ shareGate: {+ agentId: 'agent-1',+ shareConfig: { toolGrants: [] },+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ },+ });++ expect(result.toolManifestMap[YINGMI]).toBeUndefined();+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.tsindex 7dc5da7e2a4..9a30465edf0 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts@@ -47,12 +47,13 @@ import { loadModels } from '@/business/client/model-bank/loadModels';import { AiModelModel } from '@/database/models/aiModel';import { AiProviderModel } from '@/database/models/aiProvider';import { ChatGroupModel } from '@/database/models/chatGroup';-import { ConnectorModel } from '@/database/models/connector';+import { ConnectorModel, type DecryptedConnector } from '@/database/models/connector';import { ConnectorToolModel } from '@/database/models/connectorTool';import { DocumentModel } from '@/database/models/document';import { FileModel } from '@/database/models/file';import type { MessageModel } from '@/database/models/message';import type { PluginModel } from '@/database/models/plugin';+import type { UserConnectorToolItem } from '@/database/schemas';import {type ExecutionPlan,executionPlanToManifestExecutionEnv,@@ -426,10 +427,65 @@ export const discoverTools = async (? await deps.connectorToolModel.queryAllByConnectorIds(connectorsMcp.map((c) => c.id)): [];- return { connectorGateKeeper, connectors, connectorsMcp, connectorTools };+ const discoverable = await readDiscoverableConnectors(candidateIds, connectorGateKeeper);++ return {+ connectorGateKeeper,+ connectors,+ connectorsMcp,+ connectorTools,+ discoverableConnectorManifests: discoverable.manifests,+ discoverableConnectorsMcp: discoverable.connectorsMcp,+ discoverableConnectorTools: discoverable.tools,+ };});}+ /**+ * Connectors the agent has not pinned — `auto` in the three-state plugin+ * config, which is simply "absent from `plugins`". A custom MCP is stored as+ * a connector, so without this source an unpinned one is resolvable only on+ * the turn that @-mentions it: the next turn's activator answers+ * "Not found" and the model's direct call is rejected as an unknown name.+ * Like installed plugins they are discoverable but never enabled.+ *+ * Share runs skip it: the early allowlist above exists so ungranted creator+ * connectors never get their credentials decrypted for a visitor turn.+ * Degrades to nothing on failure — widening discovery must not fail the run.+ */+ async function readDiscoverableConnectors(+ candidateIds: string[],+ gateKeeper: KeyVaultsGateKeeper | undefined,+ ): Promise<{+ connectorsMcp: DecryptedConnector[];+ manifests: LobeToolManifest[];+ tools: UserConnectorToolItem[];+ }> {+ const none = { connectorsMcp: [], manifests: [], tools: [] };+ if (shareGate || exclusivePluginIds || isGoalTurn) return none;+ try {+ const candidates = new Set(candidateIds);+ const connectorsMcp = (+ await deps.connectorModel.resolveAll(resolvedAgentId, gateKeeper)+ ).filter(+ (c) => !candidates.has(c.identifier) && (c.mcpServerUrl || c.mcpConnectionType === 'stdio'),+ );+ if (connectorsMcp.length === 0) return none;++ const tools = await deps.connectorToolModel.queryAllByConnectorIds(+ connectorsMcp.map((c) => c.id),+ );+ return {+ connectorsMcp,+ manifests: buildConnectorManifests(connectorsMcp, tools) as LobeToolManifest[],+ tools,+ };+ } catch (error) {+ log('execAgent: failed to read discoverable connectors: %O', error);+ return none;+ }+ }+async function readLobehubSkillManifests(): Promise<LobeToolManifest[]> {try {const marketService = await deps.getMarketService();@@ -661,8 +717,15 @@ export const discoverTools = async ();// 5a-1. Resolve connectors — connector identifier takes priority over plugin.- const { connectorGateKeeper, connectors, connectorsMcp, connectorTools } =- await toolReads.connectors;+ const {+ connectorGateKeeper,+ connectors,+ connectorsMcp,+ connectorTools,+ discoverableConnectorManifests,+ discoverableConnectorsMcp,+ discoverableConnectorTools,+ } = await toolReads.connectors;// 5a-1b. Model awareness: when the caller runs a shared agent whose tools// were authorized by OTHER members (workspace dimension), tell the model@@ -708,10 +771,13 @@ export const discoverTools = async (const refreshConnectorModel = connectorGateKeeper? new ConnectorModel(deps.db, deps.userId, deps.workspaceId, connectorGateKeeper): deps.connectorModel;- scheduleStaleConnectorToolsRefresh(connectorsMcp, buildLastSyncedAtMap(connectorTools), {- 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(+ [...connectorsMcp, ...discoverableConnectorsMcp],+ buildLastSyncedAtMap([...connectorTools, ...discoverableConnectorTools]),+ { connectorModel: refreshConnectorModel, connectorToolModel: deps.connectorToolModel },+ );} catch (err) {log('execAgent: failed to schedule connector tool refresh (ignored): %O', err);}@@ -720,7 +786,10 @@ export const discoverTools = async (// tools) replace a same-named plugin. Deriving the set from connectorsMcp// instead would let a disabled / not-yet-synced connector evict the plugin// while contributing no tools — leaving the runtime with nothing to call.- const connectorIdentifierSet = new Set(connectorManifests.map((m) => m.identifier));+ // Unpinned connectors supersede a leftover plugin row the same way.+ const connectorIdentifierSet = new Set(+ [...connectorManifests, ...discoverableConnectorManifests].map((m) => m.identifier),+ );// Filter out plugin entries that are now handled by real MCP connectors.// `let` because community-MCP plugins may be patched with connector@@ -1066,6 +1135,9 @@ export const discoverTools = async (const activeLobehubSkillManifests = dropDisabledManifests(lobehubSkillManifests);const activeComposioManifests = dropDisabledManifests(composioManifests);const activeConnectorManifests = dropDisabledManifests(connectorManifests);+ const activeDiscoverableConnectorManifests = dropDisabledManifests(+ discoverableConnectorManifests,+ );// Context-aware builtin manifests: inside a sub-agent (or group) run,// lobe-agent drops `callSubAgent` so the model can't recurse into nested@@ -1104,6 +1176,11 @@ export const discoverTools = async (...activeLobehubSkillManifests,...activeComposioManifests,...activeConnectorManifests,+ // Known to the engine but never invocation candidates (they stay out of+ // `connectorIds` below), so they are not enabled by default — this only+ // lets a previous turn's activation pass the explicit-activation+ // re-check when the next operation restores it.+ ...activeDiscoverableConnectorManifests,],agentConfig: {chatConfig: isGoalTurn@@ -1198,10 +1275,14 @@ export const discoverTools = async (// wall re-checks them; a connector / Composio / LobeHub skill manifest// of the same identifier still wins, because the pool seeds this source// last.- installedManifests: dropInvalidManifests(- pluginsWithoutConnectors.map((plugin) => plugin.manifest as LobeToolManifest | undefined),- 'installedPlugins(auto)',- ),+ // Unpinned connectors join them on the same terms.+ installedManifests: [+ ...activeDiscoverableConnectorManifests,+ ...dropInvalidManifests(+ pluginsWithoutConnectors.map((plugin) => plugin.manifest as LobeToolManifest | undefined),+ 'installedPlugins(auto)',+ ),+ ],lobehubSkills: activeLobehubSkillManifests,manifestContext,});@@ -1216,7 +1297,7 @@ export const discoverTools = async (...installedPlugins.filter((plugin) => plugin.customParams?.mcp?.type === 'stdio').map((plugin) => plugin.identifier),- ...connectorsMcp+ ...[...connectorsMcp, ...discoverableConnectorsMcp].filter((connector) => connector.mcpConnectionType === 'stdio').map((connector) => connector.identifier),],diff --git a/package.json b/package.jsonindex b1fdd1c9618..fc30ea4c61c 100644--- a/package.json+++ b/package.json@@ -328,7 +328,7 @@"@lobehub/icons": "^5.18.0","@lobehub/market-sdk": "0.42.0","@lobehub/tts": "^5.1.2",- "@lobehub/ui": "^5.56.0",+ "@lobehub/ui": "^5.61.0","@modelcontextprotocol/sdk": "^1.30.0","@neondatabase/serverless": "^1.1.0","@next/third-parties": "^16.3.0",diff --git a/src/features/DataImporter/SuccessResult.tsx b/src/features/DataImporter/SuccessResult.tsxindex 26801374860..391646f8e0b 100644--- a/src/features/DataImporter/SuccessResult.tsx+++ b/src/features/DataImporter/SuccessResult.tsx@@ -52,11 +52,11 @@ const SuccessResult = memo<SuccessResultProps>(({ duration, dataSource, onClickF<Flexbox gap={16} width={500}>{t('importModal.finish.subTitle', { duration: (duration / 1000).toFixed(2) })}<Table- bordereddataSource={dataSource}pagination={false}rowKey={'title'}size={'small'}+ variant="outlined"columns={[{ dataIndex: 'title', render: cellRender, title: t('importModal.result.type') },{ dataIndex: 'added', render: cellRender, title: t('importModal.result.added') },diff --git a/src/features/PluginDetailModal/APIs.tsx b/src/features/PluginDetailModal/APIs.tsxindex 340467d593e..035f2fab058 100644--- a/src/features/PluginDetailModal/APIs.tsx+++ b/src/features/PluginDetailModal/APIs.tsx@@ -27,12 +27,12 @@ const APIs = memo<{return (<Flexbox paddingBlock={16} width={'100%'}><Table- bordereddataSource={pluginManifest.api}pagination={false}rowKey={'name'}size={'small'}tableLayout="fixed"+ variant="outlined"columns={[{dataIndex: 'name',diff --git a/src/features/Settings/stats/features/usage/UsageTable.tsx b/src/features/Settings/stats/features/usage/UsageTable.tsxindex 0fb535c3012..20dbd38c2c3 100644--- a/src/features/Settings/stats/features/usage/UsageTable.tsx+++ b/src/features/Settings/stats/features/usage/UsageTable.tsx@@ -177,9 +177,11 @@ const UsageTable = memo<UsageChartProps>(({ dateStrings }) => {loading={isLoading}rowKey={(record) => record.id || `${record.model}-${record.createdAt}-${record.provider}`}size="small"- onChange={(_pagination, _filters, sorter) => {- const field = String(sorter.columnKey ?? '');- setSort(sorter.order && SORT_VALUES[field] ? { field, order: sorter.order } : null);+ onChange={(_pagination, _filters, sorterResult) => {+ // Columns sort one at a time; the array form only exists for `multiple` sorters.+ const sorter = Array.isArray(sorterResult) ? sorterResult[0] : sorterResult;+ const field = String(sorter?.columnKey ?? '');+ setSort(sorter?.order && SORT_VALUES[field] ? { field, order: sorter.order } : null);// A re-sort makes the current page a different set of rows; start// from the top rather than dropping the reader into the middle.setPagination({ current: 1 });diff --git a/src/routes/(main)/eval/features/DatasetImportModal/MappingStep.tsx b/src/routes/(main)/eval/features/DatasetImportModal/MappingStep.tsxindex bfa67003a43..de45cf8eb4e 100644--- a/src/routes/(main)/eval/features/DatasetImportModal/MappingStep.tsx+++ b/src/routes/(main)/eval/features/DatasetImportModal/MappingStep.tsx@@ -291,13 +291,13 @@ const MappingStep = memo<MappingStepProps>({/* Data preview table */}<Table- borderedcolumns={columns}dataSource={preview.map((row, i) => ({ ...row, _key: i }))}pagination={false}rowKey="_key"scroll={{ x: scrollX, y: 'calc(95vh - 280px)' }}size="small"+ variant="outlined"/></Flexbox>);