Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(agent): let the gateway discover installed-but-unpinned plugins (#20817)

LiJian59db3fca1b8b
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.installedPlugins.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.installedPlugins.test.ts
new file mode 100644
index 00000000000..a6dcff7419c
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.installedPlugins.test.ts
@@ -0,0 +1,230 @@
+import { type LobeToolManifest, ToolResolver } from '@lobechat/context-engine';
+import { describe, expect, it, vi } from 'vitest';
+
+import { buildToolDiscoveryConfig } from '@/server/modules/AgentRuntime/executorHelpers';
+
+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(),
+}));
+// `isConfigured` decides `gatewayConfigured`, i.e. whether a run routes tool
+// calls through a device gateway β€” the tests flip it to cover both modes.
+const { deviceGatewayState } = vi.hoisted(() => ({ deviceGatewayState: { isConfigured: false } }));
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ get isConfigured() {
+ return deviceGatewayState.isConfigured;
+ },
+ queryDeviceList: vi.fn().mockResolvedValue([]),
+ },
+}));
+
+const FEISHU = 'tituwork-feishu-mcp';
+
+/**
+ * A user-level installed MCP plugin row, shaped like `PluginModel.query()`:
+ * the manifest carries the `api` list the activator's manifest map needs.
+ */
+const installedPlugin = (identifier: string, transport: 'http' | 'stdio' = 'http') => ({
+ customParams: { mcp: { type: transport } },
+ identifier,
+ manifest: {
+ api: [
+ {
+ description: 'Send a message to a Feishu chat',
+ name: 'sendMessage',
+ parameters: { properties: {}, type: 'object' },
+ },
+ ],
+ identifier,
+ meta: { description: 'Feishu MCP', title: 'Feishu MCP' },
+ type: 'mcp',
+ },
+ runtimeType: 'mcp',
+});
+
+interface RunOptions {
+ disabledPluginIds?: string[];
+ /** A device gateway is configured for the deployment. */
+ gatewayConfigured?: boolean;
+ /** The agent's own `plugins` config β€” i.e. what the user pinned. */
+ plugins?: string[];
+ /** Transport the installed plugin row reports. */
+ transport?: 'http' | 'stdio';
+}
+
+const run = (options: RunOptions = {}) => {
+ deviceGatewayState.isConfigured = options.gatewayConfigured ?? false;
+
+ return discoverTools(
+ {
+ agentDocumentsService: { hasDocuments: vi.fn().mockResolvedValue(false) },
+ composioService: { getComposioManifests: vi.fn().mockResolvedValue([]) },
+ connectorModel: { resolveByIdentifiers: vi.fn().mockResolvedValue([]) },
+ connectorToolModel: {
+ queryAllByConnectorIds: vi.fn().mockResolvedValue([]),
+ queryByConnector: vi.fn().mockResolvedValue([]),
+ },
+ db: {} as never,
+ getMarketService: vi.fn().mockResolvedValue({
+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),
+ }),
+ messageModel: { update: vi.fn() },
+ pluginModel: {
+ query: vi.fn().mockResolvedValue([installedPlugin(FEISHU, options.transport ?? 'http')]),
+ },
+ userId: 'user-1',
+ } as never,
+ {
+ agentConfig: { chatConfig: {}, plugins: options.plugins ?? [] },
+ appContext: undefined,
+ canUseDevice: false,
+ model: 'test-model',
+ prompt: 'send a message to the team chat',
+ provider: 'test-provider',
+ resolvedAgentId: 'agent-1',
+ runFacts: { deviceSystemInfo: vi.fn().mockResolvedValue(undefined) },
+ shareGate: undefined,
+ } as never,
+ {
+ disabledPluginIds: options.disabledPluginIds ?? [],
+ globalMemoryEnabled: false,
+ hasMentionedAgents: false,
+ isFixedDeviceTarget: false,
+ loadHistoryMessages: vi.fn().mockResolvedValue([]),
+ 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 β€” installed-but-not-pinned plugins (three-state `auto`)', () => {
+ it('offers an installed `auto` plugin to the activator without enabling it', async () => {
+ const result = await run();
+
+ // Discoverable: the activator resolves against `toolManifestMap`, so a
+ // missing entry here is exactly the "Not found: tituwork-feishu-mcp" the
+ // model used to get.
+ expect(result.toolManifestMap[FEISHU]).toBeDefined();
+ expect(result.toolSourceMap[FEISHU]).toBe('mcp');
+ expect(availableToolIds(result.toolManifestMap, result.toolsResult.enabledToolIds)).toContain(
+ FEISHU,
+ );
+
+ // …but NOT enabled: the pinned-only rules still decide the default tool
+ // set, so the APIs are not offered up-front and the model has to activate.
+ expect(result.toolsResult.enabledToolIds).not.toContain(FEISHU);
+ expect(offeredToolNames(result).some((name) => name.startsWith(`${FEISHU}____`))).toBe(false);
+ });
+
+ it('enables the same plugin directly once the agent pins it', async () => {
+ const result = await run({ plugins: [FEISHU] });
+
+ expect(result.toolsResult.enabledToolIds).toContain(FEISHU);
+ // `<identifier>____<api>____mcp` β€” the MCP plugin type rides on the name.
+ expect(
+ offeredToolNames(result).some((name) => name.startsWith(`${FEISHU}____sendMessage`)),
+ ).toBe(true);
+ // Enabled tools are not listed as available-to-activate.
+ expect(
+ availableToolIds(result.toolManifestMap, result.toolsResult.enabledToolIds),
+ ).not.toContain(FEISHU);
+ });
+
+ it('keeps a disabled plugin out of both paths', async () => {
+ const result = await run({ disabledPluginIds: [FEISHU] });
+
+ expect(result.toolManifestMap[FEISHU]).toBeUndefined();
+ expect(result.toolsResult.enabledToolIds).not.toContain(FEISHU);
+ expect(
+ availableToolIds(result.toolManifestMap, result.toolsResult.enabledToolIds),
+ ).not.toContain(FEISHU);
+ expect(offeredToolNames(result).some((name) => name.startsWith(`${FEISHU}____`))).toBe(false);
+ });
+});
+
+/**
+ * Replay the activator's effect on the operation's tool set: `ToolResolver`
+ * copies the executor map into the operation snapshot and `applyActivation`
+ * never revisits it, so discovery is the only place the dispatch target can be
+ * decided for a tool that only becomes callable mid-run.
+ */
+const activateAfterDiscovery = (
+ result: Awaited<ReturnType<typeof run>>,
+ identifier: string,
+): ReturnType<ToolResolver['resolve']> =>
+ new ToolResolver().resolve(
+ {
+ enabledToolIds: result.toolsResult.enabledToolIds,
+ executorMap: result.toolExecutorMap,
+ manifestMap: result.toolManifestMap,
+ sourceMap: result.toolSourceMap,
+ tools: result.tools ?? [],
+ },
+ { activatedTools: [] },
+ [
+ {
+ activatedAtStep: 1,
+ id: identifier,
+ manifest: result.toolManifestMap[identifier],
+ source: 'discovery',
+ },
+ ],
+ );
+
+describe('discoverTools β€” executor routing for a discoverable MCP plugin', () => {
+ it('keeps a discoverable stdio plugin client-executed across activation', async () => {
+ const result = await run({ transport: 'stdio' });
+
+ // A stdio MCP runs as a local process on the user's machine, so it must
+ // never be dispatched to the self-hosted server.
+ expect(result.toolExecutorMap[FEISHU]).toBe('client');
+
+ const resolved = activateAfterDiscovery(result, FEISHU);
+ expect(resolved.enabledToolIds).toContain(FEISHU);
+ expect(resolved.executorMap?.[FEISHU]).toBe('client');
+ });
+
+ it('leaves a discoverable http plugin on the server execution path', async () => {
+ const result = await run({ transport: 'http' });
+
+ expect(result.toolExecutorMap[FEISHU]).toBeUndefined();
+ expect(activateAfterDiscovery(result, FEISHU).executorMap?.[FEISHU]).toBeUndefined();
+ });
+
+ it('lets a configured device gateway own the route', async () => {
+ const result = await run({ gatewayConfigured: true, transport: 'stdio' });
+
+ // With a gateway every caller converges on the device-gateway path, so no
+ // client executor is set β€” the remote-device proxy resolves the route.
+ expect(result.toolExecutorMap[FEISHU]).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts
index 3e012d5da08..3880054686a 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts
@@ -18,6 +18,7 @@ const {
mockGetAgentConfig,
mockGetUserSettings,
mockMessageCreate,
+ mockPluginQuery,
mockResolveByIdentifiers,
mockScheduleStaleConnectorToolsRefresh,
} = vi.hoisted(() => ({
@@ -30,6 +31,8 @@ const {
mockGetAgentConfig: vi.fn(),
mockGetUserSettings: vi.fn(),
mockMessageCreate: vi.fn(),
+ // Installed MCP plugin rows; empty unless a test seeds one.
+ mockPluginQuery: vi.fn().mockResolvedValue([]),
// Returns `[]` so `connectorsMcp` stays empty β€” we only care about the
// identifier list the share-gate filter allowed through to this call.
mockResolveByIdentifiers: vi.fn().mockResolvedValue([]),
@@ -82,7 +85,7 @@ vi.mock('@/server/services/agent', () => ({
vi.mock('@/database/models/plugin', () => ({
PluginModel: vi.fn().mockImplementation(function () {
return {
- query: vi.fn().mockResolvedValue([]),
+ query: mockPluginQuery,
};
}),
}));
@@ -362,4 +365,55 @@ describe('discoverTools - share gate blocks ungranted connectors early', () => {
visitorUserId: 'visitor-1',
});
});
+
+ it('holds an installed plugin the visitor was not granted out of the tool set', async () => {
+ // An installed-but-unpinned plugin is discoverable by design β€” the share
+ // gate is what keeps a visitor from reaching it (`applyShareGateToToolSet`
+ // prunes the discovery map before the operation starts).
+ const installedMcp = {
+ identifier: 'installed-mcp',
+ manifest: {
+ api: [{ description: 'Ping', name: 'ping' }],
+ identifier: 'installed-mcp',
+ meta: {},
+ type: 'mcp',
+ },
+ runtimeType: 'mcp',
+ };
+ mockPluginQuery.mockResolvedValue([installedMcp]);
+
+ const visitorTurn = (toolGrants: { identifier: string }[]) =>
+ service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Hello',
+ shareGate: {
+ agentId: 'agent-1',
+ shareConfig: { toolGrants },
+ shareId: 'share-1',
+ visitorUserId: 'visitor-1',
+ },
+ });
+
+ await visitorTurn([{ identifier: 'granted-plugin' }]);
+
+ expect(
+ mockCreateOperation.mock.calls[0][0].toolSet.manifestMap['installed-mcp'],
+ ).toBeUndefined();
+
+ // Granted β†’ the visitor's run keeps it, so the prune above is the grant
+ // check and not an accidental blanket drop.
+ vi.clearAllMocks();
+ mockCreateOperation.mockResolvedValue({
+ autoStarted: true,
+ messageId: 'queue-msg-3',
+ operationId: 'op-789',
+ success: true,
+ });
+ mockGetUserSettings.mockResolvedValue({ general: { timezone: 'UTC' } });
+ mockPluginQuery.mockResolvedValue([installedMcp]);
+
+ await visitorTurn([{ identifier: 'granted-plugin' }, { identifier: 'installed-mcp' }]);
+
+ expect(mockCreateOperation.mock.calls[0][0].toolSet.manifestMap['installed-mcp']).toBeDefined();
+ });
});
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
index 031b7a36360..83a2150ef09 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
@@ -20,6 +20,7 @@ import type {
import type { LobeChatDatabase } from '@lobechat/database';
import type { DeviceUnavailableErrorData } from '@lobechat/device-gateway-client';
import {
+ dropInvalidManifests,
readFrozenModelFacts,
resolveClientExecutors,
resolveDiscoveryPool,
@@ -1195,6 +1196,19 @@ export const discoverTools = async (
enabledManifests: manifestMap,
exclusivePluginIds,
executionTarget: executionPlan.target,
+ // Installed-but-not-pinned plugins (`auto` in the three-state plugin
+ // config): the model must be able to discover and activate them mid-run,
+ // exactly as the client runtime lists them from `installedPlugins`.
+ // They never join `enabledToolIds` β€” the engine's rules stay pinned-only
+ // β€” so this widens what the activator can reach, not what the run gets
+ // by default. Disabled ids were dropped in 5a and the pool's own ingest
+ // 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)',
+ ),
lobehubSkills: activeLobehubSkillManifests,
manifestContext,
});
@@ -1203,7 +1217,6 @@ export const discoverTools = async (
Object.assign(
toolExecutorMap,
resolveClientExecutors({
- enabledIds: new Set(manifestMap.keys()),
hasDeviceProxy: gatewayConfigured,
manifestMap: toolManifestMap,
stdioIdentifiers: [
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts
index 6b3b6178687..d52d250a305 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts
@@ -249,4 +249,65 @@ describe('activatorRuntime', () => {
expect(result.state?.notFound).toEqual(['lobe-agent-management']);
});
});
+
+ describe('activateTools β€” installed-but-not-pinned plugins', () => {
+ // The run's discovery pool is what feeds `toolManifestMap`; an installed
+ // plugin the agent never pinned must be resolvable from it even though it
+ // is absent from `enabledToolIds`.
+ const mcpManifest = {
+ api: [{ description: 'Send a message to a Feishu chat', name: 'sendMessage' }],
+ identifier: 'tituwork-feishu-mcp',
+ meta: { title: 'Feishu MCP' },
+ type: 'mcp',
+ };
+
+ it('activates a plugin the run only discovered, and reports the APIs it unlocked', async () => {
+ const { resolveDiscoveryPool } = await import('@lobechat/mecha');
+ const pool = resolveDiscoveryPool({
+ builtinTools: [],
+ enabledManifests: new Map(),
+ executionTarget: 'none',
+ installedManifests: [mcpManifest as never],
+ });
+
+ const { activatorRuntime } = await import('../activator');
+ const runtime = await activatorRuntime.factory({
+ serverDB: {} as never,
+ toolManifestMap: pool.manifestMap,
+ userId: 'user-1',
+ });
+
+ const result = await runtime.activateTools({ identifiers: ['tituwork-feishu-mcp'] });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain(
+ 'Successfully activated tools: tituwork-feishu-mcp.sendMessage',
+ );
+ expect(result.state.notFound).toEqual([]);
+ }, 20_000);
+
+ it('still answers "Not found" for a plugin the run disabled', async () => {
+ const { resolveDiscoveryPool } = await import('@lobechat/mecha');
+ const pool = resolveDiscoveryPool({
+ builtinTools: [],
+ disabledPluginIds: [mcpManifest.identifier],
+ enabledManifests: new Map(),
+ executionTarget: 'none',
+ installedManifests: [mcpManifest as never],
+ });
+ expect(pool.manifestMap).toEqual({});
+
+ const { activatorRuntime } = await import('../activator');
+ const runtime = await activatorRuntime.factory({
+ serverDB: {} as never,
+ toolManifestMap: pool.manifestMap,
+ userId: 'user-1',
+ });
+
+ const result = await runtime.activateTools({ identifiers: ['tituwork-feishu-mcp'] });
+
+ expect(result.content).toContain('Not found: tituwork-feishu-mcp');
+ expect(result.content).not.toContain('Successfully activated');
+ }, 20_000);
+ });
});
diff --git a/packages/mecha/src/toolSet/discoveryPool.test.ts b/packages/mecha/src/toolSet/discoveryPool.test.ts
index 5c6d7121c64..d9a8cd8ace8 100644
--- a/packages/mecha/src/toolSet/discoveryPool.test.ts
+++ b/packages/mecha/src/toolSet/discoveryPool.test.ts
@@ -176,6 +176,81 @@ describe('resolveDiscoveryPool', () => {
expect(pool.manifestMap.gmail).toBeDefined();
});
+ describe('installed-but-not-pinned plugins', () => {
+ // `auto` in the agent's three-state plugin config: installed at the user
+ // level, absent from `agent.plugins`, not disabled. The client runtime
+ // lists these in `<available_tools>`; the gateway must not diverge.
+ const installed = (identifier: string) =>
+ manifest(identifier, { meta: { title: identifier }, type: 'mcp' });
+
+ it('seeds them as discoverable, without touching the enabled set', () => {
+ const pool = resolveDiscoveryPool(
+ request({
+ builtinTools: [],
+ enabledManifests: new Map([['my-plugin', manifest('my-plugin')]]),
+ installedManifests: [installed('feishu-mcp'), installed('github-mcp')],
+ }),
+ );
+
+ expect(pool.manifestMap['feishu-mcp']).toBeDefined();
+ expect(pool.manifestMap['github-mcp']).toBeDefined();
+ // Every installed plugin executes through the MCP path.
+ expect(pool.sourceMap['feishu-mcp']).toBe('mcp');
+
+ // The source is additive: what the engine enabled is unchanged, and the
+ // pool carries no notion of "enabled" of its own β€” `enabledToolIds` is
+ // computed elsewhere from the rules.
+ expect(Object.keys(pool.manifestMap)).toEqual(['my-plugin', 'feishu-mcp', 'github-mcp']);
+ });
+
+ it('never overrides an identifier another source already answered for', () => {
+ // A pinned plugin keeps the engine's manifest (and so keeps its own
+ // routing rather than being relabelled as a fresh MCP plugin).
+ const pinned = manifest('feishu-mcp', { meta: { title: 'Pinned' } });
+ const pin = resolveDiscoveryPool(
+ request({
+ enabledManifests: new Map([['feishu-mcp', pinned]]),
+ installedManifests: [installed('feishu-mcp')],
+ }),
+ );
+ expect(pin.manifestMap['feishu-mcp']).toBe(pinned);
+ expect(pin.sourceMap['feishu-mcp']).toBeUndefined();
+
+ // A connector family outranks the same-named leftover plugin row.
+ const family = resolveDiscoveryPool(
+ request({ composio: [manifest('gmail')], installedManifests: [installed('gmail')] }),
+ );
+ expect(family.sourceMap.gmail).toBe('composio');
+ });
+
+ it('keeps every wall on the new source', () => {
+ const disabled = resolveDiscoveryPool(
+ request({
+ disabledPluginIds: ['feishu-mcp'],
+ installedManifests: [installed('feishu-mcp')],
+ }),
+ );
+ expect(disabled.manifestMap['feishu-mcp']).toBeUndefined();
+ expect(disabled.sourceMap['feishu-mcp']).toBeUndefined();
+
+ const exclusive = resolveDiscoveryPool(
+ request({
+ exclusivePluginIds: ['my-plugin'],
+ installedManifests: [installed('feishu-mcp')],
+ }),
+ );
+ expect(Object.keys(exclusive.manifestMap)).toEqual(['my-plugin']);
+
+ const noDevice = resolveDiscoveryPool(
+ request({
+ deviceAccess: { canUseDevice: false, deviceLocked: false },
+ installedManifests: [installed(LocalSystemManifest.identifier)],
+ }),
+ );
+ expect(noDevice.manifestMap[LocalSystemManifest.identifier]).toBeUndefined();
+ });
+ });
+
describe('context-aware builtin manifests', () => {
const agentManagement = {
identifier: AgentManagementManifest.identifier,
@@ -215,22 +290,55 @@ describe('resolveDiscoveryPool', () => {
});
describe('resolveClientExecutors', () => {
+ const manifestMap = {
+ 'local': manifest('local', { executors: ['client'] }),
+ 'server': manifest('server'),
+ 'stdio-mcp': manifest('stdio-mcp', { type: 'mcp' }),
+ };
+
it('marks client-executed and stdio tools only without a gateway', () => {
- const manifestMap = {
- 'local': manifest('local', { executors: ['client'] }),
- 'server': manifest('server'),
- 'stdio-mcp': manifest('stdio-mcp'),
- };
expect(
resolveClientExecutors({
- enabledIds: new Set(['stdio-mcp']),
hasDeviceProxy: false,
manifestMap,
- stdioIdentifiers: ['stdio-mcp', 'not-enabled'],
+ stdioIdentifiers: ['stdio-mcp', 'no-manifest'],
}),
).toEqual({ 'local': 'client', 'stdio-mcp': 'client' });
+
+ // With a gateway the executor stays unset: every caller converges on the
+ // device-gateway route, and marking the client here would bypass it.
+ expect(
+ resolveClientExecutors({
+ hasDeviceProxy: true,
+ manifestMap,
+ stdioIdentifiers: ['stdio-mcp'],
+ }),
+ ).toEqual({});
+ });
+
+ it('marks a stdio plugin that is only discoverable, not enabled', () => {
+ // The activator can enable `stdio-mcp` mid-run. `ToolResolver` copies this
+ // map into the operation snapshot and `applyActivation` never revisits it,
+ // so an id left out here would be dispatched to the server β€” running the
+ // user's local MCP command there instead of on their machine.
+ expect(
+ resolveClientExecutors({
+ hasDeviceProxy: false,
+ manifestMap: { 'stdio-mcp': manifestMap['stdio-mcp'] },
+ stdioIdentifiers: ['stdio-mcp'],
+ }),
+ ).toEqual({ 'stdio-mcp': 'client' });
+ });
+
+ it('never marks a plugin that is not stdio', () => {
+ // An http MCP plugin in the same pool keeps running through the server's
+ // MCP path; only the stdio list is client-executed.
expect(
- resolveClientExecutors({ enabledIds: new Set(), hasDeviceProxy: true, manifestMap }),
+ resolveClientExecutors({
+ hasDeviceProxy: false,
+ manifestMap: { 'http-mcp': manifest('http-mcp', { type: 'mcp' }) },
+ stdioIdentifiers: [],
+ }),
).toEqual({});
});
});
diff --git a/packages/mecha/src/toolSet/discoveryPool.ts b/packages/mecha/src/toolSet/discoveryPool.ts
index 6103d518751..6bcf2115ea6 100644
--- a/packages/mecha/src/toolSet/discoveryPool.ts
+++ b/packages/mecha/src/toolSet/discoveryPool.ts
@@ -72,6 +72,16 @@ export interface DiscoveryPoolRequest {
enabledManifests: ReadonlyMap<string, LobeToolManifest>;
exclusivePluginIds?: readonly string[];
executionTarget: DeviceExecutionTarget;
+ /**
+ * Installed plugins the run may DISCOVER but must never enable by itself β€”
+ * the three-state plugin config's `auto` mode (installed, not pinned, not
+ * disabled). They are seeded last and only for identifiers nothing else in
+ * the pool already covers, so an enabled manifest, a discoverable builtin
+ * or a connector family keeps this run's manifest and routing. Nothing here
+ * reaches the enable rules: `enabledToolIds` stays pinned-only, and the
+ * activator is the only way one of these becomes callable.
+ */
+ installedManifests?: readonly LobeToolManifest[];
/** Disabled-filtered LobeHub skill manifests. */
lobehubSkills?: readonly LobeToolManifest[];
/**
@@ -94,8 +104,9 @@ export interface DiscoveryPool {
/**
* The pool the activator may resolve tools from mid-run: the enabled
- * manifests, every discoverable builtin the walls allow, and the connector
- * families. Device and sandbox tools only appear when the run can reach
+ * manifests, every discoverable builtin the walls allow, the connector
+ * families, and the installed plugins the run may activate but not enable on
+ * its own. Device and sandbox tools only appear when the run can reach
* them β€” explicit activation bypasses the enable rules, so what is not
* reachable must not be discoverable at all.
*/
@@ -189,12 +200,27 @@ export const resolveDiscoveryPool = (request: DiscoveryPoolRequest): DiscoveryPo
ingestFamily(request.lobehubSkills ?? [], 'lobehubSkill');
ingestFamily(request.composio ?? [], 'composio');
+ // Installed-but-not-pinned plugins (`auto` in the agent's three-state
+ // plugin config): discoverable exactly like the client runtime lists them
+ // from `installedPlugins`, yet never part of the run's enabled set β€” the
+ // activator is what turns one into a callable tool. Seeded last and only
+ // where nothing above already answered for the identifier, so a pinned
+ // manifest, a discoverable builtin or a connector family always wins.
+ for (const manifest of request.installedManifests ?? []) {
+ const identifier = manifest?.identifier;
+ if (!identifier) continue;
+ if (manifestMap[identifier]) continue;
+ if (!isManifestIngestAllowed(identifier)) continue;
+ manifestMap[identifier] = manifest;
+ // Every installed plugin executes through the MCP path, matching the
+ // client's own labelling of them.
+ sourceMap[identifier] = 'mcp';
+ }
+
return { isManifestIngestAllowed, manifestMap, sourceMap };
};
export interface ClientExecutorsRequest {
- /** Identifiers the engine enabled for this run. */
- enabledIds: ReadonlySet<string>;
/** A device gateway exists; tool calls tunnel to a registered device. */
hasDeviceProxy: boolean;
manifestMap: Readonly<Record<string, LobeToolManifest>>;
@@ -207,6 +233,14 @@ export interface ClientExecutorsRequest {
* marked for direct client dispatch only in the standalone deployment: with a
* gateway every caller converges on the device-gateway path and the executor
* stays unset so the remote-device proxy resolves the route.
+ *
+ * A stdio entry is recognised by being *part of this run's pool*, not by being
+ * enabled. The activator can turn a discoverable-but-unpinned plugin into a
+ * callable tool mid-run, and `ToolResolver.applyActivation` adds it without
+ * re-running this pass β€” an id left out here would be dispatched to the server
+ * and run the user's local MCP command there instead of on their machine.
+ * Marking the whole pool up front costs nothing: an executor entry for a tool
+ * nobody calls is inert, and a share run prunes what it does not grant.
*/
export const resolveClientExecutors = (
request: ClientExecutorsRequest,
@@ -218,7 +252,7 @@ export const resolveClientExecutors = (
executorMap[id] = 'client';
}
for (const id of request.stdioIdentifiers ?? []) {
- if (request.enabledIds.has(id)) executorMap[id] = 'client';
+ if (request.manifestMap[id]) executorMap[id] = 'client';
}
return executorMap;
};