π€― 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-builder): refuse to pin plugin ids that load no tools (#20063)
Arvin Xuc281bd088c20
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.tsindex 2464b20bb8b..be64177211a 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts@@ -7,6 +7,10 @@ import { agentBuilderRuntime } from '../agentBuilder';const {mockCreatePlugin,mockFindById,+ mockGetMcpManifest,+ mockQueryPlugins,+ mockResolveConnectors,+ mockUpdatePlugin,mockGetAgentConfigById,mockGetAiProviderList,mockGetAiProviderModelList,@@ -17,6 +21,10 @@ const {} = vi.hoisted(() => ({mockCreatePlugin: vi.fn(),mockFindById: vi.fn(),+ mockGetMcpManifest: vi.fn(),+ mockQueryPlugins: vi.fn(),+ mockResolveConnectors: vi.fn(),+ mockUpdatePlugin: vi.fn(),mockGetAgentConfigById: vi.fn(),mockGetAiProviderList: vi.fn(),mockGetAiProviderModelList: vi.fn(),@@ -52,10 +60,18 @@ vi.mock('@/database/models/plugin', () => ({return {create: mockCreatePlugin,findById: mockFindById,+ query: mockQueryPlugins,+ update: mockUpdatePlugin,};}),}));+vi.mock('@/database/models/connector', () => ({+ ConnectorModel: vi.fn(function () {+ return { resolveAll: mockResolveConnectors };+ }),+}));+vi.mock('@/database/repositories/aiInfra', () => ({AiInfraRepos: vi.fn(function () {return {@@ -67,7 +83,7 @@ vi.mock('@/database/repositories/aiInfra', () => ({vi.mock('@/server/services/discover', () => ({DiscoverService: vi.fn(function () {- return {};+ return { getMcpManifest: mockGetMcpManifest };}),}));@@ -93,6 +109,10 @@ describe('agentBuilderRuntime', () => {vi.clearAllMocks();mockServiceUpdateConfig.mockImplementation((...args) => mockUpdateConfig(...args));mockGetHiddenBuiltinModelsForUser.mockResolvedValue(undefined);+ mockResolveConnectors.mockResolvedValue([]);+ mockQueryPlugins.mockResolvedValue([]);+ mockFindById.mockResolvedValue(undefined);+ mockGetMcpManifest.mockRejectedValue(new Error('not in marketplace'));});it('does not persist a model change rejected by the shared-agent policy', async () => {@@ -149,6 +169,7 @@ describe('agentBuilderRuntime', () => {describe('updateConfig - togglePlugin', () => {it('appends a new pinned entry when enabling an absent identifier', async () => {mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: ['plugin-a'] });+ mockFindById.mockResolvedValue({ identifier: 'plugin-b', manifest: { api: [] } });const runtime = createRuntime();const result = await runtime.updateConfig(@@ -168,6 +189,7 @@ describe('agentBuilderRuntime', () => {id: 'agent-1',plugins: ['plugin-a', { identifier: 'plugin-b', mode: 'disabled' }],});+ mockFindById.mockResolvedValue({ identifier: 'plugin-b', manifest: { api: [] } });const runtime = createRuntime();const result = await runtime.updateConfig(@@ -199,6 +221,89 @@ describe('agentBuilderRuntime', () => {expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', { plugins: ['plugin-a'] });});+ // Vent msg_3TSVUmdD8G68gRPPKH: `tg_mcp` was reported enabled while the+ // user's connector is `tg-mcp`, so the agent pinned an id that loads nothing.+ it('refuses to enable an id that resolves to nothing and suggests the near match', async () => {+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: ['lobe-message'] });+ mockResolveConnectors.mockResolvedValue([+ { identifier: 'tg-mcp', isEnabled: true, status: 'connected' },+ ]);++ const runtime = createRuntime();+ const result = await runtime.updateConfig(+ {+ meta: { title: 'Telegram Analyst' },+ togglePlugin: { enabled: true, pluginId: 'tg_mcp' },+ } as never,+ { editingAgentId: 'agent-1', toolManifestMap: {} },+ );++ expect(result.success).toBe(false);+ expect(result.error).toMatchObject({ type: 'PluginNotFound' });+ expect(result.content).toContain('"tg-mcp"');+ expect(mockResolveConnectors).toHaveBeenCalledWith('agent-1');+ expect(mockUpdateConfig).not.toHaveBeenCalled();+ expect(mockUpdateAgent).not.toHaveBeenCalled();+ });++ it('enables a user connector by its exact identifier', async () => {+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });+ mockResolveConnectors.mockResolvedValue([+ { identifier: 'tg-mcp', isEnabled: true, status: 'connected' },+ ]);++ const result = await createRuntime().updateConfig(+ { togglePlugin: { enabled: true, pluginId: 'tg-mcp' } },+ { editingAgentId: 'agent-1', toolManifestMap: {} },+ );++ expect(result.success).toBe(true);+ expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', {+ plugins: [{ identifier: 'tg-mcp', mode: 'pinned' }],+ });+ });++ it('refuses a connector that exists but is not connected', async () => {+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });+ mockResolveConnectors.mockResolvedValue([+ { identifier: 'gmail', isEnabled: true, status: 'disconnected' },+ ]);++ const result = await createRuntime().updateConfig(+ { togglePlugin: { enabled: true, pluginId: 'gmail' } },+ { editingAgentId: 'agent-1', toolManifestMap: {} },+ );++ expect(result.success).toBe(false);+ expect(result.error).toMatchObject({ type: 'PluginNotConnected' });+ expect(mockUpdateConfig).not.toHaveBeenCalled();+ });++ it('refuses an official catalog integration the user never connected', async () => {+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });++ const result = await createRuntime().updateConfig(+ { togglePlugin: { enabled: true, pluginId: 'gmail' } },+ { editingAgentId: 'agent-1', toolManifestMap: {} },+ );++ expect(result.success).toBe(false);+ expect(result.error).toMatchObject({ type: 'PluginNotConnected' });+ expect(mockUpdateConfig).not.toHaveBeenCalled();+ });++ it('still disables an id that no longer resolves, so stale entries can be removed', async () => {+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: ['tg_mcp'] });++ const result = await createRuntime().updateConfig(+ { togglePlugin: { enabled: false, pluginId: 'tg_mcp' } },+ { editingAgentId: 'agent-1', toolManifestMap: {} },+ );++ expect(result.success).toBe(true);+ expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', { plugins: [] });+ });+it('returns the invocation target for a successful no-op', async () => {mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });@@ -328,6 +433,84 @@ describe('agentBuilderRuntime', () => {});});+ describe('installPlugin - market resolution', () => {+ it('refuses an installed plugin whose manifest lists no tools', async () => {+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });+ mockFindById.mockResolvedValue({+ identifier: 'adkit',+ manifest: { identifier: 'adkit', type: 'mcp', url: 'https://mcp.adkit.so' },+ type: 'customPlugin',+ });++ const result = await createRuntime().installPlugin(+ { identifier: 'adkit', source: 'market' },+ { editingAgentId: 'agent-1', toolManifestMap: {} },+ );++ expect(result.success).toBe(false);+ expect(result.error).toMatchObject({ type: 'PluginHasNoTools' });+ expect(mockGetMcpManifest).not.toHaveBeenCalled();+ expect(mockUpdateConfig).not.toHaveBeenCalled();+ });++ it('writes no row and pins nothing when the marketplace has no manifest', async () => {+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });++ const result = await createRuntime().installPlugin(+ { identifier: 'adkit-ads-mcp', source: 'market' },+ { editingAgentId: 'agent-1', toolManifestMap: {} },+ );++ expect(result.success).toBe(false);+ expect(result.error).toMatchObject({ type: 'PluginNotFound' });+ expect(mockCreatePlugin).not.toHaveBeenCalled();+ expect(mockUpdateConfig).not.toHaveBeenCalled();+ });++ it('installs the marketplace plugin even when a same-named connector exists', async () => {+ const manifest = { api: [{ name: 'send' }], identifier: 'gmail' };+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });+ mockResolveConnectors.mockResolvedValue([+ { identifier: 'gmail', isEnabled: false, status: 'disconnected' },+ ]);+ mockGetMcpManifest.mockResolvedValue(manifest);++ const result = await createRuntime().installPlugin(+ { identifier: 'gmail', source: 'market' },+ { editingAgentId: 'agent-1', toolManifestMap: {} },+ );++ expect(result.success).toBe(true);+ expect(mockCreatePlugin).toHaveBeenCalledWith({+ identifier: 'gmail',+ manifest,+ type: 'plugin',+ });+ });++ it('installs a marketplace plugin with its manifest and says it loads next run', async () => {+ const manifest = { api: [{ name: 'listCampaigns' }], identifier: 'ads-mcp' };+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });+ mockGetMcpManifest.mockResolvedValue(manifest);++ const result = await createRuntime().installPlugin(+ { identifier: 'ads-mcp', source: 'market' },+ { editingAgentId: 'agent-1', toolManifestMap: {} },+ );++ expect(result.success).toBe(true);+ expect(result.content).toContain('next run');+ expect(mockCreatePlugin).toHaveBeenCalledWith({+ identifier: 'ads-mcp',+ manifest,+ type: 'plugin',+ });+ expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', {+ plugins: [{ identifier: 'ads-mcp', mode: 'pinned' }],+ });+ });+ });+// Regression guard for `searchMarketTools` returning `unauthorized`: built// without an identity, DiscoverService signs no trusted-client token, so every// server-executed market search failed β which the model reports as a plaindiff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.tsindex 9205b7c8d89..c01dd147f80 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts@@ -15,10 +15,18 @@ const {mockUpdateConfig,mockFindById,mockCreatePlugin,+ mockGetMcpManifest,+ mockQueryPlugins,+ mockResolveConnectors,+ mockUpdatePlugin,} = vi.hoisted(() => ({mockCountAgents: vi.fn(),mockCreatePlugin: vi.fn(),mockFindById: vi.fn(),+ mockGetMcpManifest: vi.fn(),+ mockQueryPlugins: vi.fn(),+ mockResolveConnectors: vi.fn(),+ mockUpdatePlugin: vi.fn(),mockGetAgentConfigById: vi.fn(),mockGetAssistantList: vi.fn(),mockQueryAgents: vi.fn(),@@ -48,14 +56,23 @@ vi.mock('@/database/models/plugin', () => ({return {create: mockCreatePlugin,findById: mockFindById,+ query: mockQueryPlugins,+ update: mockUpdatePlugin,};}),}));+vi.mock('@/database/models/connector', () => ({+ ConnectorModel: vi.fn(function () {+ return { resolveAll: mockResolveConnectors };+ }),+}));+vi.mock('@/server/services/discover', () => ({DiscoverService: vi.fn(function () {return {getAssistantList: mockGetAssistantList,+ getMcpManifest: mockGetMcpManifest,};}),}));@@ -88,6 +105,9 @@ describe('agentManagementRuntime', () => {beforeEach(() => {vi.clearAllMocks();mockServiceUpdateConfig.mockImplementation((...args) => mockUpdateConfig(...args));+ mockResolveConnectors.mockResolvedValue([]);+ mockQueryPlugins.mockResolvedValue([]);+ mockGetMcpManifest.mockRejectedValue(new Error('not in marketplace'));});it('does not persist a model change rejected by the shared-agent policy', async () => {@@ -401,26 +421,108 @@ describe('agentManagementRuntime', () => {});describe('installPlugin', () => {- it('appends a new pinned entry when the identifier is absent', async () => {+ it('installs a marketplace plugin with its manifest and pins it', async () => {+ const manifest = { api: [{ name: 'run' }], identifier: 'plugin-b' };mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: ['plugin-a'] });mockFindById.mockResolvedValue(undefined);+ mockGetMcpManifest.mockResolvedValue(manifest);const runtime = createRuntime();- const result = await runtime.installPlugin({ agentId: 'agent-1', identifier: 'plugin-b' });+ const result = await runtime.installPlugin({+ agentId: 'agent-1',+ identifier: 'plugin-b',+ source: 'market',+ });expect(result.success).toBe(true);- expect(mockCreatePlugin).toHaveBeenCalledWith({ identifier: 'plugin-b', type: 'plugin' });+ expect(result.content).toContain('next run');+ expect(mockCreatePlugin).toHaveBeenCalledWith({+ identifier: 'plugin-b',+ manifest,+ type: 'plugin',+ });expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', {plugins: ['plugin-a', { identifier: 'plugin-b', mode: 'pinned' }],});});+ // Vent msg_f46kelJyavbcB2Xkz9: `adkit` was a custom MCP behind OAuth whose+ // manifest never listed tools; installPlugin reported success while every+ // activateTools call returned "Not found".+ it('refuses an installed plugin whose manifest lists no tools', async () => {+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });+ mockFindById.mockResolvedValue({+ identifier: 'adkit',+ manifest: { identifier: 'adkit', type: 'mcp', url: 'https://mcp.adkit.so' },+ type: 'customPlugin',+ });++ const result = await createRuntime().installPlugin({+ agentId: 'agent-1',+ identifier: 'adkit',+ source: 'market',+ });++ expect(result.success).toBe(false);+ expect(result.error).toMatchObject({ type: 'PluginHasNoTools' });+ expect(result.content).toContain('Connectors');+ expect(mockUpdateConfig).not.toHaveBeenCalled();+ });++ it('writes no bare row for an id the marketplace does not know', async () => {+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });+ mockFindById.mockResolvedValue(undefined);++ const result = await createRuntime().installPlugin({+ agentId: 'agent-1',+ identifier: 'adkit-ads-mcp',+ source: 'market',+ });++ expect(result.success).toBe(false);+ expect(result.error).toMatchObject({ type: 'PluginNotFound' });+ expect(mockCreatePlugin).not.toHaveBeenCalled();+ expect(mockUpdateConfig).not.toHaveBeenCalled();+ });++ it('refuses an official integration that is not connected', async () => {+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });+ mockFindById.mockResolvedValue(undefined);++ const result = await createRuntime().installPlugin({+ agentId: 'agent-1',+ identifier: 'gmail',+ source: 'official',+ });++ expect(result.success).toBe(false);+ expect(result.error).toMatchObject({ type: 'PluginNotConnected' });+ expect(mockUpdateConfig).not.toHaveBeenCalled();+ });++ it('pins a builtin tool without registering a plugin row', async () => {+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });++ const result = await createRuntime().installPlugin({+ agentId: 'agent-1',+ identifier: 'lobe-web-browsing',+ source: 'official',+ });++ expect(result.success).toBe(true);+ expect(result.content).not.toContain('next run');+ expect(mockCreatePlugin).not.toHaveBeenCalled();+ expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', {+ plugins: [{ identifier: 'lobe-web-browsing', mode: 'pinned' }],+ });+ });+it('flips an existing disabled object entry back to pinned in place, without duplicating it', async () => {mockGetAgentConfigById.mockResolvedValue({id: 'agent-1',plugins: ['plugin-a', { identifier: 'plugin-b', mode: 'disabled' }],});- mockFindById.mockResolvedValue({ identifier: 'plugin-b' });+ mockFindById.mockResolvedValue({ identifier: 'plugin-b', manifest: { api: [] } });const runtime = createRuntime();const result = await runtime.installPlugin({ agentId: 'agent-1', identifier: 'plugin-b' });@@ -436,7 +538,7 @@ describe('agentManagementRuntime', () => {id: 'agent-1',plugins: ['plugin-a', 'plugin-b'],});- mockFindById.mockResolvedValue({ identifier: 'plugin-b' });+ mockFindById.mockResolvedValue({ identifier: 'plugin-b', manifest: { api: [] } });const runtime = createRuntime();const result = await runtime.installPlugin({ agentId: 'agent-1', identifier: 'plugin-b' });diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.tsindex fefef9ef0c5..051eb2689ec 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts@@ -14,6 +14,7 @@ import { getPluginMode, upsertPluginMode } from '@lobechat/types';import { getHiddenBuiltinModelsForUser } from '@/business/server/aiProvider';import { AgentModel } from '@/database/models/agent';+import { ConnectorModel } from '@/database/models/connector';import { PluginModel } from '@/database/models/plugin';import { AiInfraRepos } from '@/database/repositories/aiInfra';import { AgentService } from '@/server/services/agent';@@ -21,6 +22,12 @@ import { DiscoverService } from '@/server/services/discover';import { filterHiddenProviderModels } from '@/utils/aiProvider';import { type ToolExecutionContext, type ToolExecutionResult } from '../types';+import {+ NEXT_RUN_NOTE,+ resolveOrInstallMarketPlugin,+ resolvePluginIdentifier,+ unresolvablePluginResult,+} from './pluginResolution';import { type ServerRuntimeRegistration } from './types';const MAX_MODELS = 20;@@ -53,6 +60,7 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {const agentModel = new AgentModel(context.serverDB, userId, context.workspaceId);const agentService = new AgentService(context.serverDB, userId, context.workspaceId);const pluginModel = new PluginModel(context.serverDB, userId, context.workspaceId);+ const connectorModel = new ConnectorModel(context.serverDB, userId, context.workspaceId);const aiInfraRepos = new AiInfraRepos(context.serverDB, userId, {}, context.workspaceId);/*** Market list endpoints require an authenticated caller, and `DiscoverService`@@ -214,6 +222,20 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {const isEnabled = getPluginMode(agent.plugins ?? undefined, pluginId) === 'pinned';const shouldEnable = enabled !== undefined ? enabled : !isEnabled;+ // Enabling pins the id into the agent's config; an id that resolves+ // to no loadable tool would be reported as enabled yet never load.+ // Checked before any write so a rejected call changes nothing.+ // Disabling stays unvalidated so stale entries can always be removed.+ if (shouldEnable) {+ const resolution = await resolvePluginIdentifier(+ pluginId,+ { connectorModel, pluginModel },+ { agentId },+ );+ if (resolution.status !== 'loadable')+ return unresolvablePluginResult(pluginId, resolution);+ }+// upsertPluginMode preserves an already-matching entry as-is and// flips a disabled entry back to pinned in place, instead of// blindly pushing a duplicate bare-string identifier.@@ -337,23 +359,13 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {return { content: `Agent "${agentId}" not found.`, success: false };}- const existing = await pluginModel.findById(identifier);- if (!existing) {- let manifest: any;- try {- manifest = await discoverService.getMcpManifest({ identifier });- } catch {- // proceed without manifest if fetch fails; tool will be unusable until manifest loads- }- await pluginModel.create({ identifier, manifest: manifest as any, type: 'plugin' });- } else if (!existing.manifest) {- try {- const manifest = await discoverService.getMcpManifest({ identifier });- await pluginModel.update(identifier, { manifest: manifest as any });- } catch {- // best-effort backfill- }- }+ const { installedNow, resolution } = await resolveOrInstallMarketPlugin(+ identifier,+ { connectorModel, discoverService, pluginModel },+ { agentId, source: 'market' },+ );+ if (resolution.status !== 'loadable')+ return unresolvablePluginResult(identifier, resolution);if (getPluginMode(agent.plugins ?? undefined, identifier) !== 'pinned') {await agentModel.updateConfig(agentId, {@@ -366,7 +378,7 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {}return {- content: `Successfully enabled plugin "${identifier}" for agent "${agentId}"`,+ content: `Successfully enabled plugin "${identifier}" for agent "${agentId}".${installedNow ? NEXT_RUN_NOTE : ''}`,state: { agentId, installed: true, pluginId: identifier, success: true },success: true,};diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.tsindex 2fcb5df6ad2..a266c90eb65 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts@@ -19,11 +19,17 @@ import {} from '@lobechat/types';import { AgentModel } from '@/database/models/agent';+import { ConnectorModel } from '@/database/models/connector';import { PluginModel } from '@/database/models/plugin';import { AgentService } from '@/server/services/agent';import { DiscoverService } from '@/server/services/discover';import { type ToolExecutionContext, type ToolExecutionResult } from '../types';+import {+ NEXT_RUN_NOTE,+ resolveOrInstallMarketPlugin,+ unresolvablePluginResult,+} from './pluginResolution';import { type ServerRuntimeRegistration } from './types';const handleError = (error: unknown, message: string): ToolExecutionResult => {@@ -43,6 +49,11 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {const agentModel = new AgentModel(context.serverDB, context.userId, context.workspaceId);const agentService = new AgentService(context.serverDB, context.userId, context.workspaceId);const pluginModel = new PluginModel(context.serverDB, context.userId, context.workspaceId);+ const connectorModel = new ConnectorModel(+ context.serverDB,+ context.userId,+ context.workspaceId,+ );// Same identity requirement as the Agent Builder runtime: built without an// identity, DiscoverService sends no credentials and every market read fails// as `unauthorized`.@@ -240,18 +251,23 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {installPlugin: async (params: InstallPluginParams): Promise<ToolExecutionResult> => {try {- const { agentId, identifier } = params;+ const { agentId, identifier, source } = params;const agent = await agentModel.getAgentConfigById(agentId);if (!agent) {return { content: `Agent "${agentId}" not found.`, success: false };}- // Ensure the plugin is registered in user_installed_plugins so that- // PluginModel.query() can resolve its manifest during agent execution.- const existing = await pluginModel.findById(identifier);- if (!existing) {- await pluginModel.create({ identifier, type: 'plugin' });- }+ // Pin only an id the runtime can load: a builtin, a connector, or a+ // plugin whose manifest lists its APIs (fetched from the marketplace+ // when not installed yet). Registering a bare row here used to report+ // success for ids that never produced a tool.+ const { installedNow, resolution } = await resolveOrInstallMarketPlugin(+ identifier,+ { connectorModel, discoverService, pluginModel },+ { agentId, source },+ );+ if (resolution.status !== 'loadable')+ return unresolvablePluginResult(identifier, resolution);// upsertPluginMode preserves an already-pinned entry (string or// object) as-is and flips a disabled entry back to pinned in place,@@ -267,7 +283,7 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {}return {- content: `Successfully enabled plugin "${identifier}" for agent "${agentId}"`,+ content: `Successfully enabled plugin "${identifier}" for agent "${agentId}".${installedNow ? NEXT_RUN_NOTE : ''}`,state: { installed: true, pluginId: identifier, success: true },success: true,};diff --git a/apps/server/src/services/toolExecution/serverRuntimes/pluginResolution.ts b/apps/server/src/services/toolExecution/serverRuntimes/pluginResolution.tsnew file mode 100644index 00000000000..e23e7379b96--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/pluginResolution.ts@@ -0,0 +1,169 @@+import { builtinTools } from '@lobechat/builtin-tools';+import { getConnectorCatalog } from '@lobechat/const';++import type { ConnectorModel } from '@/database/models/connector';+import type { PluginModel } from '@/database/models/plugin';++import type { ToolExecutionResult } from '../types';++/**+ * Whether a plugin id an agent-editing tool is about to pin resolves to tools+ * the runtime can actually load:+ *+ * - `loadable`: a builtin, an enabled and connected connector, or an installed+ * plugin whose manifest lists its APIs.+ * - `not-connected`: an official integration or a user connector that exists+ * but is disabled / not connected, so it contributes no tools yet.+ * - `no-tools`: installed, but the manifest has no API list, so the tool pool+ * drops it on every run (e.g. a custom MCP behind OAuth that was never+ * connected).+ * - `unknown`: nothing by that id; `suggestions` holds near matches such as+ * `tg-mcp` for `tg_mcp`.+ */+export type PluginResolution =+ | { source: 'builtin' | 'connector' | 'installed'; status: 'loadable' }+ | { status: 'no-tools' }+ | { status: 'not-connected' }+ | { status: 'unknown'; suggestions: string[] };++export interface PluginResolverDeps {+ connectorModel: Pick<ConnectorModel, 'resolveAll'>;+ pluginModel: Pick<PluginModel, 'findById' | 'query'>;+}++const catalogIdentifiers = (): string[] =>+ getConnectorCatalog({ composio: true, lobehub: true }).map((item) =>+ item.type === 'lobehub' ? item.provider.id : item.serverType.identifier,+ );++/** Mirrors the tool pool's validity check, which drops manifests without an `api` array. */+export const hasLoadableApis = (manifest: unknown): boolean =>+ Array.isArray((manifest as { api?: unknown } | null | undefined)?.api);++const normalize = (id: string) => id.toLowerCase().replaceAll(/[\s_.]+/g, '-');++export const resolvePluginIdentifier = async (+ identifier: string,+ deps: PluginResolverDeps,+ options: { agentId?: string } = {},+): Promise<PluginResolution> => {+ if (builtinTools.some((tool) => tool.identifier === identifier))+ return { source: 'builtin', status: 'loadable' };++ // A connector shadows a same-named installed plugin, but only once it is+ // enabled and connected β a disabled or disconnected row contributes no tools.+ const connectors = await deps.connectorModel.resolveAll(options.agentId);+ const connector = connectors.find((c) => c.identifier === identifier);+ if (connector) {+ return connector.isEnabled && connector.status === 'connected'+ ? { source: 'connector', status: 'loadable' }+ : { status: 'not-connected' };+ }++ const installed = await deps.pluginModel.findById(identifier);+ if (installed) {+ return hasLoadableApis(installed.manifest)+ ? { source: 'installed', status: 'loadable' }+ : { status: 'no-tools' };+ }++ const catalog = catalogIdentifiers();+ if (catalog.includes(identifier)) return { status: 'not-connected' };++ const installedIds = (await deps.pluginModel.query()).map((p) => p.identifier);+ const target = normalize(identifier);+ const suggestions = [+ ...new Set([...connectors.map((c) => c.identifier), ...installedIds, ...catalog]),+ ].filter((id) => normalize(id) === target);++ return { status: 'unknown', suggestions };+};++/** The failure returned instead of pinning an id that would load no tools. */+export const unresolvablePluginResult = (+ identifier: string,+ resolution: Exclude<PluginResolution, { status: 'loadable' }>,+): ToolExecutionResult => {+ if (resolution.status === 'no-tools') {+ return {+ content: `Plugin "${identifier}" is installed but exposes no tools, so enabling it would not make any tool available. Its manifest has no API list β an MCP server that needs OAuth must be connected by the user in Settings β Connectors first. Nothing was changed.`,+ error: { message: 'Plugin has no loadable tools', type: 'PluginHasNoTools' },+ success: false,+ };+ }++ if (resolution.status === 'not-connected') {+ return {+ content: `"${identifier}" is an integration that is not connected (or is disabled), so it provides no tools yet. Ask the user to connect it in Settings β Connectors, then enable it. Nothing was changed.`,+ error: { message: 'Integration is not connected', type: 'PluginNotConnected' },+ success: false,+ };+ }++ const hint =+ resolution.suggestions.length > 0+ ? ` Did you mean: ${resolution.suggestions.map((id) => `"${id}"`).join(', ')}?`+ : ' Use an exact identifier from the available plugins or connectors, or search the marketplace first.';++ return {+ content: `No builtin tool, connector or installed plugin has the identifier "${identifier}".${hint} Nothing was changed.`,+ error: { message: 'Unknown plugin identifier', type: 'PluginNotFound' },+ success: false,+ };+};++export interface MarketPluginDeps extends PluginResolverDeps {+ discoverService: { getMcpManifest: (params: { identifier: string }) => Promise<unknown> };+ pluginModel: PluginResolverDeps['pluginModel'] & Pick<PluginModel, 'create' | 'update'>;+}++/**+ * Resolve a plugin id for `installPlugin`. A `market` install is satisfied by+ * the marketplace plugin itself: an installed row with APIs, or a manifest+ * fetched now β a same-named builtin, catalog id or connector does not count+ * as that install. Only when the marketplace has nothing does it fall back to+ * the source-agnostic resolution. A row is written only when the fetched+ * manifest lists its APIs, and a custom plugin's own manifest is never+ * overwritten.+ *+ * `installedNow` is true when this call created or filled the row: such a tool+ * was not in the current run's tool pool, so it loads from the next run.+ */+export const resolveOrInstallMarketPlugin = async (+ identifier: string,+ deps: MarketPluginDeps,+ options: { agentId?: string; source?: string } = {},+): Promise<{ installedNow: boolean; resolution: PluginResolution }> => {+ if (options.source !== 'market')+ return {+ installedNow: false,+ resolution: await resolvePluginIdentifier(identifier, deps, options),+ };++ const existing = await deps.pluginModel.findById(identifier);+ if (existing && hasLoadableApis(existing.manifest))+ return { installedNow: false, resolution: { source: 'installed', status: 'loadable' } };+ if (existing?.manifest) return { installedNow: false, resolution: { status: 'no-tools' } };++ let manifest: unknown;+ try {+ manifest = await deps.discoverService.getMcpManifest({ identifier });+ } catch {+ // Not a marketplace plugin (or the market is unreachable).+ }++ if (hasLoadableApis(manifest)) {+ if (existing) await deps.pluginModel.update(identifier, { manifest: manifest as any });+ else await deps.pluginModel.create({ identifier, manifest: manifest as any, type: 'plugin' });++ return { installedNow: true, resolution: { source: 'installed', status: 'loadable' } };+ }++ return {+ installedNow: false,+ resolution: await resolvePluginIdentifier(identifier, deps, options),+ };+};++export const NEXT_RUN_NOTE =+ ' Its tools load when the agent starts its next run; activateTools cannot reach them in a run that is already in progress.';