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.

โ™ป๏ธ refactor(mecha): assemble the tool manifest pool in the shared core (#19616)

Arvin Xu6f64c187b141
diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
index e3dcc3b3d34..852ef3bc05d 100644
--- a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
@@ -12,8 +12,8 @@
import { builtinTools } from '@lobechat/builtin-tools';
import { createEnableChecker, type LobeToolManifest } from '@lobechat/context-engine';
import { ToolsEngine } from '@lobechat/context-engine';
-import { resolveToolRules } from '@lobechat/mecha';
-import { type BuiltinToolManifest, type RuntimePlatform } from '@lobechat/types';
+import { assembleManifestPool, resolveToolRules } from '@lobechat/mecha';
+import { type RuntimePlatform } from '@lobechat/types';
import debug from 'debug';
import { isDeviceLockedPlan, resolveExecutionTarget } from '@/helpers/executionTarget';
@@ -34,46 +34,6 @@ export type {
const log = debug('lobe-server:agent-tools-engine');
-/**
- * A manifest is usable by ToolsEngine only if it has an `api` array.
- * ToolsEngine.convertManifestsToTools calls `manifest.api.map(...)`
- * unconditionally, so any entry with `api` missing / non-array crashes the
- * whole tools build โ€” and with it every execAgent call of the affected user.
- * Installed-plugin manifests come straight from a DB jsonb column with no
- * schema validation, so guard defensively at the merge point. Mirrors the
- * frontend `dropInvalidManifests` in `src/helpers/toolEngineering`.
- */
-const isValidToolManifest = (m: LobeToolManifest | undefined): m is LobeToolManifest =>
- !!m && typeof m === 'object' && Array.isArray((m as LobeToolManifest).api);
-
-const dropInvalidManifests = (
- manifests: (LobeToolManifest | undefined)[],
- source: string,
-): LobeToolManifest[] => {
- const valid: LobeToolManifest[] = [];
- const dropped: Array<{ identifier?: string; reason: string }> = [];
-
- for (const m of manifests) {
- if (isValidToolManifest(m)) {
- valid.push(m);
- } else if (m) {
- dropped.push({
- identifier: (m as { identifier?: string }).identifier,
- reason: 'missing `api` field (expected array)',
- });
- }
- }
-
- if (dropped.length > 0) {
- console.warn(
- `[AgentToolsEngine] Dropped ${dropped.length} invalid manifest(s) from ${source}:`,
- dropped,
- );
- }
-
- return valid;
-};
-
/**
* Initialize ToolsEngine with server-side context
*
@@ -96,62 +56,35 @@ export const createServerToolsEngine = (
manifestContext,
} = config;
- // Get plugin manifests from installed plugins (from database)
- const pluginManifests = dropInvalidManifests(
- context.installedPlugins.map((plugin) => plugin.manifest as LobeToolManifest | undefined),
- 'installedPlugins',
+ // The pool rules (connector precedence, context-aware builtins, invalid
+ // manifest guard, exclusion from every source) are shared with the
+ // browser; the builtin list arrives pre-filtered by the device walls and
+ // `excludeIdentifiers` closes the second half of that wall for the other
+ // sources.
+ const { excludedCount, manifests } = assembleManifestPool(
+ {
+ additional: additionalManifests,
+ builtinTools: builtinToolsOverride,
+ installedPlugins: context.installedPlugins.map(
+ (plugin) => plugin.manifest as LobeToolManifest | undefined,
+ ),
+ },
+ { excludedIdentifiers: excludeIdentifiers, manifestContext },
);
- // Get builtin tool manifests from the (possibly pre-filtered) list. The
- // filter is one half of the hard wall keeping device tools out of an
- // external bot sender's manifestSchemas โ€” see `buildAllowedBuiltinTools`
- // and . The enableChecker rules below are defense-in-depth
- // because `allowExplicitActivation` lets activator-driven activation
- // bypass them.
- //
- // When a manifest context is supplied (agent runtime path), context-aware
- // tools resolve their manifest for it โ€” trimming APIs (e.g. lobe-agent hides
- // callSubAgent inside a sub-agent / group, both list AND systemRole) or opting
- // out entirely via `null`. This MUST mirror the frontend `createToolsEngine`:
- // a sub-agent run server-side that skipped this would still be handed
- // `callSubAgent`, letting the model recurse into nested sub-agents that the
- // runtime then rejects โ€” a dead loop that ends in the inactivity watchdog.
- const builtinManifests = builtinToolsOverride
- .map((tool) =>
- manifestContext && tool.resolveManifest
- ? tool.resolveManifest(manifestContext)
- : tool.manifest,
- )
- .filter((m): m is BuiltinToolManifest => !!m) as LobeToolManifest[];
-
- // Combine all manifests, then drop anything whose identifier the caller
- // has explicitly forbidden for this turn. The post-merge filter closes
- // the second half of the wall: an installed plugin or a
- // Skill/Composio manifest claiming `lobe-remote-device` would otherwise
- // slip through `buildAllowedBuiltinTools` (which only touches the
- // builtin source).
- const combinedManifests = [
- ...pluginManifests,
- ...builtinManifests,
- ...dropInvalidManifests(additionalManifests, 'additionalManifests'),
- ];
- const allManifests = excludeIdentifiers
- ? combinedManifests.filter((m) => !excludeIdentifiers.has(m.identifier))
- : combinedManifests;
-
log(
- 'Creating ToolsEngine with %d plugin manifests, %d builtin manifests, %d additional manifests, %d excluded',
- pluginManifests.length,
- builtinManifests.length,
+ 'Creating ToolsEngine with %d manifests (%d installed plugins, %d additional, %d excluded)',
+ manifests.length,
+ context.installedPlugins.length,
additionalManifests.length,
- combinedManifests.length - allManifests.length,
+ excludedCount,
);
return new ToolsEngine({
defaultToolIds,
enableChecker,
functionCallChecker: context.isModelSupportToolUse,
- manifestSchemas: allManifests,
+ manifestSchemas: manifests,
});
};
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
index 745500b056b..2906da368b6 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
@@ -1,8 +1,5 @@
-import { AuvManifest } from '@lobechat/builtin-tool-auv';
-import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { GoalIdentifier, isGoalPrompt } from '@lobechat/builtin-tool-goal';
import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';
-import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { MessageToolIdentifier } from '@lobechat/builtin-tool-message';
import type { DeviceAttachment } from '@lobechat/builtin-tool-remote-device';
import { generateSystemPrompt, RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
@@ -20,6 +17,11 @@ import type {
} from '@lobechat/context-engine';
import type { LobeChatDatabase } from '@lobechat/database';
import type { DeviceUnavailableErrorData } from '@lobechat/device-gateway-client';
+import {
+ resolveClientExecutors,
+ resolveDiscoveryPool,
+ resolveInvocationToolIds,
+} from '@lobechat/mecha';
import type { ChatTopicBotContext, RequestTrigger } from '@lobechat/types';
import {
agentShareFileAccessScope,
@@ -42,7 +44,6 @@ import type { PluginModel } from '@/database/models/plugin';
import {
type ExecutionPlan,
executionPlanToManifestExecutionEnv,
- executionTargetToRuntimeMode,
isDeviceCapablePlan,
isDeviceLockedPlan,
resolveExecutionPlan,
@@ -75,11 +76,7 @@ import {
resolveUserDisplayMap,
} from '@/server/utils/connectorAttribution';
-import {
- buildAllowedBuiltinTools,
- isDeviceToolIdentifier,
- REMOTE_DEVICE_TOOL_IDENTIFIERS,
-} from '../deviceToolRegistry';
+import { buildAllowedBuiltinTools } from '../deviceToolRegistry';
import { buildBotConversationGroupContext, buildGroupAgentContext } from '../helpers/groupContext';
import {
getMediaAvailabilityFromFileTypes,
@@ -937,20 +934,17 @@ export const discoverTools = async (
});
// 5f. Generate tools and manifest map
- const pluginIds = exclusivePluginIds
- ? agentPlugins
- : [
- ...new Set([
- ...agentPlugins,
- ...(disableLocalSystem ? [] : [LocalSystemManifest.identifier, AuvManifest.identifier]),
- RemoteDeviceManifest.identifier,
- // Include LobeHub Skills and Composio tools so they are passed to generateToolsDetailed
- ...activeLobehubSkillManifests.map((m) => m.identifier),
- ...activeComposioManifests.map((m) => m.identifier),
- // Connector manifests are also injected as additionalManifests
- ...activeConnectorManifests.map((m) => m.identifier),
- ]),
- ];
+ // Which identifiers the engine considers, what the activator may discover
+ // mid-run, and which tools dispatch to the client are shared rules in
+ // `@lobechat/mecha`; this pipeline only supplies the run's facts.
+ const pluginIds = resolveInvocationToolIds({
+ agentPlugins,
+ composioIds: activeComposioManifests.map((m) => m.identifier),
+ connectorIds: activeConnectorManifests.map((m) => m.identifier),
+ disableLocalSystem,
+ exclusivePluginIds,
+ lobehubSkillIds: activeLobehubSkillManifests.map((m) => m.identifier),
+ });
log('execAgent: agent configured plugins: %O', pluginIds);
const isManualMode = agentConfig.chatConfig?.skillActivateMode === 'manual';
@@ -966,166 +960,44 @@ export const discoverTools = async (
tools = toolsResult.tools;
log('execAgent: enabled tool ids: %O', toolsResult.enabledToolIds);
- // Single guard for every `toolManifestMap[id] = ...` ingest below.
- // Mirrors the post-merge filter in `createServerToolsEngine`: an
- // installed plugin, a LobeHub Skill, or a Composio manifest declaring
- // `identifier: 'lobe-remote-device'` would otherwise reach the
- // activator-discovery map and let an external bot sender enable it
- // (). Centralising the check at the ingest layer means
- // every future manifest source automatically inherits the wall.
- //
- // A device-LOCKED run (routed, or explicitly bound but offline) keeps
- // local-system but must not expose the remote-device picker: leaving it
- // discoverable lets the activator's explicit activation bypass the rule
- // gate and re-surface the device list mid-run โ€” inviting redundant
- // activateDevice calls or switching to a machine the user never chose.
- // Enforced here (not as a point deletion after the seed) so the later
- // Skill/Composio ingest loops cannot re-add the identifier.
- const isManifestIngestAllowed = (identifier: string): boolean => {
- if (exclusivePluginIds && !exclusivePluginIds.includes(identifier)) return false;
- if (disabledPluginIdSet.has(identifier)) return false;
- if (
- gatewayConfigured &&
- identifier === AuvManifest.identifier &&
- !supportedDeviceTools?.includes(identifier)
- )
- return false;
- if (!canUseDevice && isDeviceToolIdentifier(identifier)) return false;
- if (deviceLocked && REMOTE_DEVICE_TOOL_IDENTIFIERS.has(identifier)) return false;
- return true;
- };
-
// Start with the scoped manifest map (pluginIds + defaultToolIds)
const manifestMap = toolsEngine.getEnabledPluginManifests(pluginIds);
- manifestMap.forEach((manifest, id) => {
- if (!isManifestIngestAllowed(id)) return;
- toolManifestMap[id] = manifest;
- });
-
- // Also include discoverable builtin tools that are not yet in the map,
- // so the activator can find their manifests when dynamically enabling them
- // (e.g., lobe-creds, lobe-task). Exclude discoverable:false tools to prevent
- // internal infrastructure tools from being surfaced to the activator.
- const allowedBuiltinTools = buildAllowedBuiltinTools({
- canUseDevice,
- deviceLocked,
+ const discovery = resolveDiscoveryPool({
+ builtinTools: buildAllowedBuiltinTools({
+ canUseDevice,
+ deviceLocked,
+ disableLocalSystem,
+ supportedDeviceTools: gatewayConfigured ? (supportedDeviceTools ?? []) : undefined,
+ }),
+ composio: activeComposioManifests,
+ device: gatewayConfigured ? { supportedTools: supportedDeviceTools } : undefined,
+ deviceAccess: { canUseDevice, deviceLocked },
+ deviceCapable,
disableLocalSystem,
- supportedDeviceTools: gatewayConfigured ? (supportedDeviceTools ?? []) : undefined,
+ disabledPluginIds,
+ enabledManifests: manifestMap,
+ exclusivePluginIds,
+ executionTarget: executionPlan.target,
+ lobehubSkills: activeLobehubSkillManifests,
});
- // Effective runtimeMode from the plan's resolved target โ€” same value the
- // engine derives, single derivation point.
- const agentRuntimeMode = executionTargetToRuntimeMode(executionPlan.target);
- // Mirrors AgentToolsEngine's agentModeRules gate: auto mode lets the model
- // choose per call whether to run in the cloud sandbox or on the
- // auto-routed device, so Cloud Sandbox stays allowed there too.
- const cloudSandboxAllowed = agentRuntimeMode === 'cloud' || executionPlan.target === 'auto';
- // When sandbox isn't reachable, remove lobe-cloud-sandbox from the
- // manifest map. The initial seed via getEnabledPluginManifests (which includes
- // defaultToolIds) may have already placed it there, and the allowedBuiltinTools
- // loop below only guards the discoverable-builtin append path. Deleting here
- // covers both sources in a single point.
- if (!cloudSandboxAllowed) {
- delete toolManifestMap[CloudSandboxManifest.identifier];
- }
- // Same single-point deletion for the device tools: a `none` / `sandbox`
- // session must not expose the remote-device proxy either โ€” leaving it
- // discoverable would let the model activate a device mid-run and bypass
- // the execution plan ("ๆ— ่ฎพๅค‡" means NO device, not "no device yet").
- // Scoped to gateway deployments: in the standalone Electron deployment
- // (no DEVICE_GATEWAY) local-system routes in-process via the 'client'
- // executor marking below, and the desktop client owns the tool gate.
- const stripDeviceTools = gatewayConfigured && !deviceCapable;
- if (stripDeviceTools) {
- delete toolManifestMap[AuvManifest.identifier];
- delete toolManifestMap[RemoteDeviceManifest.identifier];
- delete toolManifestMap[LocalSystemManifest.identifier];
- }
- for (const tool of allowedBuiltinTools) {
- if (!isManifestIngestAllowed(tool.identifier)) continue;
- // lobe-cloud-sandbox is only activator-discoverable when the sandbox is
- // reachable (executionTarget='sandbox', or 'auto' โ€” see cloudSandboxAllowed above).
- if (tool.identifier === CloudSandboxManifest.identifier && !cloudSandboxAllowed) continue;
- // device tools are only activator-discoverable in device-capable sessions
- if (stripDeviceTools && isDeviceToolIdentifier(tool.identifier)) continue;
- if (tool.discoverable !== false && !toolManifestMap[tool.identifier]) {
- toolManifestMap[tool.identifier] = tool.manifest as LobeToolManifest;
- }
- }
-
- // Local System and AUV have `discoverable: isDesktop` in builtinTools,
- // which evaluates to false on the Node.js server side, so they never enter
- // the loop above. Explicitly inject them only when the device gateway is
- // configured AND the plan's target is 'local' โ€” skip for sandbox/none
- // targets to avoid leaking local-system into non-local sessions. (The
- // plan already degrades to `none` when device access is denied, so no
- // separate `canUseDevice` check is needed here.)
- for (const manifest of [LocalSystemManifest, AuvManifest]) {
- if (
- !disableLocalSystem &&
- isManifestIngestAllowed(manifest.identifier) &&
- gatewayConfigured &&
- agentRuntimeMode === 'local' &&
- !toolManifestMap[manifest.identifier]
- ) {
- toolManifestMap[manifest.identifier] = manifest as LobeToolManifest;
- }
- }
-
- // Include lobehub skill and composio manifests for activator discovery.
- // Uses the disabled-filtered `active*Manifests` (not the raw
- // lobehubSkillManifests/composioManifests) โ€” otherwise a disabled
- // skill/composio integration would be re-ingested here and shown to
- // the model as discoverable in <available_tools>, even though it was
- // correctly excluded from the actual invocation pool above.
- for (const manifest of activeLobehubSkillManifests) {
- if (!isManifestIngestAllowed(manifest.identifier)) continue;
- if (!toolManifestMap[manifest.identifier]) {
- toolManifestMap[manifest.identifier] = manifest;
- }
- }
- for (const manifest of activeComposioManifests) {
- if (!isManifestIngestAllowed(manifest.identifier)) continue;
- if (!toolManifestMap[manifest.identifier]) {
- toolManifestMap[manifest.identifier] = manifest;
- }
- }
-
- for (const manifest of activeLobehubSkillManifests) {
- if (!isManifestIngestAllowed(manifest.identifier)) continue;
- toolSourceMap[manifest.identifier] = 'lobehubSkill';
- }
- for (const manifest of activeComposioManifests) {
- if (!isManifestIngestAllowed(manifest.identifier)) continue;
- toolSourceMap[manifest.identifier] = 'composio';
- }
-
- // Mark tools that must run on the user's machine (local-system, stdio
- // MCP) for direct client dispatch only in the standalone deployment
- // where no DEVICE_GATEWAY is configured. In that mode the legacy
- // Remote Device proxy isn't available and the embedded Electron runs
- // both the server and the executor, so tools route in-process.
- //
- // With a device-gateway configured, every caller (desktop UI, web,
- // IM/bot) converges on the device-gateway path: tool calls tunnel to
- // a registered device's WS connection. `executor` stays unset so the
- // RemoteDevice proxy resolves the route.
- if (!gatewayConfigured) {
- for (const id of Object.keys(toolManifestMap)) {
- if (toolManifestMap[id]?.executors?.includes('client')) {
- toolExecutorMap[id] = 'client';
- }
- }
- for (const plugin of installedPlugins) {
- if (plugin.customParams?.mcp?.type === 'stdio' && manifestMap.has(plugin.identifier)) {
- toolExecutorMap[plugin.identifier] = 'client';
- }
- }
- for (const connector of connectorsMcp) {
- if (connector.mcpConnectionType === 'stdio' && manifestMap.has(connector.identifier)) {
- toolExecutorMap[connector.identifier] = 'client';
- }
- }
- }
+ Object.assign(toolManifestMap, discovery.manifestMap);
+ Object.assign(toolSourceMap, discovery.sourceMap);
+ Object.assign(
+ toolExecutorMap,
+ resolveClientExecutors({
+ enabledIds: new Set(manifestMap.keys()),
+ hasDeviceProxy: gatewayConfigured,
+ manifestMap: toolManifestMap,
+ stdioIdentifiers: [
+ ...installedPlugins
+ .filter((plugin) => plugin.customParams?.mcp?.type === 'stdio')
+ .map((plugin) => plugin.identifier),
+ ...connectorsMcp
+ .filter((connector) => connector.mcpConnectionType === 'stdio')
+ .map((connector) => connector.identifier),
+ ],
+ }),
+ );
log(
'execAgent: generated %d tools, %d lobehub skills, %d composio tools',
diff --git a/packages/mecha/src/toolSet/discoveryPool.test.ts b/packages/mecha/src/toolSet/discoveryPool.test.ts
new file mode 100644
index 00000000000..7c82ca59500
--- /dev/null
+++ b/packages/mecha/src/toolSet/discoveryPool.test.ts
@@ -0,0 +1,195 @@
+import { AuvManifest } from '@lobechat/builtin-tool-auv';
+import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
+import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
+import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
+import type { LobeToolManifest } from '@lobechat/context-engine';
+import { describe, expect, it } from 'vitest';
+
+import {
+ type DiscoveryPoolRequest,
+ resolveClientExecutors,
+ resolveDiscoveryPool,
+ resolveInvocationToolIds,
+} from './discoveryPool';
+
+const manifest = (identifier: string, extra: Record<string, unknown> = {}): LobeToolManifest =>
+ ({ api: [], identifier, meta: {}, ...extra }) as LobeToolManifest;
+
+const builtin = (identifier: string, discoverable?: boolean) => ({
+ discoverable,
+ identifier,
+ manifest: manifest(identifier) as never,
+});
+
+const request = (overrides: Partial<DiscoveryPoolRequest> = {}): DiscoveryPoolRequest => ({
+ builtinTools: [
+ builtin('lobe-creds'),
+ builtin('lobe-infra', false),
+ builtin(CloudSandboxManifest.identifier),
+ builtin(RemoteDeviceManifest.identifier),
+ ],
+ enabledManifests: new Map([['my-plugin', manifest('my-plugin')]]),
+ executionTarget: 'sandbox',
+ ...overrides,
+});
+
+describe('resolveInvocationToolIds', () => {
+ it('adds the device tools and every connector family to the agent candidates', () => {
+ const ids = resolveInvocationToolIds({
+ agentPlugins: ['a'],
+ composioIds: ['gmail'],
+ connectorIds: ['notion'],
+ lobehubSkillIds: ['linear'],
+ });
+ expect(ids).toEqual([
+ 'a',
+ LocalSystemManifest.identifier,
+ AuvManifest.identifier,
+ RemoteDeviceManifest.identifier,
+ 'linear',
+ 'gmail',
+ 'notion',
+ ]);
+ });
+
+ it('adds nothing to an exclusive set and skips local tools when disabled', () => {
+ expect(
+ resolveInvocationToolIds({ agentPlugins: ['only'], exclusivePluginIds: ['only'] }),
+ ).toEqual(['only']);
+ expect(resolveInvocationToolIds({ agentPlugins: [], disableLocalSystem: true })).toEqual([
+ RemoteDeviceManifest.identifier,
+ ]);
+ });
+});
+
+describe('resolveDiscoveryPool', () => {
+ it('seeds with the enabled manifests and appends discoverable builtins only', () => {
+ const pool = resolveDiscoveryPool(request());
+ expect(Object.keys(pool.manifestMap)).toEqual([
+ 'my-plugin',
+ 'lobe-creds',
+ CloudSandboxManifest.identifier,
+ RemoteDeviceManifest.identifier,
+ ]);
+ });
+
+ it('keeps the sandbox only when reachable and drops device tools for a non-device gateway run', () => {
+ const none = resolveDiscoveryPool(
+ request({
+ device: {},
+ enabledManifests: new Map([
+ [CloudSandboxManifest.identifier, manifest(CloudSandboxManifest.identifier)],
+ [LocalSystemManifest.identifier, manifest(LocalSystemManifest.identifier)],
+ ]),
+ executionTarget: 'none',
+ }),
+ );
+ expect(none.manifestMap[CloudSandboxManifest.identifier]).toBeUndefined();
+ expect(none.manifestMap[LocalSystemManifest.identifier]).toBeUndefined();
+ expect(none.manifestMap[RemoteDeviceManifest.identifier]).toBeUndefined();
+
+ const auto = resolveDiscoveryPool(request({ device: {}, executionTarget: 'auto' }));
+ expect(auto.manifestMap[CloudSandboxManifest.identifier]).toBeDefined();
+ });
+
+ it('keeps the picker discoverable for a device-capable run that is not routed yet', () => {
+ // `auto` with several machines online: unrouted, and the picker is
+ // exactly what resolves it.
+ const unrouted = resolveDiscoveryPool(
+ request({
+ device: {},
+ deviceAccess: { canUseDevice: true, deviceLocked: false },
+ deviceCapable: true,
+ enabledManifests: new Map([
+ [RemoteDeviceManifest.identifier, manifest(RemoteDeviceManifest.identifier)],
+ ]),
+ executionTarget: 'auto',
+ }),
+ );
+ expect(unrouted.manifestMap[RemoteDeviceManifest.identifier]).toBeDefined();
+ });
+
+ it('injects local-system and Computer Use for a local target behind a gateway', () => {
+ const local = resolveDiscoveryPool(
+ request({
+ device: { supportedTools: [AuvManifest.identifier] },
+ deviceAccess: { canUseDevice: true, deviceLocked: false },
+ deviceCapable: true,
+ executionTarget: 'local',
+ }),
+ );
+ expect(local.manifestMap[LocalSystemManifest.identifier]).toBeDefined();
+ expect(local.manifestMap[AuvManifest.identifier]).toBeDefined();
+
+ // An older device that does not report Computer Use never sees it.
+ const older = resolveDiscoveryPool(
+ request({
+ device: { supportedTools: [] },
+ deviceAccess: { canUseDevice: true, deviceLocked: false },
+ deviceCapable: true,
+ executionTarget: 'local',
+ }),
+ );
+ expect(older.manifestMap[AuvManifest.identifier]).toBeUndefined();
+ expect(older.manifestMap[LocalSystemManifest.identifier]).toBeDefined();
+ });
+
+ it('walls every ingest source: exclusive set, disabled ids, denied devices, locked picker', () => {
+ const exclusive = resolveDiscoveryPool(
+ request({ exclusivePluginIds: ['my-plugin'], lobehubSkills: [manifest('linear')] }),
+ );
+ expect(Object.keys(exclusive.manifestMap)).toEqual(['my-plugin']);
+
+ const denied = resolveDiscoveryPool(
+ request({
+ deviceAccess: { canUseDevice: false, deviceLocked: false },
+ deviceCapable: true,
+ disabledPluginIds: ['my-plugin'],
+ executionTarget: 'local',
+ lobehubSkills: [manifest(RemoteDeviceManifest.identifier)],
+ }),
+ );
+ expect(denied.manifestMap['my-plugin']).toBeUndefined();
+ expect(denied.manifestMap[RemoteDeviceManifest.identifier]).toBeUndefined();
+ expect(denied.sourceMap[RemoteDeviceManifest.identifier]).toBeUndefined();
+
+ const locked = resolveDiscoveryPool(
+ request({
+ device: {},
+ deviceAccess: { canUseDevice: true, deviceLocked: true },
+ deviceCapable: true,
+ executionTarget: 'device',
+ }),
+ );
+ expect(locked.manifestMap[RemoteDeviceManifest.identifier]).toBeUndefined();
+ });
+
+ it('records the family a connector tool executes through', () => {
+ const pool = resolveDiscoveryPool(
+ request({ composio: [manifest('gmail')], lobehubSkills: [manifest('linear')] }),
+ );
+ expect(pool.sourceMap).toEqual({ gmail: 'composio', linear: 'lobehubSkill' });
+ expect(pool.manifestMap.gmail).toBeDefined();
+ });
+});
+
+describe('resolveClientExecutors', () => {
+ 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'],
+ }),
+ ).toEqual({ 'local': 'client', 'stdio-mcp': 'client' });
+ expect(
+ resolveClientExecutors({ enabledIds: new Set(), hasDeviceProxy: true, manifestMap }),
+ ).toEqual({});
+ });
+});
diff --git a/packages/mecha/src/toolSet/discoveryPool.ts b/packages/mecha/src/toolSet/discoveryPool.ts
new file mode 100644
index 00000000000..140c592392d
--- /dev/null
+++ b/packages/mecha/src/toolSet/discoveryPool.ts
@@ -0,0 +1,209 @@
+import { AuvManifest } from '@lobechat/builtin-tool-auv';
+import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
+import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
+import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
+import type { LobeToolManifest } from '@lobechat/context-engine';
+import {
+ type DeviceExecutionTarget,
+ executionTargetToRuntimeMode,
+ type LobeBuiltinTool,
+ type ToolExecutor,
+ type ToolSource,
+} from '@lobechat/types';
+
+import { isDeviceToolIdentifier, REMOTE_DEVICE_TOOL_IDENTIFIERS } from './deviceTools';
+import type { ToolRuleDeviceAccess, ToolRuleDeviceFacts } from './types';
+
+export interface InvocationToolIdsRequest {
+ /** The run's candidate plugin identifiers (pinned, additional, selected, mention-driven). */
+ agentPlugins: readonly string[];
+ composioIds?: readonly string[];
+ connectorIds?: readonly string[];
+ disableLocalSystem?: boolean;
+ /** An exact toolset (verify agent, goal supervisor): nothing is added. */
+ exclusivePluginIds?: readonly string[];
+ lobehubSkillIds?: readonly string[];
+}
+
+/**
+ * The identifiers handed to the tools engine for this run. Beyond the
+ * agent's own candidates, every device tool and every connector-family
+ * manifest is a candidate โ€” the enable rules decide, and a tool that is not
+ * a candidate can never be enabled.
+ */
+export const resolveInvocationToolIds = (request: InvocationToolIdsRequest): string[] => {
+ if (request.exclusivePluginIds) return [...request.agentPlugins];
+ return [
+ ...new Set([
+ ...request.agentPlugins,
+ ...(request.disableLocalSystem
+ ? []
+ : [LocalSystemManifest.identifier, AuvManifest.identifier]),
+ RemoteDeviceManifest.identifier,
+ ...(request.lobehubSkillIds ?? []),
+ ...(request.composioIds ?? []),
+ ...(request.connectorIds ?? []),
+ ]),
+ ];
+};
+
+export interface DiscoveryPoolRequest {
+ /** Builtin tools after the device walls, with their `discoverable` flag. */
+ builtinTools: readonly Pick<LobeBuiltinTool, 'discoverable' | 'identifier' | 'manifest'>[];
+ /** Disabled-filtered Composio manifests. */
+ composio?: readonly LobeToolManifest[];
+ /** Gateway device facts; absent without a gateway. */
+ device?: Pick<ToolRuleDeviceFacts, 'supportedTools'>;
+ deviceAccess?: ToolRuleDeviceAccess;
+ /**
+ * The run may still reach a device: routed, or device-targeted but not
+ * routed yet (the picker is exactly what resolves that). Taken from the
+ * execution plan's kind, not from the target โ€” an `auto` run with several
+ * online machines is unrouted and still needs the picker.
+ */
+ deviceCapable?: boolean;
+ disabledPluginIds?: readonly string[];
+ disableLocalSystem?: boolean;
+ /** The manifests the engine enabled for the invocation set. */
+ enabledManifests: ReadonlyMap<string, LobeToolManifest>;
+ exclusivePluginIds?: readonly string[];
+ executionTarget: DeviceExecutionTarget;
+ /** Disabled-filtered LobeHub skill manifests. */
+ lobehubSkills?: readonly LobeToolManifest[];
+}
+
+export interface DiscoveryPool {
+ /** The single guard every ingest into the pool goes through. */
+ isManifestIngestAllowed: (identifier: string) => boolean;
+ /** What the activator may discover and enable mid-run. */
+ manifestMap: Record<string, LobeToolManifest>;
+ /** Which family a discovered tool executes through. */
+ sourceMap: Record<string, ToolSource>;
+}
+
+/**
+ * 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
+ * them โ€” explicit activation bypasses the enable rules, so what is not
+ * reachable must not be discoverable at all.
+ */
+export const resolveDiscoveryPool = (request: DiscoveryPoolRequest): DiscoveryPool => {
+ const { device, deviceAccess, executionTarget } = request;
+ const hasDeviceProxy = !!device;
+ const disabled = new Set(request.disabledPluginIds ?? []);
+ const exclusive = request.exclusivePluginIds ? new Set(request.exclusivePluginIds) : undefined;
+ const canUseDevice = deviceAccess?.canUseDevice ?? true;
+ const deviceLocked = deviceAccess?.deviceLocked ?? false;
+
+ // A device-LOCKED run keeps local-system but must not expose the picker:
+ // leaving it discoverable would let explicit activation re-surface the
+ // device list mid-run. Enforced at the ingest layer so no later source
+ // can re-add an identifier the walls removed.
+ const isManifestIngestAllowed = (identifier: string): boolean => {
+ if (exclusive && !exclusive.has(identifier)) return false;
+ if (disabled.has(identifier)) return false;
+ if (
+ hasDeviceProxy &&
+ identifier === AuvManifest.identifier &&
+ !device.supportedTools?.includes(identifier)
+ )
+ return false;
+ if (!canUseDevice && isDeviceToolIdentifier(identifier)) return false;
+ if (deviceLocked && REMOTE_DEVICE_TOOL_IDENTIFIERS.has(identifier)) return false;
+ return true;
+ };
+
+ const manifestMap: Record<string, LobeToolManifest> = {};
+ const sourceMap: Record<string, ToolSource> = {};
+
+ // Seed with the invocation set (candidates โˆช defaults the engine enabled).
+ request.enabledManifests.forEach((manifest, id) => {
+ if (isManifestIngestAllowed(id)) manifestMap[id] = manifest;
+ });
+
+ const runtimeMode = executionTargetToRuntimeMode(executionTarget);
+ const deviceCapable = request.deviceCapable ?? false;
+ // Auto mode lets the model choose the sandbox or the routed device per
+ // call, so the sandbox stays discoverable there too.
+ const cloudSandboxAllowed = runtimeMode === 'cloud' || executionTarget === 'auto';
+ if (!cloudSandboxAllowed) delete manifestMap[CloudSandboxManifest.identifier];
+ // A `none` / `sandbox` run behind a gateway must not expose device tools:
+ // "no device" means NO device, not "no device yet". Without a gateway the
+ // desktop client owns the tool gate and routes in-process.
+ const stripDeviceTools = hasDeviceProxy && !deviceCapable;
+ if (stripDeviceTools) {
+ delete manifestMap[AuvManifest.identifier];
+ delete manifestMap[RemoteDeviceManifest.identifier];
+ delete manifestMap[LocalSystemManifest.identifier];
+ }
+
+ // Discoverable builtins the activator may enable later (e.g. creds, task);
+ // `discoverable: false` keeps infrastructure tools out of the listing.
+ for (const tool of request.builtinTools) {
+ if (!isManifestIngestAllowed(tool.identifier)) continue;
+ if (tool.identifier === CloudSandboxManifest.identifier && !cloudSandboxAllowed) continue;
+ if (stripDeviceTools && isDeviceToolIdentifier(tool.identifier)) continue;
+ if (tool.discoverable !== false && !manifestMap[tool.identifier]) {
+ manifestMap[tool.identifier] = tool.manifest as LobeToolManifest;
+ }
+ }
+
+ // Local-system and Computer Use are only `discoverable` on the desktop, so
+ // a gateway server injects them explicitly for a `local` target.
+ for (const manifest of [LocalSystemManifest, AuvManifest]) {
+ if (
+ !request.disableLocalSystem &&
+ isManifestIngestAllowed(manifest.identifier) &&
+ hasDeviceProxy &&
+ runtimeMode === 'local' &&
+ !manifestMap[manifest.identifier]
+ ) {
+ manifestMap[manifest.identifier] = manifest as LobeToolManifest;
+ }
+ }
+
+ // Connector families, with the source the runtime executes them through.
+ const ingestFamily = (manifests: readonly LobeToolManifest[], source: ToolSource) => {
+ for (const manifest of manifests) {
+ if (!isManifestIngestAllowed(manifest.identifier)) continue;
+ if (!manifestMap[manifest.identifier]) manifestMap[manifest.identifier] = manifest;
+ sourceMap[manifest.identifier] = source;
+ }
+ };
+ ingestFamily(request.lobehubSkills ?? [], 'lobehubSkill');
+ ingestFamily(request.composio ?? [], 'composio');
+
+ 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>>;
+ /** Connectors and installed plugins that run over stdio (a local process). */
+ stdioIdentifiers?: readonly string[];
+}
+
+/**
+ * Tools that must run on the user's machine (local-system, stdio MCP) are
+ * 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.
+ */
+export const resolveClientExecutors = (
+ request: ClientExecutorsRequest,
+): Record<string, ToolExecutor> => {
+ const executorMap: Record<string, ToolExecutor> = {};
+ if (request.hasDeviceProxy) return executorMap;
+ for (const [id, manifest] of Object.entries(request.manifestMap)) {
+ if ((manifest as { executors?: string[] })?.executors?.includes('client'))
+ executorMap[id] = 'client';
+ }
+ for (const id of request.stdioIdentifiers ?? []) {
+ if (request.enabledIds.has(id)) executorMap[id] = 'client';
+ }
+ return executorMap;
+};
diff --git a/packages/mecha/src/toolSet/index.ts b/packages/mecha/src/toolSet/index.ts
index ec35113017f..46111958180 100644
--- a/packages/mecha/src/toolSet/index.ts
+++ b/packages/mecha/src/toolSet/index.ts
@@ -1,3 +1,5 @@
export * from './deviceTools';
+export * from './discoveryPool';
+export * from './manifestPool';
export { deviceToolWallParams, resolveToolRules } from './resolveToolRules';
export type * from './types';
diff --git a/packages/mecha/src/toolSet/manifestPool.test.ts b/packages/mecha/src/toolSet/manifestPool.test.ts
new file mode 100644
index 00000000000..483b2558b0e
--- /dev/null
+++ b/packages/mecha/src/toolSet/manifestPool.test.ts
@@ -0,0 +1,164 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ assembleManifestPool,
+ buildConnectorManifest,
+ patchManifestWithPermissions,
+} from './manifestPool';
+
+const manifest = (identifier: string, extra: Record<string, unknown> = {}) => ({
+ api: [{ description: 'do it', name: 'run', parameters: {} }],
+ identifier,
+ meta: { title: identifier },
+ ...extra,
+});
+
+describe('buildConnectorManifest', () => {
+ it('lists every synced tool with its permission mapped, and nothing for a disabled or empty connector', () => {
+ const built = buildConnectorManifest({
+ identifier: 'notion',
+ isEnabled: true,
+ name: 'Notion',
+ tools: [
+ { description: 'search', permission: 'auto', toolName: 'search' },
+ { permission: 'needs_approval', toolName: 'write' },
+ { permission: 'disabled', toolName: 'delete' },
+ ],
+ })!;
+
+ expect(built.identifier).toBe('notion');
+ expect(built.type).toBe('mcp');
+ expect(built.meta.description).toBe('Notion connector with 3 tools');
+ expect(built.api.map((a) => [a.name, a.humanIntervention])).toEqual([
+ ['search', undefined],
+ ['write', 'required'],
+ ['delete', 'required'],
+ ]);
+ expect(built.api[2].description).toContain('[TOOL DISABLED]');
+ expect(built.api[1].parameters).toEqual({ properties: {}, type: 'object' });
+
+ expect(
+ buildConnectorManifest({ identifier: 'x', isEnabled: false, name: 'x', tools: [] }),
+ ).toBeUndefined();
+ expect(
+ buildConnectorManifest({ identifier: 'x', isEnabled: true, name: 'x', tools: [] }),
+ ).toBeUndefined();
+ });
+});
+
+describe('patchManifestWithPermissions', () => {
+ it('surfaces needs_approval and disabled on the matching api entries only', () => {
+ const patched = patchManifestWithPermissions(
+ {
+ api: [
+ { name: 'a', parameters: {} },
+ { name: 'b', parameters: {} },
+ { name: 'c', parameters: {} },
+ ] as { description?: string; humanIntervention?: string; name: string; parameters: {} }[],
+ },
+ new Map([
+ ['a', 'needs_approval'],
+ ['b', 'disabled'],
+ ]),
+ );
+ expect(patched.api[0]).toMatchObject({ humanIntervention: 'required' });
+ expect(patched.api[1].description).toContain('[TOOL DISABLED]');
+ expect(patched.api[2]).toEqual({ name: 'c', parameters: {} });
+ });
+});
+
+describe('assembleManifestPool', () => {
+ it('lets a connector manifest replace the same-named plugin and orders the sources', () => {
+ const pool = assembleManifestPool({
+ additional: [manifest('extra')],
+ builtinTools: [{ identifier: 'lobe-x', manifest: manifest('lobe-x') as never }],
+ composio: [manifest('gmail')],
+ connectors: [manifest('notion', { type: 'mcp' })],
+ installedPlugins: [manifest('notion'), manifest('plain-plugin')],
+ lobehubSkills: [manifest('linear')],
+ });
+
+ expect(pool.connectorIdentifiers).toEqual(new Set(['notion']));
+ expect(pool.manifests.map((m) => m.identifier)).toEqual([
+ 'plain-plugin',
+ 'lobe-x',
+ 'gmail',
+ 'linear',
+ 'notion',
+ 'extra',
+ ]);
+ expect(pool.manifests.find((m) => m.identifier === 'notion')?.type).toBe('mcp');
+ });
+
+ it('patches permissions onto manifests executed outside the connector path', () => {
+ const pool = assembleManifestPool(
+ {
+ composio: [manifest('gmail')],
+ installedPlugins: [manifest('community-mcp')],
+ lobehubSkills: [manifest('linear')],
+ },
+ {
+ connectorPermissions: new Map([
+ ['community-mcp', new Map([['run', 'disabled']])],
+ ['gmail', new Map([['run', 'needs_approval']])],
+ ['linear', new Map()],
+ ]),
+ },
+ );
+ const byId = Object.fromEntries(pool.manifests.map((m) => [m.identifier, m]));
+ expect(byId['community-mcp'].api[0].description).toContain('[TOOL DISABLED]');
+ expect(byId['gmail'].api[0].humanIntervention).toBe('required');
+ expect(byId['linear'].api[0].humanIntervention).toBeUndefined();
+ });
+
+ it('resolves context-aware builtins for the run and drops the ones that opt out', () => {
+ const resolveManifest = vi.fn((ctx: { isSubAgent?: boolean }) =>
+ ctx.isSubAgent
+ ? null
+ : manifest('lobe-agent', { api: [{ name: 'trimmed', parameters: {} }] }),
+ );
+ const builtinTools = [
+ { identifier: 'lobe-agent', manifest: manifest('lobe-agent') as never, resolveManifest },
+ ] as never;
+
+ const contextFree = assembleManifestPool({ builtinTools });
+ expect(contextFree.manifests[0].api[0].name).toBe('run');
+ expect(resolveManifest).not.toHaveBeenCalled();
+
+ const main = assembleManifestPool({ builtinTools }, { manifestContext: {} as never });
+ expect(main.manifests[0].api[0].name).toBe('trimmed');
+
+ const sub = assembleManifestPool(
+ { builtinTools },
+ { manifestContext: { isSubAgent: true } as never },
+ );
+ expect(sub.manifests).toEqual([]);
+ });
+
+ it('drops manifests without an api array and every excluded identifier from any source', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const pool = assembleManifestPool(
+ {
+ additional: [manifest('lobe-remote-device')],
+ composio: [{ identifier: 'broken', meta: {} } as never],
+ installedPlugins: [manifest('gone'), manifest('kept'), undefined],
+ },
+ { excludedIdentifiers: ['gone', 'lobe-remote-device'] },
+ );
+ expect(pool.manifests.map((m) => m.identifier)).toEqual(['kept']);
+ // Counts what the exclusion actually removed: both `gone` and the
+ // device identifier were contributed by a source. An excluded id that
+ // no source contributed must not inflate this.
+ expect(pool.excludedCount).toBe(2);
+ expect(
+ assembleManifestPool(
+ { installedPlugins: [manifest('kept')] },
+ { excludedIdentifiers: ['never-here'] },
+ ).excludedCount,
+ ).toBe(0);
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('composio'), [
+ { identifier: 'broken', reason: 'missing `api` field (expected array)' },
+ ]);
+ warn.mockRestore();
+ });
+});
diff --git a/packages/mecha/src/toolSet/manifestPool.ts b/packages/mecha/src/toolSet/manifestPool.ts
new file mode 100644
index 00000000000..1351f58c76d
--- /dev/null
+++ b/packages/mecha/src/toolSet/manifestPool.ts
@@ -0,0 +1,237 @@
+import type { LobeToolManifest } from '@lobechat/context-engine';
+import type { BuiltinToolResolveContext, LobeBuiltinTool } from '@lobechat/types';
+import debug from 'debug';
+
+const log = debug('mecha:manifestPool');
+
+/** A connector tool's permission as the connectors settings store it. */
+export type ConnectorToolPermissionValue = 'auto' | 'disabled' | 'needs_approval';
+
+/** Per-tool permissions of one connector, keyed by tool name. */
+export type ConnectorToolPermissions = Map<string, ConnectorToolPermissionValue | string>;
+
+export interface ConnectorToolFacts {
+ description?: string | null;
+ inputSchema?: unknown;
+ permission?: ConnectorToolPermissionValue | string | null;
+ toolName: string;
+}
+
+export interface ConnectorFacts {
+ identifier: string;
+ isEnabled?: boolean | null;
+ name: string;
+ tools: ConnectorToolFacts[];
+}
+
+/**
+ * What the model reads for a tool the user switched off: it stays listed so
+ * the model can explain why it will not act, and the execution path blocks
+ * it regardless.
+ */
+export const disabledToolDescription = (toolName: string): string =>
+ `[TOOL DISABLED] The user has disabled this tool and it cannot be executed. ` +
+ `Do NOT call this tool. If the user asks to perform this action, inform them ` +
+ `that they have manually disabled "${toolName}" and can re-enable it in Settings > Connectors.`;
+
+/**
+ * Patch a manifest's `api[]` with connector tool permissions:
+ * `needs_approval` โ†’ `humanIntervention: 'required'`; `disabled` โ†’ the
+ * blocking description plus `humanIntervention: 'required'`. The disabled
+ * hard-block is enforced separately at execution time; this surfaces the
+ * permission to the model and the approval prompt.
+ */
+export function patchManifestWithPermissions<M extends { api: readonly { name: string }[] }>(
+ manifest: M,
+ toolPermissions: ConnectorToolPermissions,
+): M {
+ const patchedApi = manifest.api.map((api) => {
+ const permission = toolPermissions.get(api.name);
+ if (permission === 'disabled') {
+ return {
+ ...api,
+ description: disabledToolDescription(api.name),
+ humanIntervention: 'required' as const,
+ };
+ }
+ if (permission === 'needs_approval') {
+ return { ...api, humanIntervention: 'required' as const };
+ }
+ return api;
+ });
+ return { ...manifest, api: patchedApi as M['api'] };
+}
+
+/**
+ * A connector's tools as one MCP manifest: every synced tool is listed
+ * (disabled ones with the blocking description), permissions become
+ * `humanIntervention`. Returns nothing for a disabled connector or one with no
+ * synced tools โ€” such a connector must not replace a same-named plugin while
+ * contributing nothing to call.
+ */
+export const buildConnectorManifest = (connector: ConnectorFacts): LobeToolManifest | undefined => {
+ if (!connector.isEnabled) return undefined;
+ if (connector.tools.length === 0) return undefined;
+
+ const api = connector.tools.map((tool) => {
+ const parameters = (tool.inputSchema ?? { properties: {}, type: 'object' }) as Record<
+ string,
+ unknown
+ >;
+ if (tool.permission === 'disabled') {
+ return {
+ description: disabledToolDescription(tool.toolName),
+ humanIntervention: 'required' as const,
+ name: tool.toolName,
+ parameters,
+ };
+ }
+ return {
+ description: tool.description ?? '',
+ humanIntervention: tool.permission === 'needs_approval' ? ('required' as const) : undefined,
+ name: tool.toolName,
+ parameters,
+ };
+ });
+
+ return {
+ api,
+ identifier: connector.identifier,
+ meta: {
+ avatar: 'MCP_AVATAR',
+ description: `${connector.name} connector with ${api.length} tools`,
+ title: connector.name,
+ },
+ type: 'mcp',
+ };
+};
+
+/**
+ * A manifest is usable by the tools engine only if it has an `api` array;
+ * anything else would crash the whole tools build. Sources that populate
+ * manifests (installed plugins, Composio, LobeHub skills, MCP) have no shared
+ * schema validation, so guard at the merge point.
+ */
+const isValidToolManifest = (m: unknown): m is LobeToolManifest =>
+ !!m && typeof m === 'object' && Array.isArray((m as { api?: unknown }).api);
+
+export const dropInvalidManifests = (
+ manifests: readonly (LobeToolManifest | undefined | null)[],
+ source: string,
+): LobeToolManifest[] => {
+ const valid: LobeToolManifest[] = [];
+ const dropped: { identifier?: string; reason: string }[] = [];
+ for (const m of manifests) {
+ if (isValidToolManifest(m)) valid.push(m);
+ else if (m)
+ dropped.push({
+ identifier: (m as { identifier?: string }).identifier,
+ reason: 'missing `api` field (expected array)',
+ });
+ }
+ if (dropped.length > 0) {
+ log('Dropped %d invalid manifest(s) from %s: %O', dropped.length, source, dropped);
+ console.warn(
+ `[manifestPool] Dropped ${dropped.length} invalid manifest(s) from ${source}:`,
+ dropped,
+ );
+ }
+ return valid;
+};
+
+export interface ManifestPoolSources {
+ /** Anything the host adds beyond the standard sources. */
+ additional?: readonly (LobeToolManifest | undefined)[];
+ /** Builtin tools; context-aware ones resolve their manifest for `manifestContext`. */
+ builtinTools?: readonly Pick<LobeBuiltinTool, 'identifier' | 'manifest' | 'resolveManifest'>[];
+ composio?: readonly (LobeToolManifest | undefined)[];
+ /** Real MCP connectors (with an endpoint) that produced a manifest. */
+ connectors?: readonly (LobeToolManifest | undefined)[];
+ /** The user's installed plugins, before connector precedence. */
+ installedPlugins?: readonly (LobeToolManifest | undefined)[];
+ lobehubSkills?: readonly (LobeToolManifest | undefined)[];
+}
+
+export interface AssembleManifestPoolOptions {
+ /**
+ * Connector tool permissions keyed by connector identifier, for tools the
+ * connector system manages but that execute through another path (LobeHub
+ * skills, Composio, community-MCP plugins). Connectors that produced their
+ * own manifest already carry them.
+ */
+ connectorPermissions?: ReadonlyMap<string, ConnectorToolPermissions>;
+ /** Identifiers that must not exist in the pool, from any source. */
+ excludedIdentifiers?: Iterable<string>;
+ /**
+ * Runtime context for context-aware builtin manifests: each builtin with a
+ * `resolveManifest` produces its manifest for this context (trimming APIs
+ * or opting out). Omit for context-free callers, which get the static ones.
+ */
+ manifestContext?: BuiltinToolResolveContext;
+}
+
+export interface ManifestPool {
+ /** Identifiers served by a connector manifest; same-named plugins were dropped. */
+ connectorIdentifiers: Set<string>;
+ /**
+ * How many manifests the exclusion actually removed โ€” not the size of the
+ * excluded set, which may name identifiers no source contributed (a device
+ * builtin the walls already dropped, say). Diagnostics read this.
+ */
+ excludedCount: number;
+ manifests: LobeToolManifest[];
+}
+
+/**
+ * The manifest pool a tools engine may resolve tools from. Rules: a connector
+ * that produced a manifest replaces the same-named plugin; manifests executed
+ * outside the connector path get the connector's tool permissions patched in;
+ * context-aware builtins resolve for the run; every source drops entries the
+ * engine could not use; excluded identifiers are removed from every source.
+ */
+export const assembleManifestPool = (
+ sources: ManifestPoolSources,
+ options: AssembleManifestPoolOptions = {},
+): ManifestPool => {
+ const { connectorPermissions, manifestContext } = options;
+ const connectorManifests = dropInvalidManifests(sources.connectors ?? [], 'connectors');
+ const connectorIdentifiers = new Set(connectorManifests.map((m) => m.identifier));
+
+ const withPermissions = (manifest: LobeToolManifest): LobeToolManifest => {
+ const perms = connectorPermissions?.get(manifest.identifier);
+ return perms && perms.size > 0 ? patchManifestWithPermissions(manifest, perms) : manifest;
+ };
+
+ const pluginManifests = dropInvalidManifests(sources.installedPlugins ?? [], 'installedPlugins')
+ .filter((m) => !connectorIdentifiers.has(m.identifier))
+ .map(withPermissions);
+ const builtinManifests = dropInvalidManifests(
+ (sources.builtinTools ?? []).map((tool) =>
+ manifestContext && tool.resolveManifest
+ ? (tool.resolveManifest(manifestContext) as LobeToolManifest | null)
+ : (tool.manifest as LobeToolManifest),
+ ),
+ 'builtinTools',
+ );
+ const composioManifests = dropInvalidManifests(sources.composio ?? [], 'composio').map(
+ withPermissions,
+ );
+ const lobehubSkillManifests = dropInvalidManifests(
+ sources.lobehubSkills ?? [],
+ 'lobehubSkills',
+ ).map(withPermissions);
+ const additionalManifests = dropInvalidManifests(sources.additional ?? [], 'additionalManifests');
+
+ const excluded = new Set(options.excludedIdentifiers ?? []);
+ const merged = [
+ ...pluginManifests,
+ ...builtinManifests,
+ ...composioManifests,
+ ...lobehubSkillManifests,
+ ...connectorManifests,
+ ...additionalManifests,
+ ];
+ const manifests = merged.filter((m) => !excluded.has(m.identifier));
+
+ return { connectorIdentifiers, excludedCount: merged.length - manifests.length, manifests };
+};
diff --git a/src/helpers/toolEngineering/buildClientConnectorManifests.ts b/src/helpers/toolEngineering/buildClientConnectorManifests.ts
index c4d1ebf72b9..7cb3cd265cf 100644
--- a/src/helpers/toolEngineering/buildClientConnectorManifests.ts
+++ b/src/helpers/toolEngineering/buildClientConnectorManifests.ts
@@ -1,66 +1,24 @@
+import { buildConnectorManifest } from '@lobechat/mecha';
import { type ToolManifest } from '@lobechat/types';
-import { ConnectorToolPermission } from '@/database/schemas';
import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';
/**
* Convert connector store rows into ToolManifest entries for the classic
- * (client-orchestrated) chat path, mirroring the server-side
- * `buildConnectorManifests`. The manifest carries no `mcpParams`/auth โ€” the
- * client has no token; connector tool calls are executed server-side via
- * `connector.callTool`, which decrypts the stored credentials.
- *
- * Permission mapping:
- * - 'auto' โ†’ humanIntervention undefined (AI calls freely)
- * - 'needs_approval' โ†’ humanIntervention 'required'
- * - 'disabled' โ†’ tool included with a blocking description
+ * (client-orchestrated) chat path. The manifest carries no `mcpParams`/auth โ€”
+ * the client has no token; connector tool calls are executed server-side via
+ * `connector.callTool`, which decrypts the stored credentials. The permission
+ * mapping is the shared rule in `@lobechat/mecha`.
*/
-export const buildClientConnectorManifests = (connectors: ConnectorWithTools[]): ToolManifest[] => {
- const manifests: ToolManifest[] = [];
-
- for (const connector of connectors) {
- if (!connector.isEnabled) continue;
- const tools = connector.tools ?? [];
- if (tools.length === 0) continue;
-
- const api = tools.map((t) => {
- const parameters = (t.inputSchema ?? { properties: {}, type: 'object' }) as Record<
- string,
- unknown
- >;
- if (t.permission === ConnectorToolPermission.disabled) {
- return {
- description:
- `[TOOL DISABLED] The user has disabled this tool and it cannot be executed. ` +
- `Do NOT call this tool. If the user asks to perform this action, inform them ` +
- `that they have manually disabled "${t.toolName}" and can re-enable it in Settings > Connectors.`,
- humanIntervention: 'required' as const,
- name: t.toolName,
- parameters,
- };
- }
- return {
- description: t.description ?? '',
- humanIntervention:
- t.permission === ConnectorToolPermission.needs_approval
- ? ('required' as const)
- : undefined,
- name: t.toolName,
- parameters,
- };
- });
-
- manifests.push({
- api,
- identifier: connector.identifier,
- meta: {
- avatar: 'MCP_AVATAR',
- description: `${connector.name} connector with ${api.length} tools`,
- title: connector.name,
- },
- type: 'mcp' as any,
- });
- }
-
- return manifests;
-};
+export const buildClientConnectorManifests = (connectors: ConnectorWithTools[]): ToolManifest[] =>
+ connectors
+ .map((connector) =>
+ buildConnectorManifest({
+ identifier: connector.identifier,
+ isEnabled: connector.isEnabled,
+ name: connector.name,
+ tools: connector.tools ?? [],
+ }),
+ )
+ .filter((manifest): manifest is NonNullable<typeof manifest> => !!manifest)
+ .map((manifest) => manifest as ToolManifest);
diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.ts
index aef2c05169c..6813b15dec2 100644
--- a/src/helpers/toolEngineering/index.ts
+++ b/src/helpers/toolEngineering/index.ts
@@ -2,21 +2,22 @@
* Tools Engineering - Unified tools processing using ToolsEngine
*/
import { AuvManifest } from '@lobechat/builtin-tool-auv';
-import { createEnableChecker, type PluginEnableChecker } from '@lobechat/context-engine';
+import {
+ createEnableChecker,
+ type LobeToolManifest,
+ type PluginEnableChecker,
+} from '@lobechat/context-engine';
import { ToolsEngine } from '@lobechat/context-engine';
-import { resolveToolRules } from '@lobechat/mecha';
+import { assembleManifestPool, resolveToolRules } from '@lobechat/mecha';
import {
- type BuiltinToolManifest,
type BuiltinToolResolveContext,
type ChatCompletionTool,
type ToolManifest,
type WorkingModel,
} from '@lobechat/types';
-import type { ConnectorToolPermission } from '@/database/schemas';
import { applyToolNameMaxLength } from '@/helpers/applyToolNameMaxLength';
import { isToolAvailableInCurrentEnv } from '@/helpers/toolAvailability';
-import { patchManifestWithPermissions } from '@/libs/mcp/patchManifestPermissions';
import { getAgentStoreState } from '@/store/agent';
import {
agentChatConfigSelectors,
@@ -65,43 +66,6 @@ export interface ToolsEngineConfig {
manifestContext?: BuiltinToolResolveContext;
}
-/**
- * A manifest is usable by ToolsEngine only if it has a non-empty `api` array.
- * ToolsEngine.convertManifestsToTools calls `manifest.api.map(...)` unconditionally,
- * so any entry with `api` missing / non-array will crash the whole tools build.
- * Sources that populate manifests (installed plugins, Composio, LobeHub skills, MCP)
- * have no shared schema validation, so we guard defensively at the merge point.
- */
-const isValidToolManifest = (m: ToolManifest | undefined): m is ToolManifest =>
- !!m && typeof m === 'object' && Array.isArray((m as ToolManifest).api);
-
-const dropInvalidManifests = (manifests: (ToolManifest | undefined)[], source: string) => {
- const valid: ToolManifest[] = [];
- const dropped: Array<{ identifier?: string; reason: string }> = [];
-
- for (const m of manifests) {
- if (isValidToolManifest(m)) {
- valid.push(m);
- } else if (m) {
- dropped.push({
- identifier: (m as { identifier?: string }).identifier,
- reason: Array.isArray((m as { api?: unknown }).api)
- ? 'unknown'
- : 'missing `api` field (expected array)',
- });
- }
- }
-
- if (dropped.length > 0) {
- console.warn(
- `[toolEngineering] Dropped ${dropped.length} invalid manifest(s) from ${source}:`,
- dropped,
- );
- }
-
- return valid;
-};
-
/**
* Initialize ToolsEngine with current manifest schemas and configurable options
*/
@@ -121,91 +85,55 @@ export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine =
const toolStoreState = getToolStoreState();
- // Get custom connector manifests (user-added MCP servers). Connectors take
- // priority over plugins: any plugin sharing a connector identifier is dropped
- // so the connector (server-side execution with its stored token) wins.
- const connectorManifests = buildClientConnectorManifests(
- connectorSelectors.customConnectors(toolStoreState),
- );
- const connectorIdentifiers = new Set(connectorManifests.map((m) => m.identifier));
-
- // Per-connector tool permissions, keyed by connector identifier. Used to patch
- // community-MCP plugin manifests below so the user's needs_approval / disabled
- // settings surface as humanIntervention (custom connectors are handled by their
- // own manifests above; disabled is also hard-blocked at the mcp router).
- const connectorPermsByIdentifier = new Map(
+ // Per-connector tool permissions, keyed by connector identifier: community-
+ // MCP plugins execute outside the connector path, so the user's
+ // needs_approval / disabled settings are patched onto their manifests.
+ const connectorPermissions = new Map(
connectorSelectors
.connectorList(toolStoreState)
.map((c) => [c.identifier, new Map(c.tools.map((t) => [t.toolName, t.permission]))] as const),
);
- // Get all available plugin manifests (excluding ones now covered by a connector),
- // patched with their connector tool permissions when a connector row exists.
- const pluginManifests = pluginSelectors
- .installedPluginManifestList(toolStoreState)
- .filter((m) => !connectorIdentifiers.has(m.identifier))
- .map((m) => {
- const perms = connectorPermsByIdentifier.get(m.identifier);
- return perms && perms.size > 0
- ? (patchManifestWithPermissions(
- m as any,
- perms as Map<string, ConnectorToolPermission>,
- ) as ToolManifest)
- : m;
- });
-
- // Get all builtin tool manifests. When a manifest context is supplied (agent
- // runtime path), context-aware tools resolve their manifest for it โ€” trimming
- // APIs (e.g. lobe-agent hides callSubAgent in groups) or opting out via `null`.
- // Context-free callers fall back to the full static manifest.
- const builtinManifests = toolStoreState.builtinTools
- .map((tool) =>
- manifestContext && tool.resolveManifest
- ? tool.resolveManifest(manifestContext)
- : tool.manifest,
- )
- .filter((m): m is BuiltinToolManifest => !!m) as ToolManifest[];
-
- // Get Composio tool manifests
- const composioTools = composioStoreSelectors.composioAsLobeTools(toolStoreState);
- const composioManifests = composioTools
- .map((tool) => tool.manifest as ToolManifest)
- .filter(Boolean);
-
- // Get LobeHub Skill tool manifests
- const lobehubSkillTools = lobehubSkillStoreSelectors.lobehubSkillAsLobeTools(toolStoreState);
- const lobehubSkillManifests = lobehubSkillTools
- .map((tool) => tool.manifest as ToolManifest)
- .filter(Boolean);
-
- // Combine all manifests, dropping entries that would crash ToolsEngine.
- // Each source is filtered separately so the warning pinpoints the origin.
- const combinedManifests = [
- ...dropInvalidManifests(pluginManifests, 'installedPlugins'),
- ...dropInvalidManifests(builtinManifests, 'builtinTools'),
- ...dropInvalidManifests(composioManifests, 'composio'),
- ...dropInvalidManifests(lobehubSkillManifests, 'lobehubSkills'),
- ...dropInvalidManifests(connectorManifests, 'connectors'),
- ...dropInvalidManifests(additionalManifests, 'additionalManifests'),
- ];
+ // The pool rules (connector precedence, permission patching, context-aware
+ // builtins, invalid manifest guard, disabled-id exclusion) are shared with
+ // the server; the browser only reads its stores.
+ const { manifests } = assembleManifestPool(
+ {
+ additional: additionalManifests as LobeToolManifest[],
+ builtinTools: toolStoreState.builtinTools,
+ composio: composioStoreSelectors
+ .composioAsLobeTools(toolStoreState)
+ .map((tool) => tool.manifest as LobeToolManifest),
+ connectors: buildClientConnectorManifests(
+ connectorSelectors.customConnectors(toolStoreState),
+ ) as LobeToolManifest[],
+ installedPlugins: pluginSelectors.installedPluginManifestList(
+ toolStoreState,
+ ) as LobeToolManifest[],
+ lobehubSkills: lobehubSkillStoreSelectors
+ .lobehubSkillAsLobeTools(toolStoreState)
+ .map((tool) => tool.manifest as LobeToolManifest),
+ },
+ {
+ connectorPermissions,
+ // Disabled identifiers leave the pool outright: explicit activation
+ // bypasses the enable rules, so a rule-only gate would not hold.
+ excludedIdentifiers: disabledPluginIds,
+ manifestContext,
+ },
+ );
- // Disabled identifiers are dropped from the pool outright (not left for the
- // enableChecker rules) โ€” a plugin, skill, connector, or user-toggleable
- // builtin tool the agent has explicitly disabled must not be discoverable/
- // activatable at all, matching the server-side (aiAgent gateway) treatment.
- // Explicit activation bypasses enable rules; a plain Web client must not
- // acquire the Electron IPC executor. Gateway execution uses the server engine.
- const allManifests = combinedManifests.filter(
- (m) =>
- !disabledPluginIds.includes(m.identifier) &&
- (m.identifier !== AuvManifest.identifier || isToolAvailableInCurrentEnv(m.identifier)),
+ // A plain Web client must not acquire the Electron IPC executor: Computer
+ // Use only exists where the platform can run it.
+ const allManifests = manifests.filter(
+ (m) => m.identifier !== AuvManifest.identifier || isToolAvailableInCurrentEnv(m.identifier),
);
return new ToolsEngine({
defaultToolIds,
enableChecker,
functionCallChecker: isCanUseFC,
- manifestSchemas: allManifests,
+ manifestSchemas: allManifests as ToolManifest[],
});
};
diff --git a/src/libs/mcp/buildConnectorManifests.ts b/src/libs/mcp/buildConnectorManifests.ts
index 958665bee83..782cb77d861 100644
--- a/src/libs/mcp/buildConnectorManifests.ts
+++ b/src/libs/mcp/buildConnectorManifests.ts
@@ -1,8 +1,8 @@
+import { buildConnectorManifest } from '@lobechat/mecha';
import type { ToolManifest } from '@lobechat/types';
import type { DecryptedConnector } from '@/database/models/connector';
import type { UserConnectorToolItem } from '@/database/schemas';
-import { ConnectorToolPermission } from '@/database/schemas';
/**
* Convert connector DB rows into ToolManifest entries suitable for
@@ -27,57 +27,20 @@ export function buildConnectorManifests(
const manifests: ToolManifest[] = [];
for (const connector of connectors) {
- if (!connector.isEnabled) continue;
-
- const connectorTools = toolsByConnector.get(connector.id) ?? [];
-
- // Include ALL tools in the manifest so the AI is aware of their existence.
- // Disabled tools get a blocking description so the AI knows not to call them.
- // At execution time, the callTool endpoint will double-check and hard-block disabled tools.
- if (connectorTools.length === 0) continue;
-
- const api = connectorTools.map((t) => {
- if (t.permission === ConnectorToolPermission.disabled) {
- return {
- description:
- `[TOOL DISABLED] The user has disabled this tool and it cannot be executed. ` +
- `Do NOT call this tool. If the user asks to perform this action, inform them ` +
- `that they have manually disabled "${t.toolName}" and can re-enable it in Settings > Connectors.`,
- humanIntervention: 'required' as const,
- name: t.toolName,
- parameters: (t.inputSchema ?? { properties: {}, type: 'object' }) as Record<
- string,
- unknown
- >,
- };
- }
- return {
- description: t.description ?? '',
- humanIntervention:
- t.permission === ConnectorToolPermission.needs_approval
- ? ('required' as const)
- : undefined,
- name: t.toolName,
- parameters: (t.inputSchema ?? { properties: {}, type: 'object' }) as Record<
- string,
- unknown
- >,
- };
+ // The listing and the permission mapping are the shared rule; the server
+ // adds the endpoint and credentials the runtime needs to call it.
+ const manifest = buildConnectorManifest({
+ identifier: connector.identifier,
+ isEnabled: connector.isEnabled,
+ name: connector.name,
+ tools: toolsByConnector.get(connector.id) ?? [],
});
-
- const mcpParams = buildMcpParams(connector);
+ if (!manifest) continue;
manifests.push({
- api,
- identifier: connector.identifier,
+ ...(manifest as ToolManifest),
// @ts-ignore โ€” mcpParams is a runtime-only field not in the public type
- mcpParams,
- meta: {
- avatar: 'MCP_AVATAR',
- description: `${connector.name} connector with ${api.length} tools`,
- title: connector.name,
- },
- type: 'mcp' as any,
+ mcpParams: buildMcpParams(connector),
});
}
@@ -101,8 +64,7 @@ function buildMcpParams(connector: DecryptedConnector) {
// Merge them on top of any header-type credential headers (legacy rows), to
// mirror the sync/callTool path in services/connector/sync.ts.
const customHeaders = connector.metadata?.customHeaders as Record<string, string> | undefined;
- const mergedHeaders =
- headers || customHeaders ? { ...headers, ...customHeaders } : undefined;
+ const mergedHeaders = headers || customHeaders ? { ...headers, ...customHeaders } : undefined;
return {
auth,
diff --git a/src/libs/mcp/patchManifestPermissions.ts b/src/libs/mcp/patchManifestPermissions.ts
index 53e3657112d..928bd9386fd 100644
--- a/src/libs/mcp/patchManifestPermissions.ts
+++ b/src/libs/mcp/patchManifestPermissions.ts
@@ -1,42 +1,3 @@
-import { ConnectorToolPermission } from '@/database/schemas';
-
-/**
- * Patch a tool manifest's `api[]` with connector tool permissions.
- *
- * Pure (no DB / server imports) so it can run on BOTH the server runtime and the
- * classic client chat path. The 'disabled' hard-block is enforced separately at
- * execution time (ToolExecutionService / mcp router); this surfaces the
- * permission to the model and the client approval prompt.
- *
- * - needs_approval โ†’ humanIntervention: 'required' (approval prompt)
- * - disabled โ†’ blocking description + humanIntervention: 'required'
- */
-export function patchManifestWithPermissions<
- M extends {
- api: Array<{
- description?: string;
- humanIntervention?: unknown;
- name: string;
- [k: string]: unknown;
- }>;
- },
->(manifest: M, toolPermissions: Map<string, ConnectorToolPermission>): M {
- const patchedApi = manifest.api.map((api) => {
- const permission = toolPermissions.get(api.name);
- if (permission === ConnectorToolPermission.disabled) {
- return {
- ...api,
- description:
- `[TOOL DISABLED] The user has disabled this tool and it cannot be executed. ` +
- `Do NOT call this tool. If the user asks to perform this action, inform them ` +
- `that they have manually disabled "${api.name}" and can re-enable it in Settings > Connectors.`,
- humanIntervention: 'required' as const,
- };
- }
- if (permission === ConnectorToolPermission.needs_approval) {
- return { ...api, humanIntervention: 'required' as const };
- }
- return api;
- });
- return { ...manifest, api: patchedApi };
-}
+// The permission patch is a shared rule now: both hosts apply the same
+// mapping to manifests executed outside the connector path.
+export { patchManifestWithPermissions } from '@lobechat/mecha';