🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(plugin): install MCPs as connectors, keep the legacy create routes for released clients (#22367)
Lobehub Coder4ac339bcf17a
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.tsindex d813c338e29..6d5b40d88d2 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts@@ -2,6 +2,7 @@ import { type AgentState, selectToolSourceMap } from '@lobechat/agent-runtime';import { formatWebOnboardingStateMessage } from '@lobechat/builtin-tool-web-onboarding/utils';import { defaultUninstalledBuiltinTools } from '@lobechat/builtin-tools';import { AGENT_PLAN_FILE_TYPE } from '@lobechat/const';+import type { AvailablePluginInfo } from '@lobechat/context-engine';import {type AgentContextDocument,agentDocumentChangesByMessage,@@ -22,6 +23,7 @@ import { AgentModel } from '@/database/models/agent';import { AgentAccountModel } from '@/database/models/agentAccount';import { AiModelModel } from '@/database/models/aiModel';import { ChatGroupModel } from '@/database/models/chatGroup';+import { ConnectorModel } from '@/database/models/connector';import { FileModel } from '@/database/models/file';import { MessageModel } from '@/database/models/message';import { PluginModel } from '@/database/models/plugin';@@ -360,21 +362,37 @@ export const createServerContextFactProviders = ({}));},- // Custom MCP connectors the user installed, beyond the shared catalog.- // Read from the installed-plugins table: the run's tool source map only- // classifies skill / Composio / client tools, so it cannot tell a custom- // connector apart, and a connector the agent has not pinned yet must+ // Custom MCP servers the user installed, beyond the shared catalog: custom+ // connectors (every install now) and the custom plugin rows older installs+ // left, one entry per identifier. Read from the tables: the run's tool+ // source map only classifies skill / Composio / client tools, so it cannot+ // tell a custom connector apart, and one the agent has not pinned yet must// still be offered to createAgent / updateAgent.listCustomPlugins: async () => {- const installed = await new PluginModel(db, userId, ctx.workspaceId).query();- return installed- .filter((plugin) => plugin.type === 'customPlugin')- .map((plugin) => ({+ const [connectors, installed] = await Promise.all([+ new ConnectorModel(db, userId, ctx.workspaceId).queryPublic(),+ new PluginModel(db, userId, ctx.workspaceId).query(),+ ]);+ const plugins = new Map<string, AvailablePluginInfo>();+ for (const connector of connectors) {+ if (connector.sourceType !== 'custom') continue;+ plugins.set(connector.identifier, {+ description: connector.description ?? undefined,+ identifier: connector.identifier,+ name: connector.name || connector.identifier,+ type: 'custom',+ });+ }+ for (const plugin of installed) {+ if (plugin.type !== 'customPlugin' || plugins.has(plugin.identifier)) continue;+ plugins.set(plugin.identifier, {description: plugin.manifest?.meta?.description,identifier: plugin.identifier,name: plugin.manifest?.meta?.title || plugin.identifier,- type: 'custom' as const,- }));+ type: 'custom',+ });+ }+ return [...plugins.values()];},listEnabledProviders: async () => {diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.tsindex 2a057e95021..1b1c9aad3e0 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts@@ -5,6 +5,7 @@ import { createServerContextFactProviders } from './index';const {agentDocumentsConstructor,+ connectorQueryPublic,credsList,findById,getAgentContextDocuments,@@ -14,6 +15,7 @@ const {pluginQuery,} = vi.hoisted(() => ({agentDocumentsConstructor: vi.fn(),+ connectorQueryPublic: vi.fn(async () => [] as unknown[]),credsList: vi.fn(),findById: vi.fn(),getAgentContextDocuments: vi.fn(),@@ -39,6 +41,11 @@ vi.mock('@/database/models/user', () => ({{ getInfoForAIGeneration },),}));+vi.mock('@/database/models/connector', () => ({+ ConnectorModel: class {+ queryPublic = connectorQueryPublic;+ },+}));vi.mock('@/database/models/plugin', () => ({PluginModel: class {query = pluginQuery;@@ -175,6 +182,33 @@ describe('createServerContextFactProviders', () => {]);});+ // Installs now land only in user_connectors: a connector-only custom MCP+ // must still reach the builder's inventory, once per identifier.+ it('offers custom connectors beside legacy custom plugin rows', async () => {+ connectorQueryPublic.mockResolvedValueOnce([+ { description: 'Repo tools', identifier: 'repo-mcp', name: 'Repo', sourceType: 'custom' },+ { description: null, identifier: 'my-mcp', name: '', sourceType: 'custom' },+ { description: 'Docs', identifier: 'market-mcp', name: 'Docs', sourceType: 'marketplace' },+ ]);+ pluginQuery.mockResolvedValue([+ {+ identifier: 'my-mcp',+ manifest: { meta: { description: 'Stale', title: 'Old title' } },+ type: 'customPlugin',+ },+ { identifier: 'legacy-mcp', manifest: { meta: { title: 'Legacy' } }, type: 'customPlugin' },+ ]);++ await expect(+ createServerContextFactProviders(source({ operationToolSet: { sourceMap: {} } }))+ .listCustomPlugins!(),+ ).resolves.toEqual([+ { description: 'Repo tools', identifier: 'repo-mcp', name: 'Repo', type: 'custom' },+ { description: undefined, identifier: 'my-mcp', name: 'my-mcp', type: 'custom' },+ { description: undefined, identifier: 'legacy-mcp', name: 'Legacy', type: 'custom' },+ ]);+ });+it('reads the uninstalled builtin list from the scope the run belongs to', async () => {getUserSettings.mockResolvedValue({tool: {diff --git a/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.tsindex edd032f7e0a..1c05f10145f 100644--- a/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts+++ b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts@@ -186,7 +186,7 @@ describe('connectorRouter.syncPluginTools — customPlugin guard', () => {// Opening connector details automatically calls syncPluginTools. The old// update replaced metadata with display fields only, erasing the account id// needed for execution and remote revocation.- connectorModelMock.queryByIdentifiers.mockResolvedValueOnce([+ connectorModelMock.queryByIdentifiers.mockResolvedValue([{id: 'conn-existing',metadata: {@@ -215,6 +215,39 @@ describe('connectorRouter.syncPluginTools — customPlugin guard', () => {});});+ // A marketplace MCP reinstalled on the connector path keeps its plugin row and+ // that row's old manifest; opening Settings must not sync it over the tools+ // the reinstall synced from the server+ it.each([+ ['an HTTP', { mcpConnectionType: 'http', mcpServerUrl: 'https://mcp.example.com' }],+ ['a cloud', { mcpConnectionType: 'cloud', mcpServerUrl: null }],+ ['a stdio', { mcpConnectionType: 'stdio', mcpServerUrl: null }],+ ])('leaves %s connector installed for the identifier as it is', async (_, endpoint) => {+ connectorModelMock.queryByIdentifiers.mockResolvedValue([+ {+ id: 'conn-installed',+ metadata: { description: 'Synced from the server' },+ sourceType: 'marketplace',+ userId: 'user_test',+ ...endpoint,+ },+ ]);+ pluginModelMock.findById.mockResolvedValueOnce({+ type: 'plugin',+ manifest: {+ api: [{ description: 'Old search', name: 'search', parameters: {} }],+ meta: { description: 'Old manifest', title: 'Search MCP' },+ },+ });++ const result = await callerFor().syncPluginTools({ identifier: 'search-mcp' });++ expect(result).toEqual({ connectorId: 'conn-installed', toolCount: 0 });+ expect(connectorModelMock.update).not.toHaveBeenCalled();+ expect(connectorModelMock.create).not.toHaveBeenCalled();+ expect(connectorToolModelMock.upsertMany).not.toHaveBeenCalled();+ });+it('also defers when plugin has type=customPlugin AND has a manifest (no half-baked row written)', async () => {// Some legacy customPlugin rows DO have a manifest (cached from a successful// tools/list call earlier). The guard must not fall through just because adiff --git a/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.ts b/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.tsindex 563be319cb5..9132d6290df 100644--- a/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.ts+++ b/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.ts@@ -109,6 +109,152 @@ describe('connectorRouter.syncToolsFromClientById', () => {]);});+ it('makes a new tool need approval when its manifest requires intervention', async () => {+ await caller().syncToolsFromClientById({+ id: CONNECTOR_ID,+ tools: [+ { humanIntervention: 'required', toolName: 'send_mail' },+ { humanIntervention: 'always', toolName: 'delete_file' },+ { humanIntervention: 'never', toolName: 'list_files' },+ { toolName: 'read_file' },+ ],+ });++ expect(connectorToolModelMock.upsertMany).toHaveBeenCalledWith(CONNECTOR_ID, [+ expect.objectContaining({ defaultPermission: 'needs_approval', toolName: 'send_mail' }),+ expect.objectContaining({ defaultPermission: 'needs_approval', toolName: 'delete_file' }),+ expect.objectContaining({ defaultPermission: 'auto', toolName: 'list_files' }),+ expect.objectContaining({ defaultPermission: 'auto', toolName: 'read_file' }),+ ]);+ });++ // The connector manifest carries one permission per tool, so a rule list that+ // asks for approval for some arguments must not land as `auto`+ it('makes a new tool need approval when any of its intervention rules requires it', async () => {+ await caller().syncToolsFromClientById({+ id: CONNECTOR_ID,+ tools: [+ {+ humanIntervention: [+ { match: { path: '/tmp/*' }, policy: 'never' },+ { match: { recursive: 'true' }, policy: 'always' },+ ],+ toolName: 'remove_path',+ },+ {+ humanIntervention: [+ { match: { mode: 'draft' }, policy: 'never' },+ { policy: 'required' },+ ],+ toolName: 'publish_post',+ },+ { humanIntervention: [{ policy: 'never' }], toolName: 'list_posts' },+ ],+ });++ expect(connectorToolModelMock.upsertMany).toHaveBeenCalledWith(CONNECTOR_ID, [+ expect.objectContaining({ defaultPermission: 'needs_approval', toolName: 'remove_path' }),+ expect.objectContaining({ defaultPermission: 'needs_approval', toolName: 'publish_post' }),+ expect.objectContaining({ defaultPermission: 'auto', toolName: 'list_posts' }),+ ]);+ });++ // A dynamic resolver does not run on a connector: either of its outcomes counts+ it('makes a new tool need approval when its dynamic config can require it', async () => {+ await caller().syncToolsFromClientById({+ id: CONNECTOR_ID,+ tools: [+ { humanIntervention: { dynamic: { default: 'always', type: 'x' } }, toolName: 'a' },+ { humanIntervention: { dynamic: { default: 'never', type: 'x' } }, toolName: 'b' },+ {+ humanIntervention: { dynamic: { default: 'never', policy: 'required', type: 'x' } },+ toolName: 'c',+ },+ {+ humanIntervention: { dynamic: { default: 'never', policy: 'never', type: 'x' } },+ toolName: 'd',+ },+ ],+ });++ expect(connectorToolModelMock.upsertMany).toHaveBeenCalledWith(CONNECTOR_ID, [+ expect.objectContaining({ defaultPermission: 'needs_approval', toolName: 'a' }),+ // An unset `policy` is `always` when the resolver matches+ expect.objectContaining({ defaultPermission: 'needs_approval', toolName: 'b' }),+ expect.objectContaining({ defaultPermission: 'needs_approval', toolName: 'c' }),+ expect.objectContaining({ defaultPermission: 'auto', toolName: 'd' }),+ ]);+ });++ // The connector manifest maps `needs_approval` to `required`, which auto-run+ // and headless skip; a manifest's `always` must survive as its own mark+ it('marks a tool whose manifest can ask for always approval, on every sync', async () => {+ await caller().syncToolsFromClientById({+ id: CONNECTOR_ID,+ tools: [+ { humanIntervention: 'always', toolName: 'delete_file' },+ { humanIntervention: 'always', toolName: 'wipe', visibility: ['model'] },+ {+ humanIntervention: [+ { match: { path: '/tmp/*' }, policy: 'never' },+ { match: { recursive: 'true' }, policy: 'always' },+ ],+ toolName: 'remove_path',+ },+ { humanIntervention: { dynamic: { default: 'never', type: 'x' } }, toolName: 'audited' },+ { humanIntervention: 'required', toolName: 'send_mail' },+ {+ humanIntervention: { dynamic: { default: 'never', policy: 'required', type: 'x' } },+ toolName: 'publish',+ },+ { toolName: 'read_file', visibility: ['app'] },+ ],+ });++ expect(connectorToolModelMock.upsertMany).toHaveBeenCalledWith(CONNECTOR_ID, [+ expect.objectContaining({ metadata: { mandatoryApproval: true }, toolName: 'delete_file' }),+ expect.objectContaining({+ metadata: { mandatoryApproval: true, visibility: ['model'] },+ toolName: 'wipe',+ }),+ expect.objectContaining({ metadata: { mandatoryApproval: true }, toolName: 'remove_path' }),+ expect.objectContaining({ metadata: { mandatoryApproval: true }, toolName: 'audited' }),+ expect.objectContaining({ metadata: null, toolName: 'send_mail' }),+ expect.objectContaining({ metadata: null, toolName: 'publish' }),+ expect.objectContaining({ metadata: { visibility: ['app'] }, toolName: 'read_file' }),+ ]);+ });++ it('drops the auto tools an install no longer lists, keeping permission tombstones', async () => {+ connectorToolModelMock.queryByConnector = vi.fn().mockResolvedValue([+ { permission: 'auto', toolName: 'kept' },+ { permission: 'auto', toolName: 'removed_auto' },+ { permission: 'needs_approval', toolName: 'removed_gated' },+ { permission: 'disabled', toolName: 'removed_disabled' },+ ]);+ connectorToolModelMock.deleteToolsNotIn = vi.fn();++ await caller().syncToolsFromClientById({+ id: CONNECTOR_ID,+ pruneMissingAutoTools: true,+ tools: [{ toolName: 'kept' }],+ });++ expect(connectorToolModelMock.deleteToolsNotIn).toHaveBeenCalledWith(CONNECTOR_ID, [+ 'kept',+ 'removed_gated',+ 'removed_disabled',+ ]);+ });++ it('leaves the stored tools alone without an install', async () => {+ connectorToolModelMock.deleteToolsNotIn = vi.fn();++ await caller().syncToolsFromClientById({ id: CONNECTOR_ID, tools: [{ toolName: 'kept' }] });++ expect(connectorToolModelMock.deleteToolsNotIn).not.toHaveBeenCalled();+ });+it('rejects an unknown connector id', async () => {connectorModelMock.findById.mockResolvedValue(undefined);diff --git a/apps/server/src/routers/lambda/__tests__/connector.update.test.ts b/apps/server/src/routers/lambda/__tests__/connector.update.test.tsnew file mode 100644index 00000000000..4eaa26ee616--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/connector.update.test.ts@@ -0,0 +1,88 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { ConnectorModel } from '@/database/models/connector';++import { connectorRouter } from '../connector';++vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));+vi.mock('@/database/models/connector', () => ({ ConnectorModel: vi.fn() }));+vi.mock('@/database/models/connectorTool', () => ({ ConnectorToolModel: vi.fn() }));+vi.mock('@/database/models/plugin', () => ({ PluginModel: vi.fn() }));+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({+ KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },+}));+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');+ return {+ requireWorkspaceRoleWhenScoped: () => mod.trpc.middleware((opts: any) => opts.next()),+ wsCompatProcedure: mod.trpc.procedure,+ };+});+vi.mock('@/libs/trpc/lambda/middleware', () => ({+ serverDatabase: async (opts: any) =>+ opts.next({ ctx: { ...opts.ctx, serverDB: opts.ctx.serverDB ?? {} } }),+}));++const CONNECTOR_ID = '9f1f6f30-0000-4000-8000-000000000003';++describe('connectorRouter.update', () => {+ let connectorModelMock: { findById: ReturnType<typeof vi.fn>; update: ReturnType<typeof vi.fn> };+ const update = (patch: Record<string, unknown>) =>+ connectorRouter+ .createCaller({ serverDB: {}, userId: 'me' } as any)+ .update({ id: CONNECTOR_ID, patch });++ beforeEach(() => {+ vi.clearAllMocks();+ connectorModelMock = {+ findById: vi.fn().mockResolvedValue({ id: CONNECTOR_ID, metadata: {}, userId: 'me' }),+ update: vi.fn(),+ };+ vi.mocked(ConnectorModel).mockImplementation(function () {+ return connectorModelMock as any;+ });+ });++ // A client undoes a failed OAuth edit only when it can tell a callback that+ // connected the row from a canceled popup: only that callback reconnects it+ it('leaves the row disconnected until a new OAuth client is authorized', async () => {+ await update({ mcpServerUrl: 'https://new.example.com', oidcConfig: { scheme: 'dcr' } });++ expect(connectorModelMock.update).toHaveBeenCalledWith(+ CONNECTOR_ID,+ expect.objectContaining({ oidcConfig: { scheme: 'dcr' }, status: 'disconnected' }),+ );+ });++ it('drops an OAuth client without touching the status', async () => {+ await update({ oidcConfig: null });++ const [, stored] = connectorModelMock.update.mock.calls[0];+ expect(stored).toMatchObject({ oidcConfig: null });+ expect(stored).not.toHaveProperty('status');+ });++ // Undoing a failed custom install over a legacy marketplace projection: the+ // install's `create` made the row `custom`, the rollback makes it marketplace+ it('puts a row back on the install source it came from', async () => {+ await update({ mcpConnectionType: null, mcpServerUrl: null, sourceType: 'marketplace' });++ expect(connectorModelMock.update).toHaveBeenCalledWith(+ CONNECTOR_ID,+ expect.objectContaining({ mcpServerUrl: null, sourceType: 'marketplace' }),+ );+ });++ it('refuses to turn a row into a builtin tool', async () => {+ await expect(update({ sourceType: 'builtin' })).rejects.toMatchObject({ code: 'BAD_REQUEST' });++ expect(connectorModelMock.update).not.toHaveBeenCalled();+ });++ it('keeps the status of an edit that brings no OAuth client', async () => {+ await update({ name: 'Renamed' });++ expect(connectorModelMock.update.mock.calls[0][1]).not.toHaveProperty('status');+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/plugin.legacyWrites.test.ts b/apps/server/src/routers/lambda/__tests__/plugin.legacyWrites.test.tsnew file mode 100644index 00000000000..82ac374686d--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/plugin.legacyWrites.test.ts@@ -0,0 +1,120 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { PluginModel } from '@/database/models/plugin';++import { toClientVersionLabel } from '../_helpers/legacyPluginWriteMetrics';+import { pluginRouter } from '../plugin';++const counter = vi.hoisted(() => ({ add: vi.fn() }));++vi.mock('@lobechat/observability-otel/modules/legacy-plugin-write', () => ({+ legacyPluginWriteCounter: counter,+}));+vi.mock('@/database/models/plugin', () => ({ PluginModel: vi.fn() }));+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');+ // The real `wsCompatProcedure` validates a Better-Auth session; unit tests+ // skip auth and rely on the test ctx already carrying `userId`.+ return { wsCompatProcedure: mod.trpc.procedure };+});+vi.mock('@/libs/trpc/lambda/middleware', () => ({+ serverDatabase: async (opts: any) =>+ opts.next({ ctx: { ...opts.ctx, serverDB: opts.ctx.serverDB ?? {} } }),+}));++/**+ * Released clients still install MCPs through these two routes, so until the+ * routes are removed they must keep writing `user_installed_plugins` rows+ * exactly as before, and every call must be counted.+ */+describe('pluginRouter legacy create routes', () => {+ let pluginModel: {+ create: ReturnType<typeof vi.fn>;+ findById: ReturnType<typeof vi.fn>;+ update: ReturnType<typeof vi.fn>;+ };++ const caller = () =>+ pluginRouter.createCaller({+ clientMetadata: { type: 'desktop', version: '2.1.4' },+ userId: 'user-1',+ } as any);++ beforeEach(() => {+ vi.clearAllMocks();+ pluginModel = {+ create: vi.fn(async (row: { identifier: string }) => ({ identifier: row.identifier })),+ findById: vi.fn().mockResolvedValue(undefined),+ update: vi.fn(),+ };+ vi.mocked(PluginModel).mockImplementation(function () {+ return pluginModel as any;+ });+ });++ it('createOrInstallPlugin still creates a plugin row and counts the call', async () => {+ const manifest = { api: [], identifier: 'box' };++ const result = await caller().createOrInstallPlugin({+ customParams: { mcp: { type: 'http', url: 'https://mcp.example.com' } },+ identifier: 'box',+ manifest,+ settings: { token: 'x' },+ type: 'plugin',+ });++ expect(result).toBe('box');+ expect(pluginModel.create).toHaveBeenCalledWith({+ customParams: { mcp: { type: 'http', url: 'https://mcp.example.com' } },+ identifier: 'box',+ manifest,+ settings: { token: 'x' },+ type: 'plugin',+ });+ expect(counter.add).toHaveBeenCalledWith(1, {+ client_type: 'desktop',+ client_version: toClientVersionLabel('2.1.4'),+ plugin_type: 'plugin',+ procedure: 'createOrInstallPlugin',+ });+ });++ it('createOrInstallPlugin still only refreshes the manifest of an existing row', async () => {+ pluginModel.findById.mockResolvedValue({ identifier: 'box', userId: 'user-1' });+ const manifest = { api: [{ name: 'search' }], identifier: 'box' };++ const result = await caller().createOrInstallPlugin({+ identifier: 'box',+ manifest,+ type: 'plugin',+ });++ expect(result).toBeUndefined();+ expect(pluginModel.create).not.toHaveBeenCalled();+ expect(pluginModel.update).toHaveBeenCalledWith('box', { manifest });+ expect(counter.add).toHaveBeenCalledTimes(1);+ });++ it('createPlugin still creates a custom plugin row and counts the call', async () => {+ const result = await caller().createPlugin({+ customParams: { mcp: { command: 'npx', type: 'stdio' } },+ identifier: 'my-mcp',+ type: 'customPlugin',+ });++ expect(result).toBe('my-mcp');+ expect(pluginModel.create).toHaveBeenCalledWith({+ customParams: { mcp: { command: 'npx', type: 'stdio' } },+ identifier: 'my-mcp',+ manifest: undefined,+ type: 'customPlugin',+ });+ expect(counter.add).toHaveBeenCalledWith(1, {+ client_type: 'desktop',+ client_version: toClientVersionLabel('2.1.4'),+ plugin_type: 'customPlugin',+ procedure: 'createPlugin',+ });+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/cloudMcpCaller.test.ts b/apps/server/src/routers/lambda/_helpers/cloudMcpCaller.test.tsnew file mode 100644index 00000000000..ed8b2ea51d3--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/cloudMcpCaller.test.ts@@ -0,0 +1,78 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DiscoverService } from '@/server/services/discover';++import { resolveRequestCloudMcpCaller } from './cloudMcpCaller';++const resolveMarketUserContext = vi.hoisted(() => vi.fn());+const isTrustedClientEnabled = vi.hoisted(() => vi.fn());+const getUserSettings = vi.hoisted(() => vi.fn());++vi.mock('@/libs/trpc/lambda/middleware', () => ({ resolveMarketUserContext }));+vi.mock('@/libs/trusted-client', () => ({ isTrustedClientEnabled }));+vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn(function UserModel() {+ return { getUserSettings };+ }),+}));+vi.mock('@/server/services/discover', () => ({+ DiscoverService: vi.fn(function DiscoverService(this: any, options: unknown) {+ this.options = options;+ }),+}));+vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(function FileService(this: any, ...args: unknown[]) {+ this.args = args;+ }),+}));++const ctx = {+ marketAccessToken: 'cookie-token',+ serverDB: {} as any,+ userId: 'user-1',+ workspaceId: 'ws-1',+};+const marketUserInfo = { email: '[email protected]', userId: 'user-1', workspaceId: 'ws-1' };++beforeEach(() => {+ vi.clearAllMocks();+ resolveMarketUserContext.mockResolvedValue({ marketAccessToken: 'db-token', marketUserInfo });+});++describe('resolveRequestCloudMcpCaller', () => {+ it('forwards the stored Market token when trusted-client auth is not configured', async () => {+ isTrustedClientEnabled.mockReturnValue(false);+ getUserSettings.mockResolvedValue({ market: { accessToken: 'db-token' } });++ const caller = await resolveRequestCloudMcpCaller(ctx);++ expect(caller?.userAccessToken).toBe('db-token');+ expect(DiscoverService).toHaveBeenCalledWith({+ accessToken: 'db-token',+ userInfo: marketUserInfo,+ });+ // Media blocks are stored in the requester's own (workspace) storage+ expect((caller?.fileService as any).args).toEqual([ctx.serverDB, 'user-1', 'ws-1']);+ });++ it('has no caller without a stored Market token when trusted-client auth is off', async () => {+ isTrustedClientEnabled.mockReturnValue(false);+ getUserSettings.mockResolvedValue({ market: {} });++ await expect(resolveRequestCloudMcpCaller(ctx)).resolves.toBeUndefined();+ expect(DiscoverService).not.toHaveBeenCalled();+ });++ it('runs as the trusted-client identity without reading a user token', async () => {+ isTrustedClientEnabled.mockReturnValue(true);++ const caller = await resolveRequestCloudMcpCaller(ctx);++ expect(caller?.userAccessToken).toBeUndefined();+ expect(getUserSettings).not.toHaveBeenCalled();+ expect(DiscoverService).toHaveBeenCalledWith({+ accessToken: 'db-token',+ userInfo: marketUserInfo,+ });+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/cloudMcpCaller.ts b/apps/server/src/routers/lambda/_helpers/cloudMcpCaller.tsnew file mode 100644index 00000000000..689cfe4999d--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/cloudMcpCaller.ts@@ -0,0 +1,41 @@+import type { LobeChatDatabase } from '@lobechat/database';++import { UserModel } from '@/database/models/user';+import { resolveMarketUserContext } from '@/libs/trpc/lambda/middleware';+import { isTrustedClientEnabled } from '@/libs/trusted-client';+import { DiscoverService } from '@/server/services/discover';+import type { CloudMcpCaller } from '@/server/services/mcp/cloudTool';++import { resolveRequestFileService } from './requestFileService';++/**+ * The caller a signed-in request runs a cloud MCP tool as, the way+ * `market.callCloudMcpEndpoint` does: the user's Market identity, their stored+ * Market token when trusted-client auth is not configured, and their file+ * storage for media blocks. `undefined` when there is no Market credential.+ */+export const resolveRequestCloudMcpCaller = async (ctx: {+ marketAccessToken?: string;+ serverDB: LobeChatDatabase;+ userId: string;+ workspaceId?: string | null;+}): Promise<CloudMcpCaller | undefined> => {+ const { marketAccessToken, marketUserInfo } = await resolveMarketUserContext(ctx);++ // Without trusted-client auth the market knows the user only by their own token+ let userAccessToken: string | undefined;+ if (!isTrustedClientEnabled()) {+ const settings = await new UserModel(ctx.serverDB, ctx.userId).getUserSettings();+ userAccessToken = (settings?.market as { accessToken?: string } | undefined)?.accessToken;+ if (!userAccessToken) return undefined;+ }++ return {+ discoverService: new DiscoverService({+ accessToken: marketAccessToken,+ userInfo: marketUserInfo,+ }),+ fileService: resolveRequestFileService(ctx),+ userAccessToken,+ };+};diff --git a/apps/server/src/routers/lambda/_helpers/connectorCallContext.test.ts b/apps/server/src/routers/lambda/_helpers/connectorCallContext.test.tsnew file mode 100644index 00000000000..b09c0a46a01--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/connectorCallContext.test.ts@@ -0,0 +1,69 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { checkTelemetryEnabled } from '@/libs/trpc/lambda/middleware';+import { scheduleToolCallReport } from '@/server/routers/tools/_helpers/scheduleToolCallReport';++import {+ resolveRequestToolCallReporter,+ withRequestConnectorCallers,+} from './connectorCallContext';++vi.mock('@/libs/trpc/lambda/middleware', () => ({ checkTelemetryEnabled: vi.fn() }));+vi.mock('@/server/routers/tools/_helpers/scheduleToolCallReport', () => ({+ scheduleToolCallReport: vi.fn(),+}));+vi.mock('./cloudMcpCaller', () => ({ resolveRequestCloudMcpCaller: vi.fn() }));+vi.mock('./requestFileService', () => ({ resolveRequestFileService: vi.fn() }));++const ctx = { marketAccessToken: 'mp-token', serverDB: {} as never, userId: 'user-1' };+const report = {+ identifier: 'notes-mcp',+ mcpType: 'http',+ meta: { sessionId: 'tpc_1', version: '1.2.0' },+ requestPayload: '{}',+ startTime: 1,+ success: true,+ toolName: 'search',+};++beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(checkTelemetryEnabled).mockResolvedValue({ telemetryEnabled: true });+});++describe('resolveRequestToolCallReporter', () => {+ it("reports a call with the request's Market token while telemetry is on", async () => {+ const reporter = await resolveRequestToolCallReporter(ctx);++ reporter!(report);++ expect(scheduleToolCallReport).toHaveBeenCalledWith({+ ...report,+ marketAccessToken: 'mp-token',+ telemetryEnabled: true,+ });+ });++ it('reports nothing once the user turned telemetry off', async () => {+ vi.mocked(checkTelemetryEnabled).mockResolvedValue({ telemetryEnabled: false });++ await expect(resolveRequestToolCallReporter(ctx)).resolves.toBeUndefined();+ });++ it('reports nothing without a Market token, and does not read the setting', async () => {+ await expect(+ resolveRequestToolCallReporter({ ...ctx, marketAccessToken: undefined }),+ ).resolves.toBeUndefined();+ expect(checkTelemetryEnabled).not.toHaveBeenCalled();+ });+});++describe('withRequestConnectorCallers', () => {+ it('keeps the request context and resolves nothing up front', () => {+ const callers = withRequestConnectorCallers(ctx);++ expect(callers).toMatchObject(ctx);+ expect(callers.resolveToolCallReporter).toBeTypeOf('function');+ expect(checkTelemetryEnabled).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/connectorCallContext.ts b/apps/server/src/routers/lambda/_helpers/connectorCallContext.tsnew file mode 100644index 00000000000..78b85000d65--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/connectorCallContext.ts@@ -0,0 +1,43 @@+import type { LobeChatDatabase } from '@lobechat/database';++import { checkTelemetryEnabled } from '@/libs/trpc/lambda/middleware';+import { scheduleToolCallReport } from '@/server/routers/tools/_helpers/scheduleToolCallReport';+import type { ConnectorToolCallReporter } from '@/server/services/connector/exec';++import { resolveRequestCloudMcpCaller } from './cloudMcpCaller';+import { resolveRequestFileService } from './requestFileService';++interface RequestContext {+ marketAccessToken?: string;+ serverDB: LobeChatDatabase;+ userId: string;+ workspaceId?: string | null;+}++/**+ * Reports a marketplace connector's call to the Market the way+ * `tools.mcp.callTool` reports a plugin's: with the request's Market token, and+ * only while the user has telemetry on. `undefined` when neither holds.+ */+export const resolveRequestToolCallReporter = async (+ ctx: RequestContext,+): Promise<ConnectorToolCallReporter | undefined> => {+ const { marketAccessToken } = ctx;+ if (!marketAccessToken) return;+ const { telemetryEnabled } = await checkTelemetryEnabled(ctx);+ if (!telemetryEnabled) return;++ return (report) => scheduleToolCallReport({ ...report, marketAccessToken, telemetryEnabled });+};++/**+ * What a signed-in request's connector tool call runs with: who a cloud tool+ * runs as, where a result's media blocks are stored, and how the call is+ * reported to the Market. Each is resolved only for a call that needs it.+ */+export const withRequestConnectorCallers = <T extends RequestContext>(ctx: T) => ({+ ...ctx,+ resolveCloudMcpCaller: () => resolveRequestCloudMcpCaller(ctx),+ resolveFileService: () => resolveRequestFileService(ctx),+ resolveToolCallReporter: () => resolveRequestToolCallReporter(ctx),+});diff --git a/apps/server/src/routers/lambda/_helpers/connectorToolPermission.ts b/apps/server/src/routers/lambda/_helpers/connectorToolPermission.tsnew file mode 100644index 00000000000..5a018cce16f--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/connectorToolPermission.ts@@ -0,0 +1,34 @@+import { humanInterventionMayResolveTo } from '@lobechat/const/plugin';++import { ConnectorToolPermission } from '@/database/schemas';++const APPROVAL_POLICIES = ['required', 'always'] as const;++const requiresApproval = (policy: unknown) =>+ (APPROVAL_POLICIES as readonly unknown[]).includes(policy);++/**+ * Map a builtin or plugin manifest's humanIntervention → default+ * ConnectorToolPermission. Their manifests keep their own rules at run time.+ */+export function resolveDefaultPermission(humanIntervention: unknown): ConnectorToolPermission {+ return requiresApproval(humanIntervention)+ ? ConnectorToolPermission.needs_approval+ : ConnectorToolPermission.auto;+}++/**+ * Map a manifest tool's humanIntervention → the default permission of the+ * connector tool that carries it from now on. The connector's manifest is+ * built from that one permission, so argument rules and dynamic resolvers+ * cannot survive: one that can ask for approval makes every call need it.+ * One that can ask for `always` also marks the tool's metadata+ * (`withMandatoryApprovalMark`), which keeps it past auto-run.+ */+export function resolveConnectorToolPermission(+ humanIntervention: unknown,+): ConnectorToolPermission {+ return humanInterventionMayResolveTo(humanIntervention, APPROVAL_POLICIES)+ ? ConnectorToolPermission.needs_approval+ : ConnectorToolPermission.auto;+}diff --git a/apps/server/src/routers/lambda/_helpers/legacyPluginWriteMetrics.test.ts b/apps/server/src/routers/lambda/_helpers/legacyPluginWriteMetrics.test.tsnew file mode 100644index 00000000000..5c647cfd668--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/legacyPluginWriteMetrics.test.ts@@ -0,0 +1,97 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { recordLegacyPluginWrite, toClientVersionLabel } from './legacyPluginWriteMetrics';++const counter = vi.hoisted(() => ({ add: vi.fn() }));++vi.mock('@lobechat/observability-otel/modules/legacy-plugin-write', () => ({+ legacyPluginWriteCounter: counter,+}));+// The server's own version bounds the labels+vi.mock('@lobechat/const', () => ({ CURRENT_VERSION: '2.3.3' }));++describe('toClientVersionLabel', () => {+ const server = '2.3.3';++ it.each([+ ['2.3.3', '2.3'],+ ['v2.3.1', '2.3'],+ ['2.3.0-canary.12', '2.3'],+ ['2.1.1-nightly.20261114', '2.1'],+ ['2.0.0', '2.0'],+ ])('labels the release %s by its release line %s', (version, label) => {+ expect(toClientVersionLabel(version, server)).toBe(label);+ });++ // A header can carry any version: past what this server ships, every value+ // shares one label instead of opening a series each+ it.each([['2.4.0'], ['2.9.4-canary.1'], ['3.0.0'], ['9999.9999.999999']])(+ 'labels %s, past the server, as newer',+ (version) => {+ expect(toClientVersionLabel(version, server)).toBe('newer');+ },+ );++ it.each([['1.143.2'], ['0.0.0-nightly.pr22902.39193'], ['1.0.0-canary.123456']])(+ 'labels %s, of an older major, as older',+ (version) => {+ expect(toClientVersionLabel(version, server)).toBe('older');+ },+ );++ it('keeps fabricated pre-releases of one line to one label', () => {+ const labels = new Set(+ Array.from({ length: 50 }, (_, i) => toClientVersionLabel(`2.3.0-canary.${i}`, server)),+ );++ expect([...labels]).toEqual(['2.3']);+ });++ it.each([['latest'], ['2.1'], ['2.1.4; DROP TABLE'], ['user-1234'], ['1.2.3-'.padEnd(60, 'x')]])(+ 'collapses the non-release version %s into other',+ (version) => {+ expect(toClientVersionLabel(version, server)).toBe('other');+ },+ );++ it('labels a missing version as none', () => {+ expect(toClientVersionLabel(undefined, server)).toBe('none');+ });++ it("bounds the labels by this server's version by default", () => {+ expect(toClientVersionLabel('2.3.9')).toBe('2.3');+ expect(toClientVersionLabel('2.4.0')).toBe('newer');+ });+});++describe('recordLegacyPluginWrite', () => {+ beforeEach(() => {+ counter.add.mockClear();+ });++ it('counts one call labelled by procedure, plugin type and client', () => {+ recordLegacyPluginWrite('createOrInstallPlugin', 'plugin', {+ type: 'desktop',+ version: '2.1.4',+ });++ expect(counter.add).toHaveBeenCalledWith(1, {+ client_type: 'desktop',+ client_version: '2.1',+ plugin_type: 'plugin',+ procedure: 'createOrInstallPlugin',+ });+ });++ it('counts a call without client metadata as an unknown client', () => {+ recordLegacyPluginWrite('createPlugin', 'customPlugin', undefined);++ expect(counter.add).toHaveBeenCalledWith(1, {+ client_type: 'unknown',+ client_version: 'none',+ plugin_type: 'customPlugin',+ procedure: 'createPlugin',+ });+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/legacyPluginWriteMetrics.ts b/apps/server/src/routers/lambda/_helpers/legacyPluginWriteMetrics.tsnew file mode 100644index 00000000000..e988588c892--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/legacyPluginWriteMetrics.ts@@ -0,0 +1,59 @@+import { CURRENT_VERSION } from '@lobechat/const';+import { legacyPluginWriteCounter } from '@lobechat/observability-otel/modules/legacy-plugin-write';+import type { ClientMetadata } from '@lobechat/utils/server';++export type LegacyPluginWriteProcedure = 'createOrInstallPlugin' | 'createPlugin';++/**+ * Release versions (`1.2.3`, `2.0.0-canary.4`, `0.0.0-nightly.pr1.2`),+ * capturing major and minor: only those reach a label.+ */+const RELEASE_VERSION_PATTERN = /^v?(\d{1,4})\.(\d{1,4})\.\d{1,6}(?:-[\d.a-z]{1,40})?$/i;++const toReleaseLine = (version: string): [major: number, minor: number] | undefined => {+ const match = RELEASE_VERSION_PATTERN.exec(version);+ return match ? [Number(match[1]), Number(match[2])] : undefined;+};++/**+ * The client's release line, bounded by this server's own version. The version+ * comes from a request header, so the label set must not grow with what+ * clients send:+ *+ * - `2.0` … `2.3` (for a 2.3.x server): a release line of the server's major,+ * pre-release and patch dropped;+ * - `older`: an older major; `newer`: past what this server ships;+ * - `other`: not a release version; `none`: no version sent.+ */+export const toClientVersionLabel = (+ version: string | undefined,+ serverVersion: string = CURRENT_VERSION,+): string => {+ if (!version) return 'none';+ const client = toReleaseLine(version);+ const server = toReleaseLine(serverVersion);+ if (!client || !server) return 'other';++ const [major, minor] = client;+ const [serverMajor, serverMinor] = server;+ if (major < serverMajor) return 'older';+ if (major > serverMajor || minor > serverMinor) return 'newer';+ return `${major}.${minor}`;+};++/**+ * Count one call to a legacy plugin create route, so deleting the routes can+ * wait until released clients have stopped calling them.+ */+export const recordLegacyPluginWrite = (+ procedure: LegacyPluginWriteProcedure,+ pluginType: 'customPlugin' | 'plugin',+ clientMetadata: ClientMetadata | undefined,+) => {+ legacyPluginWriteCounter.add(1, {+ client_type: clientMetadata?.type ?? 'unknown',+ client_version: toClientVersionLabel(clientMetadata?.version),+ plugin_type: pluginType,+ procedure,+ });+};diff --git a/apps/server/src/routers/lambda/_helpers/requestFileService.test.ts b/apps/server/src/routers/lambda/_helpers/requestFileService.test.tsnew file mode 100644index 00000000000..7537d8ca4e4--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/requestFileService.test.ts@@ -0,0 +1,33 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { FileService } from '@/server/services/file';++import { resolveRequestFileService } from './requestFileService';++vi.mock('@/server/services/file', () => ({ FileService: vi.fn() }));++const ctx = { serverDB: {} as never, userId: 'user-1', workspaceId: 'ws-1' };++beforeEach(() => {+ vi.mocked(FileService).mockReset();+});++describe('resolveRequestFileService', () => {+ it("builds the request user's file storage in their workspace", () => {+ vi.mocked(FileService).mockImplementation(function (this: object) {+ return this;+ } as never);++ expect(resolveRequestFileService(ctx)).toBeInstanceOf(FileService);+ expect(FileService).toHaveBeenCalledWith(ctx.serverDB, 'user-1', 'ws-1');+ });++ // An MCP call must still run where no file storage is configured+ it('resolves nothing when the storage cannot be built', () => {+ vi.mocked(FileService).mockImplementation(function () {+ throw new Error('S3 environment variables are not set completely, please check your env');+ } as never);++ expect(resolveRequestFileService(ctx)).toBeUndefined();+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/requestFileService.ts b/apps/server/src/routers/lambda/_helpers/requestFileService.tsnew file mode 100644index 00000000000..cbdcbce0e5e--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/requestFileService.ts@@ -0,0 +1,20 @@+import type { LobeChatDatabase } from '@lobechat/database';++import { FileService } from '@/server/services/file';++/**+ * The request user's file storage, where an MCP tool result's image / audio+ * blocks are stored. `undefined` without file storage configured (its S3+ * client throws on an incomplete env): the call still runs, its media inline.+ */+export const resolveRequestFileService = (ctx: {+ serverDB: LobeChatDatabase;+ userId: string;+ workspaceId?: string | null;+}): FileService | undefined => {+ try {+ return new FileService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);+ } catch {+ return undefined;+ }+};diff --git a/apps/server/src/routers/lambda/connector.syncTools.test.ts b/apps/server/src/routers/lambda/connector.syncTools.test.tsindex 99abba3282d..117ac6d2db0 100644--- a/apps/server/src/routers/lambda/connector.syncTools.test.ts+++ b/apps/server/src/routers/lambda/connector.syncTools.test.ts@@ -104,6 +104,20 @@ describe('connectorRouter.syncTools', () => {});});+ it('drops the auto tools the server no longer lists only for an install', async () => {+ sync.mockResolvedValue({ toolCount: 1 });++ await caller().syncTools({ id, pruneMissingAutoTools: true });+ await caller().syncTools({ id });++ expect(sync).toHaveBeenNthCalledWith(1, id, expect.anything(), {+ pruneMissingAutoTools: true,+ });+ expect(sync).toHaveBeenNthCalledWith(2, id, expect.anything(), {+ pruneMissingAutoTools: undefined,+ });+ });+it('still wraps unexpected upstream failures', async () => {sync.mockRejectedValue(new Error('connection reset'));await expect(caller().syncTools({ id })).rejects.toMatchObject({diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.tsindex 8733287819f..b9c688447cd 100644--- a/apps/server/src/routers/lambda/connector.ts+++ b/apps/server/src/routers/lambda/connector.ts@@ -1,4 +1,8 @@-import { getComposioAppByIdentifier } from '@lobechat/const';+import {+ getComposioAppByIdentifier,+ hasCallableMcpEndpoint,+ withMandatoryApprovalMark,+} from '@lobechat/const';import { isFullAccessApiKey } from '@lobechat/const/apiKeyScope';import { buildMcpToolMetadata } from '@lobechat/const/mcpApp';import { upsertPluginMode } from '@lobechat/types';@@ -48,7 +52,10 @@ import {generateConnectorOAuthState,saveConnectorOAuthState,} from '@/server/services/connector/stateStore';-import { syncConnectorToolsById } from '@/server/services/connector/sync';+import {+ pruneMissingAutoConnectorTools,+ syncConnectorToolsById,+} from '@/server/services/connector/sync';import {resolveConnectorAuthorizerId,resolveUserDisplayMap,@@ -56,6 +63,7 @@ import {} from '@/server/utils/connectorAttribution';import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';+import { withRequestConnectorCallers } from './_helpers/connectorCallContext';import {assertConnectorCredentialsManageable,assertConnectorMaintainable,@@ -63,6 +71,10 @@ import {getConnectorMemberManage,isWorkspaceConnectorAdmin,} from './_helpers/connectorManagePolicy';+import {+ resolveConnectorToolPermission,+ resolveDefaultPermission,+} from './_helpers/connectorToolPermission';import { upsertConnectorEntry } from './_helpers/upsertConnectorEntry';const connectorProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {@@ -108,6 +120,18 @@ const connectorCredentialsInputSchema = z.discriminatedUnion('type', [z.object({ headers: z.record(z.string(), z.string()), type: z.literal('header') }),]);+const mcpConnectionTypeSchema = z.enum([+ ConnectorMcpConnectionType.http,+ ConnectorMcpConnectionType.stdio,+ ConnectorMcpConnectionType.cloud,+]);+const mcpServerUrlSchema = z.string().url();+const mcpStdioConfigSchema = z.object({+ args: z.array(z.string()).optional(),+ command: z.string(),+ env: z.record(z.string(), z.string()).optional(),+});+const createConnectorSchema = z.object({/*** Bind this connector to a specific agent (Agent > Workspace/Personal). When@@ -119,21 +143,9 @@ const createConnectorSchema = z.object({credentials: connectorCredentialsInputSchema.optional(),identifier: z.string().min(1).max(255),isEnabled: z.boolean().optional().default(true),- mcpConnectionType: z- .enum([- ConnectorMcpConnectionType.http,- ConnectorMcpConnectionType.stdio,- ConnectorMcpConnectionType.cloud,- ])- .optional(),- mcpServerUrl: z.string().url().optional(),- mcpStdioConfig: z- .object({- args: z.array(z.string()).optional(),- command: z.string(),- env: z.record(z.string(), z.string()).optional(),- })- .optional(),+ mcpConnectionType: mcpConnectionTypeSchema.optional(),+ mcpServerUrl: mcpServerUrlSchema.optional(),+ mcpStdioConfig: mcpStdioConfigSchema.optional(),metadata: z.record(z.string(), z.unknown()).optional(),name: z.string().min(1).max(255),oidcConfig: oidcConfigSchema.optional(),@@ -703,8 +715,23 @@ export const connectorRouter = router({// agent scope must go through bindAgent/unbindAgent (agent edit-rights// + uniqueness guards), not the generic update patch..omit({ agentId: true, identifier: true, sourceType: true })- // Allow `null` here so an edit can clear credentials (switch to no-auth).- .extend({ credentials: connectorCredentialsInputSchema.nullish() }),+ // Allow `null` here so an edit can clear credentials (switch to no-auth),+ // drop an OAuth client (undoing a failed switch to OAuth), or put back+ // an endpoint-less row (undoing a failed install over a legacy plugin's+ // tool projection).+ .extend({+ credentials: connectorCredentialsInputSchema.nullish(),+ mcpConnectionType: mcpConnectionTypeSchema.nullish(),+ mcpServerUrl: mcpServerUrlSchema.nullish(),+ mcpStdioConfig: mcpStdioConfigSchema.nullish(),+ oidcConfig: oidcConfigSchema.nullish(),+ // `create` re-sources the row it upserts, so undoing a failed custom+ // install over a legacy marketplace projection puts its source back.+ // Only between the two install sources `create` moves a row across.+ sourceType: z+ .enum([ConnectorSourceType.custom, ConnectorSourceType.marketplace])+ .optional(),+ }),}),).mutation(async ({ input, ctx }) => {@@ -724,6 +751,10 @@ export const connectorRouter = router({await ctx.connectorModel.update(input.id, {...patch,...(patch.metadata === undefined ? {} : { metadata }),+ // A new OAuth client needs a new authorization: the row stays+ // disconnected until the callback connects it, so a client can tell+ // a successful callback from a canceled one+ ...(patch.oidcConfig ? { status: ConnectorStatus.disconnected } : {}),// undefined → leave untouched; null → clear; object → encrypt the JSON string.// When credentials are cleared, also drop the cached expiry timestamp so// token-refresh logic doesn't act on a stale value for the new server.@@ -795,7 +826,13 @@ export const connectorRouter = router({* user permission settings are preserved.*/syncTools: connectorWriteProcedure- .input(z.object({ id: z.string().uuid() }))+ .input(+ z.object({+ id: z.string().uuid(),+ /** An install: `auto` tools the server no longer lists are dropped. */+ pruneMissingAutoTools: z.boolean().optional(),+ }),+ ).mutation(async ({ input, ctx }) => {const target = await ctx.connectorModel.findById(input.id);if (!target) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });@@ -803,7 +840,9 @@ export const connectorRouter = router({// a maintenance operation, gated like delete/reset.await assertConnectorMaintainable(ctx, target);try {- return await syncConnectorToolsById(input.id, ctx);+ return await syncConnectorToolsById(input.id, ctx, {+ pruneMissingAutoTools: input.pruneMissingAutoTools,+ });} catch (err: any) {// Keep actionable rejections and their structured reason for the client.if (err instanceof TRPCError) throw err;@@ -832,11 +871,13 @@ export const connectorRouter = router({/** With `fromApp`: the server the view came from (`getMcpServerFingerprint`). */server: z.string().optional(),toolName: z.string().min(1),+ /** The conversation the call runs in, reported as the call's session. */+ topicId: z.string().optional(),}),).mutation(async ({ input, ctx }) => {try {- return await callConnectorToolById(input, ctx);+ return await callConnectorToolById(input, withRequestConnectorCallers(ctx));} catch (err: any) {if (err instanceof ConnectorToolCallError) {throw new TRPCError({ cause: err, code: err.code, message: err.message });@@ -980,12 +1021,22 @@ export const connectorRouter = router({tools: z.array(z.object({description: z.string().optional(),+ /**+ * A manifest tool's `humanIntervention` (cloud marketplace installs):+ * `required` / `always`, or rules or a dynamic config that can ask+ * for either, make a newly synced tool need approval. One that can+ * ask for `always` keeps it on every sync, since no approval mode+ * waives it.+ */+ humanIntervention: z.unknown().optional(),inputSchema: z.record(z.string(), z.unknown()).optional(),toolName: z.string(),/** The MCP tool's `_meta.ui.visibility`, when it declares one. */visibility: z.array(z.string()).optional(),}),),+ /** An install: `auto` tools the client no longer lists are dropped. */+ pruneMissingAutoTools: z.boolean().optional(),}),).mutation(async ({ input, ctx }) => {@@ -996,13 +1047,27 @@ export const connectorRouter = router({const syncInputs = input.tools.map((t) => ({crudType: inferCrudType(t.toolName),+ // Applies to new tools only: a synced tool keeps the permission it has+ defaultPermission: resolveConnectorToolPermission(t.humanIntervention),description: t.description,inputSchema: t.inputSchema,- metadata: buildMcpToolMetadata(t.visibility),+ // Refreshed on every sync, unlike the permission: an `always` the+ // manifest asks for stays mandatory whatever the permission is+ metadata: withMandatoryApprovalMark(+ buildMcpToolMetadata(t.visibility),+ t.humanIntervention,+ ),toolName: t.toolName,}));await ctx.connectorToolModel.upsertMany(input.id, syncInputs);+ if (input.pruneMissingAutoTools) {+ await pruneMissingAutoConnectorTools(+ ctx.connectorToolModel,+ input.id,+ syncInputs.map((tool) => tool.toolName),+ );+ }await ctx.connectorModel.updateStatus(input.id, ConnectorStatus.connected);return { toolCount: syncInputs.length };}),@@ -1085,6 +1150,15 @@ export const connectorRouter = router({return { connectorId: null, toolCount: 0 };}+ // A connector installed for this identifier (an endpoint plus the tools+ // it synced from its own server) supersedes the plugin row, whose+ // manifest a reinstall leaves as it was. Projecting that manifest would+ // put the old tools and display fields back over the synced ones.+ const [installed] = await ctx.connectorModel.queryByIdentifiers([input.identifier]);+ if (installed && hasCallableMcpEndpoint(installed)) {+ return { connectorId: installed.id, toolCount: 0 };+ }+// Legacy plugin rows can outlive a provider's removal from the Composio catalog. Do not// project those rows back into user_connectors when the detail panel performs its sync.if (plugin.customParams?.composio && !getComposioAppByIdentifier(input.identifier)) {@@ -1121,13 +1195,3 @@ export const connectorRouter = router({return { connectorId, toolCount: syncInputs.length };}),});--// ── Private helpers ───────────────────────────────────────────────────────────--/** Map builtin manifest humanIntervention → default ConnectorToolPermission */-function resolveDefaultPermission(humanIntervention: unknown): ConnectorToolPermission {- if (humanIntervention === 'required' || humanIntervention === 'always') {- return ConnectorToolPermission.needs_approval;- }- return ConnectorToolPermission.auto;-}diff --git a/apps/server/src/routers/lambda/connector.update.test.ts b/apps/server/src/routers/lambda/connector.update.test.tsnew file mode 100644index 00000000000..6f679967451--- /dev/null+++ b/apps/server/src/routers/lambda/connector.update.test.ts@@ -0,0 +1,70 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { connectorRouter } from './connector';++const mocks = vi.hoisted(() => ({+ findById: vi.fn(),+ update: vi.fn(),+}));+vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));+vi.mock('@/database/models/connector', () => ({+ ConnectorModel: vi.fn(function () {+ return mocks;+ }),+}));+vi.mock('@/database/models/connectorTool', () => ({ ConnectorToolModel: vi.fn() }));+vi.mock('@/database/models/plugin', () => ({ PluginModel: vi.fn() }));+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({+ KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },+}));+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {+ const { trpc } = await import('@/libs/trpc/lambda/init');+ return {+ requireWorkspaceRoleWhenScoped: () => trpc.middleware((opts) => opts.next()),+ wsCompatProcedure: trpc.procedure,+ };+});+vi.mock('@/libs/trpc/lambda/middleware', async () => {+ const { trpc } = await import('@/libs/trpc/lambda/init');+ return {+ serverDatabase: trpc.middleware((opts) =>+ opts.next({ ctx: { ...opts.ctx, serverDB: {} as never } }),+ ),+ };+});++const id = '9f1f6f30-0000-4000-8000-000000000001';+const caller = connectorRouter.createCaller({ userId: 'creator' } as never);++beforeEach(() => {+ vi.resetAllMocks();+ mocks.findById.mockResolvedValue({ id, userId: 'creator' });+});++describe('connector.update endpoint fields', () => {+ it('clears the transport, URL and stdio config when the patch sends null', async () => {+ await caller.update({+ id,+ patch: { mcpConnectionType: null, mcpServerUrl: null, mcpStdioConfig: null },+ });++ expect(mocks.update).toHaveBeenCalledWith(+ id,+ expect.objectContaining({+ mcpConnectionType: null,+ mcpServerUrl: null,+ mcpStdioConfig: null,+ }),+ );+ });++ it('leaves the endpoint untouched when the patch omits it', async () => {+ await caller.update({ id, patch: { name: 'Renamed' } });++ const patch = mocks.update.mock.calls[0][1];+ expect(patch).toMatchObject({ name: 'Renamed' });+ for (const field of ['mcpConnectionType', 'mcpServerUrl', 'mcpStdioConfig'])+ expect(patch).not.toHaveProperty(field);+ });+});diff --git a/apps/server/src/routers/lambda/plugin.ts b/apps/server/src/routers/lambda/plugin.tsindex 9efd7c44d2e..606dc760298 100644--- a/apps/server/src/routers/lambda/plugin.ts+++ b/apps/server/src/routers/lambda/plugin.ts@@ -9,6 +9,7 @@ import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';+import { recordLegacyPluginWrite } from './_helpers/legacyPluginWriteMetrics';const pluginProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;@@ -19,7 +20,15 @@ const pluginProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =});});+/**+ * Legacy `user_installed_plugins` rows. Current clients install MCP servers as+ * connectors (`connector.create`) and only read, update and remove rows here.+ */export const pluginRouter = router({+ /**+ * @deprecated Kept unchanged for released clients that still install MCPs as+ * plugin rows. Remove once `legacy_plugin_write_calls_total` is close to zero.+ */createOrInstallPlugin: pluginProcedure.use(withScopedPermission('agent:update')).input(@@ -32,6 +41,8 @@ export const pluginRouter = router({}),).mutation(async ({ input, ctx }) => {+ recordLegacyPluginWrite('createOrInstallPlugin', input.type, ctx.clientMetadata);+const result = await ctx.pluginModel.findById(input.identifier);// if not exist, we should create the plugin@@ -53,6 +64,10 @@ export const pluginRouter = router({await ctx.pluginModel.update(input.identifier, { manifest: input.manifest });}),+ /**+ * @deprecated Kept unchanged for released clients that still add custom MCPs+ * as plugin rows. Remove once `legacy_plugin_write_calls_total` is close to zero.+ */createPlugin: pluginProcedure.use(withScopedPermission('agent:update')).input(@@ -64,6 +79,8 @@ export const pluginRouter = router({}),).mutation(async ({ input, ctx }) => {+ recordLegacyPluginWrite('createPlugin', input.type, ctx.clientMetadata);+const data = await ctx.pluginModel.create({customParams: input.customParams,identifier: input.identifier,diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.tsindex f31150c3894..789037126f6 100644--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts@@ -69,13 +69,17 @@ const connectorTools = [interface RunOptions {agentId?: string;+ /** Override the connector's transport (`http` by default). */+ connection?: { mcpConnectionType: string; mcpServerUrl: string | null };installed?: boolean;+ metadata?: Record<string, unknown>;/** The agent's own `plugins` config — i.e. what the user pinned. */plugins?: string[];/** This turn's @-mention picks. */selectedToolIds?: string[];shareGate?: unknown;sourceType?: 'custom' | 'marketplace';+ status?: string;}const connectorModel = {@@ -86,9 +90,11 @@ const connectorModel = {const run = (options: RunOptions = {}) => {const connector = {...customConnector,+ ...options.connection,+ ...(options.metadata && { metadata: options.metadata }),agentId: options.agentId ?? null,sourceType: options.sourceType ?? 'custom',- status: 'connected',+ status: options.status ?? 'connected',};connectorModel.resolveAll.mockReset().mockResolvedValue([connector]);connectorModel.resolveByIdentifiers@@ -209,6 +215,74 @@ describe('discoverTools — unpinned custom MCP connectors', () => {expect(activated.enabledToolIds).toContain(YINGMI);});+ it.each([+ { label: 'http', connection: undefined },+ { label: 'cloud', connection: { mcpConnectionType: 'cloud', mcpServerUrl: null } },+ ])('treats a connector-only marketplace install as installed: $label', async ({ connection }) => {+ // No user_installed_plugins row: the connector's own mark is the install+ const result = await run({+ connection,+ installed: false,+ metadata: { marketplaceInstalled: true },+ sourceType: 'marketplace',+ });+ expect(result.toolManifestMap[YINGMI]).toBeDefined();+ expect((result.toolManifestMap[YINGMI] as any).mcpParams.type).toBe(+ connection?.mcpConnectionType ?? 'http',+ );+ const activated = result.toolsEngine!.generateToolsDetailed({+ context: { isExplicitActivation: true },+ model: 'test-model',+ provider: 'test-provider',+ skipDefaultTools: true,+ toolIds: [YINGMI],+ });+ expect(activated.enabledToolIds).toContain(YINGMI);+ });++ // A reinstall over a plugin row rewrites the endpoint and resets the row to+ // disconnected until its tools sync: the old tools must not run against it+ it('rejects a pending reinstall over a plugin row until its connector is connected', async () => {+ const result = await run({+ installed: true,+ sourceType: 'marketplace',+ status: 'disconnected',+ });+ expect(result.toolManifestMap[YINGMI]).toBeUndefined();+ });++ it('keeps an endpoint-less plugin projection on its plugin row whatever its status', async () => {+ const result = await run({+ connection: { mcpConnectionType: null as never, mcpServerUrl: null },+ installed: true,+ sourceType: 'marketplace',+ status: 'disconnected',+ });+ // Not routed as an MCP connector, but not filtered out of discovery either+ expect(result.toolSourceMap[YINGMI]).not.toBe('mcp');+ });++ // An OAuth re-authorization leaves a finished install disconnected until its+ // callback connects it: the client already hides it, so must a server run+ it('rejects a finished install while it is not connected', async () => {+ const result = await run({+ installed: false,+ metadata: { marketplaceInstalled: true },+ sourceType: 'marketplace',+ status: 'disconnected',+ });+ expect(result.toolManifestMap[YINGMI]).toBeUndefined();+ });++ it('rejects an unfinished cloud marketplace install that has no plugin row', async () => {+ const result = await run({+ connection: { mcpConnectionType: 'cloud', mcpServerUrl: null },+ installed: false,+ sourceType: 'marketplace',+ });+ expect(result.toolManifestMap[YINGMI]).toBeUndefined();+ });+it('keeps an unmentioned, unpinned connector discoverable without enabling it', async () => {// The follow-up turn after an @-mention: no mention, nothing pinned. The// activator used to answer "Not found: yingmi" here.diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.tsindex 603317ffc89..165185ef208 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts@@ -1,4 +1,5 @@import type { DeviceAttachment } from '@lobechat/builtin-tool-remote-device';+import { hasCallableMcpEndpoint, isMarketplaceInstallRunnable } from '@lobechat/const';import type { LobeToolManifest } from '@lobechat/context-engine';import { FILE_PREVIEW_CHARS, isOversizedFileContent } from '@lobechat/prompts';import type { FrozenCredentialFacts } from '@lobechat/types';@@ -116,17 +117,13 @@ const refreshConnectorTokens = async ();};-/** Base marketplace OAuth rows require installation; agent-owned copies are independent. */+/** Drop unfinished marketplace installs (see `isMarketplaceInstallRunnable`). */const filterInstalledMarketplaceConnectors = (connectors: DecryptedConnector[],installedIds: Set<string>,) =>- connectors.filter(- (connector) =>- !!connector.agentId ||- connector.sourceType !== 'marketplace' ||- !connector.mcpServerUrl ||- installedIds.has(connector.identifier),+ connectors.filter((connector) =>+ isMarketplaceInstallRunnable(connector, installedIds.has(connector.identifier)),);const readConnectors = async (@@ -161,14 +158,14 @@ const readConnectors = async (// must not make an unfinished marketplace install callable by a server run.const connectors = filterInstalledMarketplaceConnectors(resolved, installedIds);- // Only connectors WITH a real MCP endpoint (mcpServerUrl or stdio) can replace plugins in the+ // Only connectors WITH a real MCP endpoint (mcpServerUrl, stdio or cloud) can replace plugins in the// manifest. Connectors WITHOUT an endpoint (e.g. Lobehub/Composio OAuth skills synced via// syncToolsFromClient) must continue using their original plugin executor path — otherwise// after humanIntervention approval the runtime tries to call mcpServerUrl='' and returns empty.const connectorsMcp = await refreshConnectorTokens(deps,connectorGateKeeper,- connectors.filter((c) => c.mcpServerUrl || c.mcpConnectionType === 'stdio'),+ connectors.filter(hasCallableMcpEndpoint),onRefreshTimeout,);@@ -243,7 +240,7 @@ const readDiscoverableConnectors = async (resolved = await deps.connectorModel.resolveAll(ctx.resolvedAgentId, gateKeeper);}const connectorsMcp = filterInstalledMarketplaceConnectors(resolved, installedIds).filter(- (c) => !candidates.has(c.identifier) && (c.mcpServerUrl || c.mcpConnectionType === 'stdio'),+ (c) => !candidates.has(c.identifier) && hasCallableMcpEndpoint(c),);if (connectorsMcp.length === 0) return none;diff --git a/apps/server/src/services/connector/exec.test.ts b/apps/server/src/services/connector/exec.test.tsindex 4cdbb45c093..49a2503a398 100644--- a/apps/server/src/services/connector/exec.test.ts+++ b/apps/server/src/services/connector/exec.test.ts@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { ConnectorToolPermission } from '@/database/schemas';import { deviceGateway } from '@/server/services/deviceGateway';import { mcpService } from '@/server/services/mcp';+import type * as ContentProcessorModule from '@/server/services/mcp/contentProcessor';import { callConnectorToolById, readConnectorUiResourceById } from './exec';import { scheduleStaleConnectorToolsRefresh } from './refresh';@@ -13,6 +14,17 @@ vi.mock('@/server/services/mcp', () => ({mcpService: { callTool: vi.fn(), readUiResource: vi.fn() },}));vi.mock('@/server/services/deviceGateway', () => ({ deviceGateway: { isConfigured: false } }));+const callCloudMcpEndpoint = vi.hoisted(() => vi.fn());+vi.mock('@/server/services/discover', () => ({+ DiscoverService: vi.fn(function DiscoverService() {+ return { callCloudMcpEndpoint };+ }),+}));+const processContentBlocks = vi.hoisted(() => vi.fn());+vi.mock('@/server/services/mcp/contentProcessor', async (importOriginal) => ({+ ...(await importOriginal<typeof ContentProcessorModule>()),+ processContentBlocks,+}));const mcpAppsEnabled = vi.hoisted(() => vi.fn().mockResolvedValue(false));vi.mock('@/server/services/mcp/featureGate', () => ({ isMcpAppsEnabled: mcpAppsEnabled }));vi.mock('./tokens', () => ({ ensureFreshConnectorToken: vi.fn(async (c) => c) }));@@ -73,6 +85,50 @@ describe('callConnectorToolById', () => {expect(mcpService.callTool).not.toHaveBeenCalled();});+ describe('an unfinished marketplace install', () => {+ // A reinstall over a plugin row rewrites the endpoint and resets the row to+ // disconnected until its tools sync: the old tool rows must not run on it+ const pending = {+ ...connector,+ metadata: {},+ sourceType: 'marketplace',+ status: 'disconnected',+ };+ const call = (row: any, pluginRow?: unknown) =>+ callConnectorToolById(+ { identifier: 'my-conn', toolName: 'do_thing' },+ {+ ...makeCtx([row], [tool()]),+ pluginModel: { findById: vi.fn().mockResolvedValue(pluginRow) },+ },+ );++ it('refuses a pending reinstall over a plugin row', async () => {+ await expect(call(pending, { identifier: 'my-conn' })).rejects.toHaveProperty(+ 'code',+ 'FORBIDDEN',+ );+ expect(mcpService.callTool).not.toHaveBeenCalled();+ });++ it('refuses a connected row with neither its install mark nor a plugin row', async () => {+ await expect(call({ ...pending, status: 'connected' })).rejects.toHaveProperty(+ 'code',+ 'FORBIDDEN',+ );+ expect(mcpService.callTool).not.toHaveBeenCalled();+ });++ it('runs a connected row once a plugin row or its install mark finishes it', async () => {+ vi.mocked(mcpService.callTool).mockResolvedValue({ ok: true } as any);++ await call({ ...pending, status: 'connected' }, { identifier: 'my-conn' });+ await call({ ...pending, metadata: { marketplaceInstalled: true }, status: 'connected' });++ expect(mcpService.callTool).toHaveBeenCalledTimes(2);+ });+ });+it('rejects an unknown tool name not in the synced list', async () => {const ctx = makeCtx([connector], [tool({ toolName: 'other' })]);await expect(@@ -129,6 +185,56 @@ describe('callConnectorToolById', () => {);});+ // Image / audio blocks become the caller's files, as `tools.mcp.callTool` stores them+ it("stores a result's media blocks with the caller's file service", async () => {+ vi.mocked(mcpService.callTool).mockResolvedValue({ success: true });+ const fileService = { uploadMedia: vi.fn() };+ const blocks = [{ data: 'aGk=', mimeType: 'image/png', type: 'image' }];+ processContentBlocks.mockResolvedValue([{ text: 'stored', type: 'text' }]);++ await callConnectorToolById(+ { identifier: 'my-conn', toolName: 'do_thing' },+ { ...makeCtx([connector], [tool()]), resolveFileService: () => fileService },+ );++ const { processContentBlocks: processor } = vi.mocked(mcpService.callTool).mock.calls[0][0];+ expect(processor).toBeTypeOf('function');+ await expect(processor!(blocks as any)).resolves.toEqual([{ text: 'stored', type: 'text' }]);+ expect(processContentBlocks).toHaveBeenCalledWith(blocks, fileService);+ });++ it('formats media blocks as returned without file storage, or for a view', async () => {+ vi.mocked(mcpService.callTool).mockResolvedValue({ success: true });+ const resolveFileService = vi.fn(() => ({ uploadMedia: vi.fn() }) as any);++ await callConnectorToolById(+ { identifier: 'my-conn', toolName: 'do_thing' },+ { ...makeCtx([connector], [tool()]), resolveFileService: () => undefined },+ );+ const server = await getMcpServerFingerprint({ type: 'http', url: connector.mcpServerUrl! });+ await callConnectorToolById(+ { fromApp: true, identifier: 'my-conn', server, toolName: 'do_thing' },+ { ...makeCtx([connector], [tool()]), resolveFileService },+ );++ expect(mcpService.callTool).toHaveBeenCalledTimes(2);+ for (const [call] of vi.mocked(mcpService.callTool).mock.calls) {+ expect(call.processContentBlocks).toBeUndefined();+ }+ expect(resolveFileService).not.toHaveBeenCalled();+ });++ // Built only for an HTTP call: storage that cannot be built must not fail another kind+ it('never reads file storage for a call that does not reach an HTTP server', async () => {+ const resolveFileService = vi.fn();+ const ctx = { ...makeCtx([connector], [tool()]), resolveFileService };++ await expect(+ callConnectorToolById({ identifier: 'my-conn', toolName: 'missing' }, ctx),+ ).rejects.toHaveProperty('code', 'BAD_REQUEST');+ expect(resolveFileService).not.toHaveBeenCalled();+ });+it.each([true, false])('passes the caller mcp_apps flag (%s) through', async (enabled) => {mcpAppsEnabled.mockResolvedValueOnce(enabled);vi.mocked(mcpService.callTool).mockResolvedValue({ success: true });@@ -277,6 +383,77 @@ describe('callConnectorToolById', () => {});});+ describe('cloud connectors', () => {+ const cloud = {+ ...connector,+ credentials: null,+ mcpConnectionType: 'cloud',+ mcpServerUrl: null,+ };+ const fileService = { name: 'fileService' };+ const cloudCtx = (caller: unknown) => ({+ ...makeCtx([cloud], [tool()]),+ resolveCloudMcpCaller: vi.fn().mockResolvedValue(caller),+ userId: 'user-1',+ });++ it('runs the tool through the market cloud gateway with the Market token', async () => {+ callCloudMcpEndpoint.mockResolvedValue({ content: [{ text: 'found', type: 'text' }] });+ processContentBlocks.mockImplementation(async (blocks) => blocks);+ const ctx = cloudCtx({+ discoverService: { callCloudMcpEndpoint },+ fileService,+ userAccessToken: 'market-token',+ });++ const res = await callConnectorToolById(+ { args: '{"q":"x"}', identifier: 'my-conn', toolName: 'do_thing' },+ ctx,+ );++ expect(callCloudMcpEndpoint).toHaveBeenCalledWith({+ apiParams: { q: 'x' },+ identifier: 'my-conn',+ toolName: 'do_thing',+ userAccessToken: 'market-token',+ });+ expect(res).toMatchObject({ content: 'found', success: true });+ expect(mcpService.callTool).not.toHaveBeenCalled();+ expect(ensureFreshConnectorToken).not.toHaveBeenCalled();+ });++ it('stores media blocks before formatting the result', async () => {+ const image = { data: 'iVBORw0KGgo', mimeType: 'image/png', type: 'image' };+ const stored = {+ data: 'https://files.example.com/a.png',+ mimeType: 'image/png',+ type: 'image',+ };+ callCloudMcpEndpoint.mockResolvedValue({ content: [image] });+ processContentBlocks.mockResolvedValue([stored]);+ const ctx = cloudCtx({ discoverService: { callCloudMcpEndpoint }, fileService });++ const res = (await callConnectorToolById(+ { identifier: 'my-conn', toolName: 'do_thing' },+ ctx,+ )) as { content: string; state: { content: unknown[] } };++ expect(processContentBlocks).toHaveBeenCalledWith([image], fileService);+ expect(res.content).toBe('');+ expect(res.content).not.toContain('iVBOR');+ expect(res.state.content).toEqual([stored]);+ });++ it('refuses the call when there is no Market credential to run it as', async () => {+ const ctx = cloudCtx(undefined);++ await expect(+ callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(callCloudMcpEndpoint).not.toHaveBeenCalled();+ });+ });+it('still returns the tool result when the background refresh scheduler throws', async () => {// The refresh is a pure optimization; a failure in it must never break the// tool call the user actually asked for.@@ -344,7 +521,7 @@ describe('readConnectorUiResourceById', () => {);});- it('rejects missing, disabled and stdio connectors', async () => {+ it('rejects missing, disabled, stdio and cloud connectors', async () => {await expect(readConnectorUiResourceById({ identifier: 'x', server: SERVER, uri: 'ui://app' },@@ -363,6 +540,12 @@ describe('readConnectorUiResourceById', () => {makeCtx([{ ...connector, mcpConnectionType: 'stdio' }], []),),).rejects.toHaveProperty('code', 'BAD_REQUEST');+ await expect(+ readConnectorUiResourceById(+ { identifier: 'my-conn', server: SERVER, uri: 'ui://app' },+ makeCtx([{ ...connector, mcpConnectionType: 'cloud', mcpServerUrl: null }], []),+ ),+ ).rejects.toHaveProperty('code', 'BAD_REQUEST');expect(mcpService.readUiResource).not.toHaveBeenCalled();});@@ -442,3 +625,116 @@ describe('agent-scoped connectors of an agent the caller cannot see', () => {expect(mcpService.readUiResource).not.toHaveBeenCalled();});});++// Marketplace installs used to run as plugins, whose calls the Market was told+// about (`tools.mcp.callTool`, `market.callCloudMcpEndpoint`)+describe('Market call reports', () => {+ const marketplace = {+ ...connector,+ metadata: { marketplaceInstalled: true, version: '1.2.0' },+ sourceType: 'marketplace',+ status: 'connected',+ };+ const reportCtx = (row: any, report = vi.fn()) => ({+ ...makeCtx([row], [tool()]),+ resolveToolCallReporter: vi.fn().mockResolvedValue(report),+ });++ it("reports a marketplace server's call with its session and installed version", async () => {+ vi.mocked(mcpService.callTool).mockResolvedValue({ content: 'done' } as any);+ const report = vi.fn();++ await callConnectorToolById(+ { args: '{"q":1}', identifier: 'my-conn', toolName: 'do_thing', topicId: 'tpc_1' },+ reportCtx(marketplace, report),+ );++ expect(report).toHaveBeenCalledTimes(1);+ expect(report).toHaveBeenCalledWith(+ expect.objectContaining({+ identifier: 'my-conn',+ mcpType: 'http',+ meta: { sessionId: 'tpc_1', version: '1.2.0' },+ requestPayload: '{"q":1}',+ result: { content: 'done' },+ startTime: expect.any(Number),+ success: true,+ toolName: 'do_thing',+ }),+ );+ });++ it('reports a failed call as failed and still throws its error', async () => {+ const failure = new Error('upstream 500');+ vi.mocked(mcpService.callTool).mockRejectedValue(failure);+ const report = vi.fn();++ await expect(+ callConnectorToolById(+ { identifier: 'my-conn', toolName: 'do_thing' },+ reportCtx(marketplace, report),+ ),+ ).rejects.toBe(failure);++ expect(report).toHaveBeenCalledWith(+ expect.objectContaining({+ errorCode: 'CALL_FAILED',+ errorMessage: 'upstream 500',+ success: false,+ }),+ );+ });++ it('reports a market-hosted (cloud) server as cloud', async () => {+ callCloudMcpEndpoint.mockResolvedValue({ content: [{ text: 'found', type: 'text' }] });+ const report = vi.fn();+ const ctx = {+ ...reportCtx(+ { ...marketplace, credentials: null, mcpConnectionType: 'cloud', mcpServerUrl: null },+ report,+ ),+ resolveCloudMcpCaller: vi+ .fn()+ .mockResolvedValue({ discoverService: { callCloudMcpEndpoint } }),+ };++ await callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx);++ expect(report).toHaveBeenCalledWith(+ expect.objectContaining({ mcpType: 'cloud', success: true }),+ );+ });++ it('does not report custom servers, or rows without an endpoint of their own', async () => {+ vi.mocked(mcpService.callTool).mockResolvedValue({ content: 'done' } as any);+ const custom = reportCtx({ ...connector, sourceType: 'custom' });+ // A Composio connection is a marketplace row its own executor runs+ const composio = reportCtx({+ ...marketplace,+ mcpConnectionType: null,+ mcpServerUrl: null,+ metadata: { composio: { toolkit: 'gmail' } },+ });++ await callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, custom);+ // This route has no endpoint to call it on+ await expect(+ callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, composio),+ ).rejects.toThrow();++ expect(custom.resolveToolCallReporter).not.toHaveBeenCalled();+ expect(composio.resolveToolCallReporter).not.toHaveBeenCalled();+ });++ it('still runs the call when no reporter can be resolved', async () => {+ vi.mocked(mcpService.callTool).mockResolvedValue({ content: 'done' } as any);+ const ctx = {+ ...makeCtx([marketplace], [tool()]),+ resolveToolCallReporter: vi.fn().mockRejectedValue(new Error('db down')),+ };++ await expect(+ callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx),+ ).resolves.toEqual({ content: 'done' });+ });+});diff --git a/apps/server/src/services/connector/exec.ts b/apps/server/src/services/connector/exec.tsindex 22429e6ac96..9a9df5a8bd5 100644--- a/apps/server/src/services/connector/exec.ts+++ b/apps/server/src/services/connector/exec.ts@@ -1,11 +1,16 @@+import { hasCallableMcpEndpoint, isMarketplaceInstallRunnable } from '@lobechat/const';import { getMcpServerFingerprint, isSyncedMcpToolVisibleTo } from '@lobechat/const/mcpApp';import { isLocalOrPrivateUrl } from '@lobechat/utils';import type { AgentModel } from '@/database/models/agent';import type { DecryptedConnector } from '@/database/models/connector';+import type { PluginModel } from '@/database/models/plugin';import { ConnectorMcpConnectionType, ConnectorToolPermission } from '@/database/schemas';import { deviceGateway } from '@/server/services/deviceGateway';+import type { FileService } from '@/server/services/file';import { mcpService } from '@/server/services/mcp';+import { callCloudMcpTool, type CloudMcpCaller } from '@/server/services/mcp/cloudTool';+import { processContentBlocks } from '@/server/services/mcp/contentProcessor';import { isMcpAppsEnabled } from '@/server/services/mcp/featureGate';import { buildLastSyncedAtMap, scheduleStaleConnectorToolsRefresh } from './refresh';@@ -25,9 +30,49 @@ export class ConnectorToolCallError extends Error {}}+/** A finished connector tool call, as the Market's call report reads it. */+export interface ConnectorToolCallReport {+ errorCode?: string;+ errorMessage?: string;+ identifier: string;+ /** The connector's transport: `http` or `cloud`. */+ mcpType: string;+ meta: { sessionId?: string; version?: string };+ requestPayload: unknown;+ result?: unknown;+ startTime: number;+ success: boolean;+ toolName: string;+}++export type ConnectorToolCallReporter = (report: ConnectorToolCallReport) => void;+export interface ConnectorExecContext extends ConnectorToolSyncContext {/** Visibility-aware: decides whether the caller may act as the given agent. */agentModel: Pick<AgentModel, 'existsById'>;+ /**+ * The caller's legacy plugin rows, which stand in for an unmarked marketplace+ * install made before installs used connectors. None: no such row counts.+ */+ pluginModel?: Pick<PluginModel, 'findById'>;+ /**+ * Who a market-hosted (`cloud`) connector's tool runs as, resolved only for+ * such a call. `undefined` (or no resolver): no Market credential to run as.+ */+ resolveCloudMcpCaller?: () => Promise<CloudMcpCaller | undefined>;+ /**+ * The caller's file storage, read only for an HTTP connector call: a result's+ * image / audio blocks are stored as files the text result links to, as+ * `tools.mcp.callTool` does. `undefined` (or no resolver): the blocks are+ * formatted as returned (base64 data).+ */+ resolveFileService?: () => FileService | undefined;+ /**+ * Reports a marketplace MCP server's call to the Market, resolved only for+ * such a call. `undefined` (or no resolver): nothing is reported, e.g. the+ * user turned telemetry off.+ */+ resolveToolCallReporter?: () => Promise<ConnectorToolCallReporter | undefined>;/** `userId` decides the caller's `mcp_apps` flag. */userId?: string | null;}@@ -52,6 +97,22 @@ const findConnector = async (return ctx.connectorModel.resolveByIdentifiers([params.identifier], params.agentId);};+/**+ * An unfinished marketplace install (an interrupted reinstall, an OAuth+ * callback that connected after a cancel) must not run: its tool rows may not+ * match its endpoint. The same rule as tool discovery's.+ */+const assertInstallFinished = async (connector: DecryptedConnector, ctx: ConnectorExecContext) => {+ if (isMarketplaceInstallRunnable(connector, false)) return;+ const pluginRow = await ctx.pluginModel?.findById(connector.identifier);+ if (isMarketplaceInstallRunnable(connector, !!pluginRow)) return;++ throw new ConnectorToolCallError(+ 'FORBIDDEN',+ `Connector '${connector.name}' has not finished installing. Install it again to use its tools.`,+ );+};+/*** Execute a single connector tool, enforcing the full permission model:* - the connector must exist and be enabled,@@ -90,6 +151,8 @@ export const callConnectorToolById = async (/** With `fromApp`: the server the view came from; its calls reach no other. */server?: string;toolName: string;+ /** The conversation the call runs in, reported as the call's session. */+ topicId?: string;},ctx: ConnectorExecContext,): Promise<unknown> => {@@ -100,6 +163,7 @@ export const callConnectorToolById = async (if (!connector.isEnabled) {throw new ConnectorToolCallError('FORBIDDEN', 'Connector is disabled');}+ await assertInstallFinished(connector, ctx);// A view open since the connector was pointed elsewhere must not drive the new serverif (params.fromApp && !(await reachesServer(connector, params.server))) {throw new ConnectorToolCallError(@@ -172,13 +236,88 @@ export const callConnectorToolById = async ();}+ const report = await resolveReporter(connector, ctx);+ if (!report) return runConnectorTool(connector, params, ctx);++ const startTime = Date.now();+ let failure: Error | undefined;+ let result: unknown;+ try {+ result = await runConnectorTool(connector, params, ctx);+ return result;+ } catch (error) {+ failure = error instanceof Error ? error : new Error(String(error));+ throw error;+ } finally {+ report({+ errorCode: failure ? 'CALL_FAILED' : undefined,+ errorMessage: failure?.message,+ identifier: connector.identifier,+ mcpType: connector.mcpConnectionType ?? ConnectorMcpConnectionType.http,+ meta: { sessionId: params.topicId, version: installedVersion(connector.metadata) },+ requestPayload: params.args,+ result,+ startTime,+ success: !failure,+ toolName: params.toolName,+ });+ }+};++/**+ * The Market reporter for a marketplace MCP server's call, the way its plugin's+ * calls were reported (`tools.mcp.callTool`, `market.callCloudMcpEndpoint`).+ * Rows without an endpoint (Composio, skill projections) run elsewhere. A+ * reporter that can't be resolved never fails the call.+ */+const resolveReporter = async (connector: DecryptedConnector, ctx: ConnectorExecContext) => {+ if (connector.sourceType !== 'marketplace' || !hasCallableMcpEndpoint(connector)) return;+ try {+ return await ctx.resolveToolCallReporter?.();+ } catch {+ return undefined;+ }+};++/** The manifest version a marketplace install recorded. */+const installedVersion = (metadata: unknown): string | undefined => {+ const version = (metadata as { version?: unknown } | null)?.version;+ return typeof version === 'string' ? version : undefined;+};++const runConnectorTool = async (+ connector: DecryptedConnector,+ params: { args?: string; fromApp?: boolean; toolName: string },+ ctx: ConnectorExecContext,+): Promise<unknown> => {+ // A market-hosted stdio server: no session to open, the market's cloud+ // gateway runs the tool by identifier.+ if (connector.mcpConnectionType === ConnectorMcpConnectionType.cloud) {+ const caller = await ctx.resolveCloudMcpCaller?.();+ if (!caller) {+ throw new ConnectorToolCallError(+ 'FORBIDDEN',+ 'User access token not found. Please sign in to Market first.',+ );+ }+ return callCloudMcpTool(+ { args: params.args, identifier: connector.identifier, toolName: params.toolName },+ caller,+ );+ }+const fresh = await ensureFreshConnectorToken(connector, ctx.connectorModel);+ // A view's call gets its blocks back as they are (`mcpService.callTool`)+ const fileService = params.fromApp ? undefined : ctx.resolveFileService?.();return mcpService.callTool({argsStr: params.args ?? '{}',clientParams: buildConnectorMcpParams(fresh),fromApp: params.fromApp,mcpApps: await isMcpAppsEnabled(ctx.userId),+ processContentBlocks: fileService+ ? (blocks) => processContentBlocks(blocks, fileService)+ : undefined,toolName: params.toolName,});};@@ -205,10 +344,14 @@ export const readConnectorUiResourceById = async (if (!connector.isEnabled) {throw new ConnectorToolCallError('FORBIDDEN', 'Connector is disabled');}- if (connector.mcpConnectionType === ConnectorMcpConnectionType.stdio) {+ await assertInstallFinished(connector, ctx);+ if (+ connector.mcpConnectionType === ConnectorMcpConnectionType.stdio ||+ connector.mcpConnectionType === ConnectorMcpConnectionType.cloud+ ) {throw new ConnectorToolCallError('BAD_REQUEST',- 'Interactive views are not supported for stdio connectors yet',+ `Interactive views are not supported for ${connector.mcpConnectionType} connectors yet`,);}// A cloud server can't reach a localhost / LAN endpoint, and resource readsdiff --git a/apps/server/src/services/connector/sync.test.ts b/apps/server/src/services/connector/sync.test.tsindex cafdfeb5c63..b0f1079f1b6 100644--- a/apps/server/src/services/connector/sync.test.ts+++ b/apps/server/src/services/connector/sync.test.ts@@ -228,6 +228,31 @@ describe('syncConnectorToolsById', () => {]);});+ it('drops only the auto tools the server no longer lists when asked to', async () => {+ vi.mocked(mcpService.listRawTools).mockResolvedValue([+ { description: 'Kept', inputSchema: { type: 'object' }, name: 'kept' },+ ]);+ const deleteToolsNotIn = vi.fn();+ const connectorToolModel = {+ deleteToolsNotIn,+ queryByConnector: async () => [+ { permission: 'auto', toolName: 'kept' },+ { permission: 'auto', toolName: 'gone' },+ { permission: 'needs_approval', toolName: 'gated' },+ ],+ upsertMany: vi.fn(),+ };+ const connectorModel = { findById: async () => httpConnector(null), updateStatus: vi.fn() };++ await syncConnectorToolsById('c1', { connectorModel, connectorToolModel } as any);+ expect(deleteToolsNotIn).not.toHaveBeenCalled();++ await syncConnectorToolsById('c1', { connectorModel, connectorToolModel } as any, {+ pruneMissingAutoTools: true,+ });+ expect(deleteToolsNotIn).toHaveBeenCalledWith('c1', ['kept', 'gated']);+ });+it.each([true, false])("lists on a session announcing MCP Apps under the user's flag (%s)",async (enabled) => {diff --git a/apps/server/src/services/connector/sync.ts b/apps/server/src/services/connector/sync.tsindex b2addbaa4c4..98c486e5606 100644--- a/apps/server/src/services/connector/sync.ts+++ b/apps/server/src/services/connector/sync.ts@@ -3,7 +3,11 @@ import { buildMcpToolMetadata, getMcpToolVisibility } from '@lobechat/const/mcpAimport type { ConnectorModel, DecryptedConnector } from '@/database/models/connector';import type { ConnectorToolModel } from '@/database/models/connectorTool';import type { ConnectorCredentials } from '@/database/schemas';-import { ConnectorMcpConnectionType, ConnectorStatus } from '@/database/schemas';+import {+ ConnectorMcpConnectionType,+ ConnectorStatus,+ ConnectorToolPermission,+} from '@/database/schemas';import type { AuthConfig } from '@/libs/mcp';import { inferCrudType } from '@/libs/mcp/utils';import { mcpService } from '@/server/services/mcp';@@ -90,6 +94,29 @@ export const buildHttpAuthFromCredentials = (}};+export interface ConnectorToolSyncOptions {+ /**+ * Drop the `auto` tools the server no longer lists, so they stop being+ * advertised: eval contracts, and an MCP install or reinstall, whose tool+ * list replaces the stored one as a plugin install replaced its manifest.+ * Approval and disabled rows stay as permission tombstones, so neither a later+ * listing nor the rollback of a failed reinstall can bring them back as `auto`.+ */+ pruneMissingAutoTools?: boolean;+}++/** After a sync: delete the connector's `auto` tools that `listedToolNames` no longer has. */+export const pruneMissingAutoConnectorTools = async (+ connectorToolModel: Pick<ConnectorToolModel, 'deleteToolsNotIn' | 'queryByConnector'>,+ connectorId: string,+ listedToolNames: string[],+): Promise<void> => {+ const tombstones = (await connectorToolModel.queryByConnector(connectorId))+ .filter((tool) => tool.permission !== ConnectorToolPermission.auto)+ .map((tool) => tool.toolName);+ await connectorToolModel.deleteToolsNotIn(connectorId, [...listedToolNames, ...tombstones]);+};+/*** Connect to a connector's MCP server, fetch its tool list, and sync it into* `user_connector_tools`. Refreshes the OAuth token first when needed, and@@ -102,7 +129,7 @@ export const syncConnectorToolsById = async (connectorId: string,/** `userId` decides the `mcp_apps` flag: with it on, view-only tools are listed too. */ctx: ConnectorToolSyncContext & { userId?: string | null },- options: { pruneMissingAutoTools?: boolean } = {},+ options: ConnectorToolSyncOptions = {},): Promise<{ toolCount: number }> => {let connector = await ctx.connectorModel.findById(connectorId);if (!connector) throw new Error('Connector not found');@@ -140,15 +167,11 @@ export const syncConnectorToolsById = async (await ctx.connectorToolModel.upsertMany(connectorId, syncInputs);if (options.pruneMissingAutoTools) {- // Eval contracts exclude vanished auto tools. Retain denied/approval rows as- // permission tombstones so a later upstream listing cannot auto-approve them.- const restricted = (await ctx.connectorToolModel.queryByConnector(connectorId))- .filter((tool) => tool.permission !== 'auto')- .map((tool) => tool.toolName);- await ctx.connectorToolModel.deleteToolsNotIn(connectorId, [- ...syncInputs.map((tool) => tool.toolName),- ...restricted,- ]);+ await pruneMissingAutoConnectorTools(+ ctx.connectorToolModel,+ connectorId,+ syncInputs.map((tool) => tool.toolName),+ );}await ctx.connectorModel.updateStatus(connectorId, ConnectorStatus.connected);diff --git a/apps/server/src/services/mcp/cloudTool.ts b/apps/server/src/services/mcp/cloudTool.tsnew file mode 100644index 00000000000..dd0900196e6--- /dev/null+++ b/apps/server/src/services/mcp/cloudTool.ts@@ -0,0 +1,53 @@+import { safeParseJSON } from '@lobechat/utils';++import type { ToolCallContent } from '@/libs/mcp';++import { DiscoverService } from '../discover';+import type { FileService } from '../file';+import { contentBlocksToString, processContentBlocks } from './contentProcessor';++/** Who a cloud MCP call runs as, and where its media is stored. */+export interface CloudMcpCaller {+ discoverService: DiscoverService;+ /**+ * Stores image / audio blocks as files, so the text result links to them.+ * Without it the blocks are formatted as returned (base64 data).+ */+ fileService?: FileService;+ /** The user's Market token, sent when trusted-client auth is not configured. */+ userAccessToken?: string;+}++/** The agent runtime's caller: the user's trusted-client identity only. */+export const runtimeCloudMcpCaller = (userId?: string | null): CloudMcpCaller => ({+ discoverService: new DiscoverService({ userInfo: userId ? { userId } : undefined }),+});++/**+ * Run a tool of a marketplace MCP the market hosts (a "cloud" endpoint)+ * through the market's cloud gateway, by identifier. Shared by the agent+ * runtime's MCP executor and connector tool calls.+ */+export const callCloudMcpTool = async (+ params: { args?: string; identifier: string; toolName: string },+ caller: CloudMcpCaller,+) => {+ // Returns CloudGatewayResponse: { content: ToolCallContent[], isError?: boolean }+ const cloudResult = await caller.discoverService.callCloudMcpEndpoint({+ apiParams: safeParseJSON(params.args) || {},+ identifier: params.identifier,+ toolName: params.toolName,+ userAccessToken: caller.userAccessToken,+ });+ const rawContent = (cloudResult?.content ?? []) as ToolCallContent[];+ const content =+ cloudResult?.isError || !caller.fileService+ ? rawContent+ : await processContentBlocks(rawContent, caller.fileService);++ return {+ content: contentBlocksToString(content),+ state: { ...cloudResult, content },+ success: !cloudResult?.isError,+ };+};diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.tsindex d8f2f4d4153..3172951f5a2 100644--- a/apps/server/src/services/toolExecution/index.ts+++ b/apps/server/src/services/toolExecution/index.ts@@ -1,17 +1,11 @@import { BRANDING_NAME } from '@lobechat/business-const';import { DEFAULT_TOOL_RESULT_MAX_LENGTH, truncateToolResult } from '@lobechat/prompts/toolResult';import { type ChatToolPayload } from '@lobechat/types';-import { safeParseJSON } from '@lobechat/utils';import { isDeviceOnlyMcpEndpoint } from '@lobechat/utils/mcpEndpoint';import debug from 'debug';import { ConnectorToolPermission } from '@/database/schemas';-import {- type CloudMCPParams,- type HttpMCPClientParams,- type StdioMCPParams,- type ToolCallContent,-} from '@/libs/mcp';+import { type CloudMCPParams, type HttpMCPClientParams, type StdioMCPParams } from '@/libs/mcp';import {buildBlockedToolResponse,getConnectorToolPermission,@@ -20,11 +14,10 @@ import { deviceGateway } from '@/server/services/deviceGateway';import { resolveDeviceClientKind } from '@/server/services/deviceGateway/deviceChannels';import { resolveDeviceDispatchAuthorizationFailure } from '@/server/services/deviceGateway/dispatchAuthorization';import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';-import { contentBlocksToString } from '@/server/services/mcp/contentProcessor';import { isMcpAppsEnabled } from '@/server/services/mcp/featureGate';-import { DiscoverService } from '../discover';import { type MCPService } from '../mcp';+import { callCloudMcpTool, runtimeCloudMcpCaller } from '../mcp/cloudTool';import { type BuiltinToolsExecutor } from './builtin';import { classifyToolError, getToolAccessDeniedError } from './errorClassification';import { buildMcpAuthorizationErrorContent, isMcpAuthorizationError } from './mcpAuthError';@@ -579,35 +572,14 @@ export class ToolExecutionService {log('Executing Cloud MCP tool: %s:%s via cloud gateway', identifier, apiName);try {- // Create DiscoverService with user context- const discoverService = new DiscoverService({- userInfo: context.userId ? { userId: context.userId } : undefined,- });-- // Parse arguments- const apiParams = safeParseJSON(args) || {};-- // Call cloud MCP endpoint via Market API- // Returns CloudGatewayResponse: { content: ToolCallContent[], isError?: boolean }- const cloudResult = await discoverService.callCloudMcpEndpoint({- apiParams,- identifier,- toolName: apiName,- });-- const cloudResultContent = (cloudResult?.content ?? []) as ToolCallContent[];-- // Convert content blocks to string (same as market router does)- const content = contentBlocksToString(cloudResultContent);- const state = { ...cloudResult, content: cloudResultContent };+ const { content, state, success } = await callCloudMcpTool(+ { args, identifier, toolName: apiName },+ runtimeCloudMcpCaller(context.userId),+ );log('Cloud MCP tool execution successful for: %s:%s', identifier, apiName);- return {- content,- state,- success: !cloudResult?.isError,- };+ return { content, state, success };} catch (error) {log('Cloud MCP tool execution failed for %s:%s: %O', identifier, apiName, error);return {diff --git a/packages/const/src/plugin.test.ts b/packages/const/src/plugin.test.tsindex 8b9fd21571d..dbc2ecd5176 100644--- a/packages/const/src/plugin.test.ts+++ b/packages/const/src/plugin.test.ts@@ -1,6 +1,14 @@import { describe, expect, it } from 'vitest';-import { ARTIFACT_TAG_REGEX } from './plugin';+import {+ ARTIFACT_TAG_REGEX,+ hasMandatoryApproval,+ humanInterventionMayResolveTo,+ isMarketplaceInstallRunnable,+ keepsDesktopStdioExecution,+ mayRequireMandatoryApproval,+ withMandatoryApprovalMark,+} from './plugin';describe('ARTIFACT_TAG_REGEX', () => {it('should match a simple lobeArtifact tag', () => {@@ -78,3 +86,119 @@ OpenAI的存在,就像是一场精心编排的默剧。台上的演员们摆出expect(matches).toHaveLength(2);});});++describe('keepsDesktopStdioExecution', () => {+ it.each([+ { connector: { sourceType: 'marketplace' }, expected: true },+ {+ connector: { metadata: { desktopStdioExecution: true }, sourceType: 'custom' },+ expected: true,+ },+ {+ connector: { metadata: { desktopStdioExecution: 'true' }, sourceType: 'custom' },+ expected: false,+ },+ { connector: { metadata: null, sourceType: 'custom' }, expected: false },+ ])('is $expected for $connector', ({ connector, expected }) => {+ expect(keepsDesktopStdioExecution(connector)).toBe(expected);+ });+});++describe('isMarketplaceInstallRunnable', () => {+ const pending = {+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://mcp.example.com',+ metadata: {},+ sourceType: 'marketplace',+ status: 'disconnected',+ };++ it.each([+ { case: 'a pending reinstall over a plugin row', connector: pending, plugin: true, ok: false },+ { case: 'an unfinished install', connector: { ...pending, status: 'connected' }, ok: false },+ {+ case: 'a connected row with a plugin row',+ connector: { ...pending, status: 'connected' },+ ok: true,+ plugin: true,+ },+ {+ case: 'a finished install',+ connector: { ...pending, metadata: { marketplaceInstalled: true }, status: 'connected' },+ ok: true,+ },+ {+ case: 'a finished install waiting on its authorization',+ connector: { ...pending, metadata: { marketplaceInstalled: true } },+ ok: false,+ },+ { case: 'an agent-owned copy', connector: { ...pending, agentId: 'agt_1' }, ok: true },+ {+ case: 'an endpoint-less projection',+ connector: { ...pending, mcpConnectionType: null, mcpServerUrl: null },+ ok: true,+ },+ { case: 'a custom connector', connector: { ...pending, sourceType: 'custom' }, ok: true },+ ])('is $ok for $case', ({ connector, ok, plugin }) => {+ expect(isMarketplaceInstallRunnable(connector, !!plugin)).toBe(ok);+ });+});++describe('mayRequireMandatoryApproval', () => {+ it('reads a static always', () => {+ expect(mayRequireMandatoryApproval('always')).toBe(true);+ expect(mayRequireMandatoryApproval('required')).toBe(false);+ expect(mayRequireMandatoryApproval('never')).toBe(false);+ expect(mayRequireMandatoryApproval(undefined)).toBe(false);+ expect(mayRequireMandatoryApproval(null)).toBe(false);+ });++ it('counts a rule that can ask for always, whatever its match', () => {+ expect(+ mayRequireMandatoryApproval([+ { match: { path: '/tmp/*' }, policy: 'never' },+ { match: { recursive: 'true' }, policy: 'always' },+ ]),+ ).toBe(true);+ expect(mayRequireMandatoryApproval([{ policy: 'never' }, { policy: 'required' }])).toBe(false);+ });++ it('counts either outcome of a dynamic config, whose unset policy is always', () => {+ expect(mayRequireMandatoryApproval({ dynamic: { default: 'never', type: 'x' } })).toBe(true);+ expect(+ mayRequireMandatoryApproval({ dynamic: { default: 'always', policy: 'never', type: 'x' } }),+ ).toBe(true);+ expect(+ mayRequireMandatoryApproval({ dynamic: { default: 'never', policy: 'required', type: 'x' } }),+ ).toBe(false);+ });+});++describe('humanInterventionMayResolveTo', () => {+ it('matches any of the given policies', () => {+ expect(humanInterventionMayResolveTo('required', ['required', 'always'])).toBe(true);+ expect(humanInterventionMayResolveTo([{ policy: 'never' }], ['required', 'always'])).toBe(+ false,+ );+ });+});++describe('withMandatoryApprovalMark', () => {+ it('marks the metadata only for a manifest that can ask for always', () => {+ expect(withMandatoryApprovalMark(null, 'always')).toEqual({ mandatoryApproval: true });+ expect(withMandatoryApprovalMark({ visibility: ['model'] }, 'always')).toEqual({+ mandatoryApproval: true,+ visibility: ['model'],+ });+ expect(withMandatoryApprovalMark(null, 'required')).toBeNull();+ expect(withMandatoryApprovalMark({ visibility: ['app'] }, undefined)).toEqual({+ visibility: ['app'],+ });+ });++ it('is read back by hasMandatoryApproval', () => {+ expect(hasMandatoryApproval(withMandatoryApprovalMark(null, 'always'))).toBe(true);+ expect(hasMandatoryApproval({ mandatoryApproval: 'true' })).toBe(false);+ expect(hasMandatoryApproval(null)).toBe(false);+ });+});diff --git a/packages/const/src/plugin.ts b/packages/const/src/plugin.tsindex 670bd087f2c..3b32c5f98d8 100644--- a/packages/const/src/plugin.ts+++ b/packages/const/src/plugin.ts@@ -51,3 +51,135 @@ export const MENTION_TAG_REGEX = /<mention\b[^>]*>([\S\s]*?)(?:<\/mention>|$)/;export const AGENTS_TAG = 'lobeAgents';export const AGENTS_TAG_REGEX = /<lobeAgents\b[^>]*(?:\/>|>([\S\s]*?)(?:<\/lobeAgents>|$))/;++/**+ * `user_connectors.metadata` key a marketplace MCP install sets once it has+ * finished. An OAuth callback can still connect a row after the user canceled+ * the install, so a connected marketplace row is callable only with this mark+ * (or, for installs made before connectors, a `user_installed_plugins` row).+ */+export const MARKETPLACE_INSTALL_COMPLETED_KEY = 'marketplaceInstalled';++export const isMarketplaceInstallCompleted = (metadata: unknown): boolean =>+ !!metadata &&+ typeof metadata === 'object' &&+ (metadata as Record<string, unknown>)[MARKETPLACE_INSTALL_COMPLETED_KEY] === true;++/**+ * `user_connectors.metadata` key a custom MCP installed from a protocol link+ * sets. Those installs used to be custom plugins, whose stdio calls ran on the+ * desktop over IPC with or without a device gateway.+ */+export const DESKTOP_STDIO_EXECUTION_KEY = 'desktopStdioExecution';++/**+ * Whether a stdio connector's conversation calls stay on the desktop that makes+ * them even when a device gateway is configured (the connector route refuses+ * stdio): marketplace and protocol-link installs, which ran there as plugins.+ */+export const keepsDesktopStdioExecution = (connector: {+ metadata?: unknown;+ sourceType?: string | null;+}): boolean =>+ connector.sourceType === 'marketplace' ||+ (!!connector.metadata &&+ typeof connector.metadata === 'object' &&+ (connector.metadata as Record<string, unknown>)[DESKTOP_STDIO_EXECUTION_KEY] === true);++/**+ * A connector the tool runtime can call: an HTTP URL, a stdio command, or a+ * marketplace server the market hosts (`cloud`). Rows without one only+ * project tools another executor runs.+ */+export const hasCallableMcpEndpoint = (connector: {+ mcpConnectionType?: string | null;+ mcpServerUrl?: string | null;+}): boolean =>+ !!connector.mcpServerUrl ||+ connector.mcpConnectionType === 'stdio' ||+ connector.mcpConnectionType === 'cloud';++/**+ * Whether a connector's tools may run as far as its marketplace install goes.+ * A base marketplace row with an endpoint needs a finished install (its own+ * mark, or a pre-connector plugin row: `hasPluginRow`) and a connected status.+ * A reinstall or an OAuth re-authorization rewrites the endpoint and leaves the+ * row disconnected until its tools sync, so neither the plugin row nor the mark+ * may run the old tools against the new endpoint meanwhile. Other rows and+ * agent-owned copies pass.+ */+export const isMarketplaceInstallRunnable = (+ connector: {+ agentId?: string | null;+ mcpConnectionType?: string | null;+ mcpServerUrl?: string | null;+ metadata?: unknown;+ sourceType?: string | null;+ status?: string | null;+ },+ hasPluginRow: boolean,+): boolean =>+ !!connector.agentId ||+ connector.sourceType !== 'marketplace' ||+ !hasCallableMcpEndpoint(connector) ||+ (connector.status === 'connected' &&+ (hasPluginRow || isMarketplaceInstallCompleted(connector.metadata)));++/**+ * Whether a manifest tool's `humanIntervention` can resolve to one of+ * `policies`: the policy itself, any of its rules, or either outcome of a+ * dynamic config (its `policy`, `always` when unset, on a match; its `default`+ * otherwise). Callers that carry one policy per tool, where rules and+ * resolvers cannot run, read the strictest outcome from this.+ */+export const humanInterventionMayResolveTo = (+ humanIntervention: unknown,+ policies: readonly string[],+): boolean => {+ const matches = (policy: unknown) => typeof policy === 'string' && policies.includes(policy);+ const rules = Array.isArray(humanIntervention) ? humanIntervention : [humanIntervention];++ return rules.some((rule) => {+ if (!rule || typeof rule !== 'object') return matches(rule);++ const { dynamic, policy } = rule as { dynamic?: unknown; policy?: unknown };+ if (dynamic && typeof dynamic === 'object') {+ const { default: fallback, policy: onMatch = 'always' } = dynamic as {+ default?: unknown;+ policy?: unknown;+ };+ return matches(onMatch) || matches(fallback);+ }+ return matches(policy);+ });+};++/**+ * Whether a manifest tool can ask for `always` approval, the one no approval+ * mode waives (auto-run and headless skip `required`).+ */+export const mayRequireMandatoryApproval = (humanIntervention: unknown): boolean =>+ humanInterventionMayResolveTo(humanIntervention, ['always']);++/**+ * `user_connector_tools.metadata` key a synced tool sets when its manifest can+ * ask for `always` approval (a cloud marketplace MCP the market marks so). The+ * connector's manifest is built from the row, whose `needs_approval` becomes a+ * `required` that auto-run skips: the mark keeps the tool on `always`, whatever+ * its permission, as the plugin manifest kept it.+ */+export const MANDATORY_APPROVAL_KEY = 'mandatoryApproval';++export const hasMandatoryApproval = (metadata: unknown): boolean =>+ !!metadata &&+ typeof metadata === 'object' &&+ (metadata as Record<string, unknown>)[MANDATORY_APPROVAL_KEY] === true;++/** A synced tool's `metadata`, marked when its manifest `humanIntervention` can ask for `always`. */+export const withMandatoryApprovalMark = (+ metadata: Record<string, unknown> | null,+ humanIntervention: unknown,+): Record<string, unknown> | null =>+ mayRequireMandatoryApproval(humanIntervention)+ ? { ...metadata, [MANDATORY_APPROVAL_KEY]: true }+ : metadata;diff --git a/packages/mecha/src/toolSet/manifestPool.test.ts b/packages/mecha/src/toolSet/manifestPool.test.tsindex a36bd07ea58..766d5dd210a 100644--- a/packages/mecha/src/toolSet/manifestPool.test.ts+++ b/packages/mecha/src/toolSet/manifestPool.test.ts@@ -62,6 +62,31 @@ describe('buildConnectorManifest', () => {expect(built.meta.description).toBe('Dashboard connector with 3 tools');});+ // Auto-run and headless skip `required` but never `always`+ it('keeps a tool its manifest made mandatory on always, whatever its permission', () => {+ const mandatory = { mandatoryApproval: true };+ const built = buildConnectorManifest({+ identifier: 'cloud-mail',+ isEnabled: true,+ name: 'Cloud Mail',+ tools: [+ { metadata: mandatory, permission: 'needs_approval', toolName: 'send' },+ { metadata: { ...mandatory, visibility: ['model'] }, permission: 'auto', toolName: 'wipe' },+ { metadata: mandatory, permission: 'disabled', toolName: 'purge' },+ { metadata: { mandatoryApproval: 'yes' }, permission: 'auto', toolName: 'read' },+ ],+ })!;++ expect(built.api.map((a) => [a.name, a.humanIntervention])).toEqual([+ ['send', 'always'],+ ['wipe', 'always'],+ // Execution refuses a disabled tool regardless+ ['purge', 'required'],+ ['read', undefined],+ ]);+ expect(built.api[2].description).toContain('[TOOL DISABLED]');+ });+it('builds nothing when every tool is for views only', () => {expect(buildConnectorManifest({@@ -93,6 +118,47 @@ describe('patchManifestWithPermissions', () => {expect(patched.api[1].description).toContain('[TOOL DISABLED]');expect(patched.api[2]).toEqual({ name: 'c', parameters: {} });});++ it("never loosens a manifest's own always into a required that auto-run skips", () => {+ const patched = patchManifestWithPermissions(+ {+ api: [+ { humanIntervention: 'always', name: 'a' },+ { humanIntervention: [{ match: { force: true }, policy: 'always' }], name: 'b' },+ { humanIntervention: { dynamic: { default: 'never', type: 'audit' } }, name: 'c' },+ { humanIntervention: 'required', name: 'd' },+ { name: 'e' },+ { humanIntervention: 'always', name: 'f' },+ ] as { humanIntervention?: unknown; name: string }[],+ },+ new Map([+ ['a', 'needs_approval'],+ ['b', 'needs_approval'],+ ['c', 'needs_approval'],+ ['d', 'needs_approval'],+ ['e', 'needs_approval'],+ ['f', 'auto'],+ ]),+ );++ expect(patched.api.map((a) => [a.name, a.humanIntervention])).toEqual([+ ['a', 'always'],+ ['b', 'always'],+ // A dynamic config's unset `policy` is `always` on a match+ ['c', 'always'],+ ['d', 'required'],+ ['e', 'required'],+ ['f', 'always'],+ ]);+ });++ it('reads a manifest-level always where the tool sets none, as the runtime does', () => {+ const patched = patchManifestWithPermissions(+ { api: [{ name: 'a' }], humanIntervention: 'always' },+ new Map([['a', 'needs_approval']]),+ );+ expect(patched.api[0]).toMatchObject({ humanIntervention: 'always' });+ });});describe('assembleManifestPool', () => {diff --git a/packages/mecha/src/toolSet/manifestPool.ts b/packages/mecha/src/toolSet/manifestPool.tsindex cf97100b053..4ee2c99ebe7 100644--- a/packages/mecha/src/toolSet/manifestPool.ts+++ b/packages/mecha/src/toolSet/manifestPool.ts@@ -1,4 +1,5 @@import { isSyncedMcpToolVisibleTo } from '@lobechat/const/mcpApp';+import { hasMandatoryApproval, mayRequireMandatoryApproval } from '@lobechat/const/plugin';import type { LobeToolManifest } from '@lobechat/context-engine';import type { BuiltinToolResolveContext, LobeBuiltinTool } from '@lobechat/types';import debug from 'debug';@@ -37,9 +38,26 @@ export const disabledToolDescription = (toolName: string): string =>`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.`;+/**+ * A synced connector tool's `humanIntervention`: `needs_approval` →+ * `required`; `disabled` → `required` too (the manifest adds the blocking+ * description and execution refuses it). A tool its manifest made mandatory+ * (`metadata.mandatoryApproval`) is `always` whatever its permission, since+ * auto-run and headless skip `required` but never `always`.+ */+export const connectorToolIntervention = (+ tool: Pick<ConnectorToolFacts, 'metadata' | 'permission'>,+): 'always' | 'required' | undefined => {+ if (tool.permission === 'disabled') return 'required';+ if (hasMandatoryApproval(tool.metadata)) return 'always';+ return tool.permission === 'needs_approval' ? 'required' : undefined;+};+/*** Patch a manifest's `api[]` with connector tool permissions:- * `needs_approval` → `humanIntervention: 'required'`; `disabled` → the+ * `needs_approval` → `humanIntervention: 'required'`, or `always` where the+ * tool (or, failing that, the manifest) can ask for `always` itself, so a+ * permission never loosens it into one auto-run skips; `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.@@ -48,6 +66,7 @@ export function patchManifestWithPermissions<M extends { api: readonly { name: smanifest: M,toolPermissions: ConnectorToolPermissions,): M {+ const manifestIntervention = (manifest as { humanIntervention?: unknown }).humanIntervention;const patchedApi = manifest.api.map((api) => {const permission = toolPermissions.get(api.name);if (permission === 'disabled') {@@ -58,7 +77,13 @@ export function patchManifestWithPermissions<M extends { api: readonly { name: s};}if (permission === 'needs_approval') {- return { ...api, humanIntervention: 'required' as const };+ const own = (api as { humanIntervention?: unknown }).humanIntervention;+ return {+ ...api,+ humanIntervention: mayRequireMandatoryApproval(own ?? manifestIntervention)+ ? ('always' as const)+ : ('required' as const),+ };}return api;});@@ -68,10 +93,10 @@ export function patchManifestWithPermissions<M extends { api: readonly { name: s/*** A connector's tools as one MCP manifest: every synced tool the model may* see is listed (disabled ones with the blocking description), permissions- * become `humanIntervention`. Tools only views may call are left out. Returns- * nothing for a disabled connector or one with no tools for the model — such a- * connector must not replace a same-named plugin while contributing nothing- * to call.+ * become `humanIntervention` (`connectorToolIntervention`). Tools only views+ * may call are left out. Returns nothing for a disabled connector or one with+ * no tools for the model — 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;@@ -84,17 +109,12 @@ export const buildConnectorManifest = (connector: ConnectorFacts): LobeToolManifstring,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,+ description:+ tool.permission === 'disabled'+ ? disabledToolDescription(tool.toolName)+ : (tool.description ?? ''),+ humanIntervention: connectorToolIntervention(tool),name: tool.toolName,parameters,};diff --git a/packages/observability-otel/package.json b/packages/observability-otel/package.jsonindex fe9bc4ff3aa..29281577951 100644--- a/packages/observability-otel/package.json+++ b/packages/observability-otel/package.json@@ -10,6 +10,7 @@"./modules/agent-runtime": "./src/modules/agent-runtime/index.ts","./modules/agent-signal": "./src/modules/agent-signal/index.ts","./modules/bot-wake": "./src/modules/bot-wake/index.ts",+ "./modules/legacy-plugin-write": "./src/modules/legacy-plugin-write/index.ts","./modules/memory-user-memory": "./src/modules/memory-user-memory/index.ts","./modules/onboarding-understanding": "./src/modules/onboarding-understanding/index.ts","./modules/fts-search-reindex": "./src/modules/fts-search-reindex/index.ts",diff --git a/packages/observability-otel/src/modules/legacy-plugin-write/index.ts b/packages/observability-otel/src/modules/legacy-plugin-write/index.tsnew file mode 100644index 00000000000..647d009759b--- /dev/null+++ b/packages/observability-otel/src/modules/legacy-plugin-write/index.ts@@ -0,0 +1,21 @@+import { metrics } from '@opentelemetry/api';++const meter = metrics.getMeter('server-services-legacy-plugin-write');++/**+ * Calls to the 1.0 plugin create routes (`plugin.createPlugin`,+ * `plugin.createOrInstallPlugin`). Current clients install MCP servers as+ * connectors, so what is left here is released clients that still write+ * `user_installed_plugins` rows. Deleting the routes waits until this series is+ * close to zero.+ *+ * Labels are small closed sets only: `procedure`, `plugin_type`+ * (plugin|customPlugin), `client_type` (desktop|mobile|web|unknown) and+ * `client_version` (a release line such as `2.3` up to the server's own,+ * `older`, `newer`, `other` or `none`). Never a user, workspace or plugin+ * identifier.+ */+export const legacyPluginWriteCounter = meter.createCounter('legacy_plugin_write_calls_total', {+ description: 'Calls to the legacy plugin create routes, by procedure and client.',+ unit: '{call}',+});diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsxindex 94ab25f5f19..2de95fe8db1 100644--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx@@ -36,7 +36,7 @@ import type { ReactNode } from 'react';import { useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { openConnectorEditDrawer } from '@/features/Connectors/CustomConnectorModal/imperative';+import { useConnectorConfigure } from '@/features/Connectors/CustomConnectorModal/useConnectorConfigure';import { openPluginEditDrawer } from '@/features/PluginDevModal/imperative';import { createSkillStoreModal } from '@/features/SkillStore';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';@@ -82,6 +82,7 @@ import SkillRow from './SkillRow';import ToolItem from './ToolItem';import ToolItemDetailPopover from './ToolItemDetailPopover';import { styles } from './useControls.styles';+import { usePluginRowUninstall } from './usePluginRowUninstall';const officialTag = (<Tooltip placement={'top'} title={'LobeHub'}>@@ -158,19 +159,14 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =const [autoModeLoading, setAutoModeLoading] = useState(false);const { allowed: canEdit } = usePermission('edit_own_content');const list = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);- const [- uninstallPlugin,- removeComposioConnection,- deleteAgentSkill,- uninstallBuiltinTool,- deleteConnector,- ] = useToolStore((s) => [- s.uninstallCustomPlugin,- s.removeComposioConnection,- s.deleteAgentSkill,- s.uninstallBuiltinTool,- s.deleteConnector,- ]);+ const uninstallPluginRow = usePluginRowUninstall();+ const [removeComposioConnection, deleteAgentSkill, uninstallBuiltinTool, deleteConnector] =+ useToolStore((s) => [+ s.removeComposioConnection,+ s.deleteAgentSkill,+ s.uninstallBuiltinTool,+ s.deleteConnector,+ ]);const [checked, togglePlugin, setPluginMode] = useAgentStore((s) => [// Pinned identifiers only (getAgentPluginsById already excludes disabled).agentByIdSelectors.getAgentPluginsById(agentId)(s),@@ -571,8 +567,9 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);- // Custom connectors (user-added OAuth MCP servers) from the connector store- const customConnectors = useToolStore(connectorSelectors.customConnectors, isEqual);+ // MCP connectors the user added: custom ones and marketplace installs+ const customConnectors = useToolStore(connectorSelectors.userMcpConnectors, isEqual);+ const getConfigure = useConnectorConfigure();const isConnectorsInit = useToolStore((s) => s.isConnectorsInit);const fetchConnectors = useToolStore((s) => s.fetchConnectors);useEffect(() => {@@ -1169,7 +1166,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =[userAgentSkills, t, createManagedSkillItem, deleteAgentSkill],);- // Custom connector list items (user-added OAuth MCP servers).+ // Connector MCP list items (custom ones and marketplace installs).// Toggling adds the connector identifier to agents.plugins[] — the same field// the runtime resolves connectors from, so they become callable immediately.const customConnectorItems = useMemo(@@ -1189,7 +1186,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =return createManagedSkillItem({badge: <Icon icon={McpIcon} size={12} />,- configureConfig: { onConfigure: () => openConnectorEditDrawer(connector.id) },+ configureConfig: getConfigure(connector),deleteConfig: {displayName: title,onDelete: async () => {@@ -1210,7 +1207,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =title,});}),- [customConnectors, t, createManagedSkillItem, deleteConnector, togglePlugin],+ [customConnectors, t, createManagedSkillItem, deleteConnector, getConfigure, togglePlugin],);// Skills list items (including LobeHub Skill and Composio)@@ -1298,7 +1295,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =: undefined,deleteConfig: {displayName: title,- onDelete: () => uninstallPlugin(item.identifier),+ onDelete: () => uninstallPluginRow(item),},extraTag: isCustom ? (<Tag color={'warning'} icon={<Icon icon={Package} />} size={'small'}>diff --git a/src/features/ChatInput/ActionBar/Tools/usePluginRowUninstall.test.ts b/src/features/ChatInput/ActionBar/Tools/usePluginRowUninstall.test.tsnew file mode 100644index 00000000000..96f7b2cb661--- /dev/null+++ b/src/features/ChatInput/ActionBar/Tools/usePluginRowUninstall.test.ts@@ -0,0 +1,36 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useToolStore } from '@/store/tool';++import { usePluginRowUninstall } from './usePluginRowUninstall';++const uninstallCustomPlugin = vi.fn();+const uninstallMCPPlugin = vi.fn();++const uninstallRow = (row: { identifier: string; runtimeType?: string; type: string }) =>+ renderHook(() => usePluginRowUninstall()).result.current(row);++describe('usePluginRowUninstall', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ useToolStore.setState({ uninstallCustomPlugin, uninstallMCPPlugin } as never);+ });++ // A reinstalled marketplace MCP keeps its legacy row beside the connector it+ // runs on; the picker lists only the row, so its Delete must remove both.+ it('uninstalls a community MCP row through the marketplace uninstall', async () => {+ await uninstallRow({ identifier: 'market-mcp', runtimeType: 'mcp', type: 'plugin' });++ expect(uninstallMCPPlugin).toHaveBeenCalledWith('market-mcp');+ expect(uninstallCustomPlugin).not.toHaveBeenCalled();+ });++ it('removes only the plugin row of a custom MCP or a non-MCP community plugin', async () => {+ await uninstallRow({ identifier: 'my-mcp', runtimeType: 'mcp', type: 'customPlugin' });+ await uninstallRow({ identifier: 'search', runtimeType: 'default', type: 'plugin' });++ expect(uninstallCustomPlugin.mock.calls).toEqual([['my-mcp'], ['search']]);+ expect(uninstallMCPPlugin).not.toHaveBeenCalled();+ });+});diff --git a/src/features/ChatInput/ActionBar/Tools/usePluginRowUninstall.ts b/src/features/ChatInput/ActionBar/Tools/usePluginRowUninstall.tsnew file mode 100644index 00000000000..61e36d8c605--- /dev/null+++ b/src/features/ChatInput/ActionBar/Tools/usePluginRowUninstall.ts@@ -0,0 +1,31 @@+import { useCallback } from 'react';++import { useToolStore } from '@/store/tool';++interface PluginRow {+ identifier: string;+ runtimeType?: string;+ type: string;+}++/**+ * The picker's Delete for a plugin row. A community MCP reinstalled since+ * connectors keeps its legacy row beside the marketplace connector it runs on,+ * and the picker lists only the row, so its Delete goes through+ * `uninstallMCPPlugin`, which removes both, as Settings' Uninstall does. Any+ * other row is the plugin alone.+ */+export const usePluginRowUninstall = () => {+ const [uninstallPlugin, uninstallMCPPlugin] = useToolStore((s) => [+ s.uninstallCustomPlugin,+ s.uninstallMCPPlugin,+ ]);++ return useCallback(+ ({ identifier, runtimeType, type }: PluginRow) =>+ type !== 'customPlugin' && runtimeType === 'mcp'+ ? uninstallMCPPlugin(identifier)+ : uninstallPlugin(identifier),+ [uninstallMCPPlugin, uninstallPlugin],+ );+};diff --git a/src/features/ChatInput/InputEditor/ActionTag/useInstalledSkillsAndTools.ts b/src/features/ChatInput/InputEditor/ActionTag/useInstalledSkillsAndTools.tsindex bfd765bc69b..502a0fe82cd 100644--- a/src/features/ChatInput/InputEditor/ActionTag/useInstalledSkillsAndTools.ts+++ b/src/features/ChatInput/InputEditor/ActionTag/useInstalledSkillsAndTools.ts@@ -17,7 +17,7 @@ import type { ActionTagData } from './types';interface InstalledSources {builtinSkills: ReturnType<typeof builtinToolSelectors.installedBuiltinSkills>;composioServers: ReturnType<typeof composioStoreSelectors.getServers>;- customConnectors: ReturnType<typeof connectorSelectors.customConnectors>;+ customConnectors: ReturnType<typeof connectorSelectors.userMcpConnectors>;installedPlugins: ReturnType<typeof pluginSelectors.installedPluginMetaList>;lobehubSkillServers: ReturnType<typeof lobehubSkillStoreSelectors.getServers>;marketAgentSkills: ReturnType<typeof agentSkillsSelectors.getMarketAgentSkills>;@@ -27,7 +27,8 @@ interface InstalledSources {const selectInstalledSources = (s: ToolStore): InstalledSources => ({builtinSkills: builtinToolSelectors.installedBuiltinSkills(s),composioServers: composioStoreSelectors.getServers(s),- customConnectors: connectorSelectors.customConnectors(s),+ // Custom connectors and marketplace MCPs installed as connectors+ customConnectors: connectorSelectors.userMcpConnectors(s),installedPlugins: pluginSelectors.installedPluginMetaList(s),lobehubSkillServers: lobehubSkillStoreSelectors.getServers(s),marketAgentSkills: agentSkillsSelectors.getMarketAgentSkills(s),diff --git a/src/features/Connectors/ConnectorDetail/index.test.tsx b/src/features/Connectors/ConnectorDetail/index.test.tsxindex 2e529387bd6..36a6186cea4 100644--- a/src/features/Connectors/ConnectorDetail/index.test.tsx+++ b/src/features/Connectors/ConnectorDetail/index.test.tsx@@ -1,6 +1,7 @@/*** @vitest-environment happy-dom*/+import type * as LobeConst from '@lobechat/const';import { fireEvent, render, screen } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -23,6 +24,7 @@ const mocks = vi.hoisted(() => ({isEnabled?: boolean;metadata?: { description?: string };mcpConnectionType?: string;+ mcpServerUrl?: string;name: string;sourceType: string;status?: string;@@ -40,6 +42,12 @@ const mocks = vi.hoisted(() => ({uninstallMCPPlugin: vi.fn(),updateToolPermission: vi.fn(),},+ manageable: {+ canManage: true,+ canManageCredentials: true,+ isPending: false,+ restrictedByPolicy: false,+ },}));vi.mock('react-i18next', () => ({@@ -49,11 +57,16 @@ vi.mock('react-i18next', () => ({}),}));-vi.mock('@lobechat/const', () => ({+vi.mock('@lobechat/const', async (importOriginal) => ({+ hasCallableMcpEndpoint: (await importOriginal<typeof LobeConst>()).hasCallableMcpEndpoint,getComposioAppByIdentifier: () => undefined,getLobehubSkillProviderById: () => undefined,}));+vi.mock('@/hooks/useConnectorManagePolicy', () => ({+ useConnectorManageable: () => mocks.manageable,+}));+// The manage gate pulls in the user store chain — irrelevant to these render// tests, and it drags heavy module graphs into the unit env.vi.mock('@/hooks/useResourceManageable', () => ({@@ -113,6 +126,82 @@ describe('ConnectorDetail', () => {];mocks.toolState.syncing = false;mocks.toolState.uninstalledBuiltinTools = [];+ mocks.manageable.canManageCredentials = true;+ });++ describe('Refresh', () => {+ const refresh = () => fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));++ it("re-reads a legacy plugin's projected tools from the plugin", () => {+ render(<ConnectorDetail connectorId="connector-1" />);+ refresh();++ expect(mocks.toolState.syncPluginTools).toHaveBeenCalledWith('notion');+ expect(mocks.toolState.syncConnectorTools).not.toHaveBeenCalled();+ });++ // A fresh marketplace install has no legacy plugin row to bootstrap from+ it.each([+ { mcpConnectionType: 'http', mcpServerUrl: 'https://mcp.notion.com/mcp' },+ { mcpConnectionType: 'stdio' },+ { mcpConnectionType: 'cloud' },+ ])('syncs a connector-path install from its own server: %o', (endpoint) => {+ mocks.toolState.connectors[0] = { ...mocks.toolState.connectors[0], ...endpoint };++ render(<ConnectorDetail connectorId="connector-1" />);+ refresh();++ expect(mocks.toolState.syncConnectorTools).toHaveBeenCalledWith('connector-1');+ expect(mocks.toolState.syncPluginTools).not.toHaveBeenCalled();+ });++ it('needs the credentials permission only for a sync that connects to the server', () => {+ mocks.manageable.canManageCredentials = false;+ mocks.toolState.connectors[0] = {+ ...mocks.toolState.connectors[0],+ mcpConnectionType: 'stdio',+ };+ const { unmount } = render(<ConnectorDetail connectorId="connector-1" />);+ expect(screen.getByRole('button', { name: 'Refresh' })).toBeDisabled();+ unmount();++ // A cloud server's tools come from the market manifest+ mocks.toolState.connectors[0] = {+ ...mocks.toolState.connectors[0],+ mcpConnectionType: 'cloud',+ };+ render(<ConnectorDetail connectorId="connector-1" />);+ expect(screen.getByRole('button', { name: 'Refresh' })).toBeEnabled();+ });+ });++ // A protocol-link stdio MCP is a custom connector now, no longer a custom+ // plugin whose command Settings could edit+ it.each([+ { mcpConnectionType: 'http', mcpServerUrl: 'https://mcp.example.com' },+ { mcpConnectionType: 'stdio' },+ ])('offers Edit for a custom connector: %o', (endpoint) => {+ mocks.toolState.connectors[0] = {+ ...mocks.toolState.connectors[0],+ ...endpoint,+ sourceType: ConnectorSourceType.custom,+ };++ render(<ConnectorDetail connectorId="connector-1" />);++ expect(screen.getByRole('button', { name: 'Edit' })).toBeEnabled();+ expect(screen.getByTestId('custom-connector-modal')).toBeInTheDocument();+ });++ it('offers no Edit for a marketplace connector', () => {+ mocks.toolState.connectors[0] = {+ ...mocks.toolState.connectors[0],+ mcpConnectionType: 'stdio',+ };++ render(<ConnectorDetail connectorId="connector-1" />);++ expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument();});it('uses lifecycle actions instead of the generic marketplace uninstall action', () => {diff --git a/src/features/Connectors/ConnectorDetail/index.tsx b/src/features/Connectors/ConnectorDetail/index.tsxindex b24e2823af8..b3bc1a977d8 100644--- a/src/features/Connectors/ConnectorDetail/index.tsx+++ b/src/features/Connectors/ConnectorDetail/index.tsx@@ -1,4 +1,8 @@-import { getComposioAppByIdentifier, getLobehubSkillProviderById } from '@lobechat/const';+import {+ getComposioAppByIdentifier,+ getLobehubSkillProviderById,+ hasCallableMcpEndpoint,+} from '@lobechat/const';import { Button, confirmModal, Flexbox, Tabs, Text, toast, Tooltip } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';@@ -139,6 +143,10 @@ const ConnectorDetail = memo<ConnectorDetailProps>(const updateToolPermission = useToolStore((s) => s.updateToolPermission);const isMcpConnector = connector?.sourceType === ConnectorSourceType.custom;+ // The edit modal stores a server URL or a stdio command, args and env+ const isEditable =+ isMcpConnector &&+ (connector?.mcpConnectionType === 'http' || connector?.mcpConnectionType === 'stdio');const isBuiltin = connector?.sourceType === ConnectorSourceType.builtin;const isMarketplace = connector?.sourceType === ConnectorSourceType.marketplace;@@ -206,17 +214,23 @@ const ConnectorDetail = memo<ConnectorDetailProps>([connectorId, notifyActionError, settlePermissionRejection],);- // Custom connector sync uses the stored credentials (on desktop it reads them- // through the creator/owner-only edit read), so it follows the credentials- // gate. Builtin/marketplace bootstrap syncs are no-ops for non-managers.- const canSync = canManageCredentials || connector?.sourceType !== ConnectorSourceType.custom;+ // A marketplace row without an endpoint only projects a legacy plugin's+ // tools; one installed on the connector path syncs from its own server.+ const isPluginProjection = isMarketplace && !!connector && !hasCallableMcpEndpoint(connector);+ // A sync that connects to the server uses the stored credentials (on desktop+ // it reads them through the creator/owner-only edit read), so it follows the+ // credentials gate. Builtin/manifest bootstrap syncs are no-ops for non-managers.+ const syncsFromServer =+ connector?.sourceType === ConnectorSourceType.custom ||+ (isMarketplace && !isPluginProjection && connector?.mcpConnectionType !== 'cloud');+ const canSync = canManageCredentials || !syncsFromServer;const handleSync = useCallback(async () => {if (!connector) return;try {if (connector.sourceType === ConnectorSourceType.builtin) {await syncBuiltinTool(connector.identifier);- } else if (connector.sourceType === ConnectorSourceType.marketplace) {+ } else if (isPluginProjection) {await syncPluginTools(connector.identifier);} else {await syncConnectorTools(connectorId);@@ -227,6 +241,7 @@ const ConnectorDetail = memo<ConnectorDetailProps>(}, [connector,connectorId,+ isPluginProjection,notifyActionError,syncBuiltinTool,syncPluginTools,@@ -318,8 +333,8 @@ const ConnectorDetail = memo<ConnectorDetailProps>({syncLabel}</Button></ManageTooltip>- {/* Edit button for custom MCP connectors — only http type has a server URL to edit */}- {isMcpConnector && connector?.mcpConnectionType === 'http' && (+ {/* Edit button for custom MCP connectors: their server URL or stdio command */}+ {isEditable && (<ManageTooltip title={credentialsTooltip}><Buttondisabled={!canManageCredentials}@@ -534,8 +549,8 @@ const ConnectorDetail = memo<ConnectorDetailProps>(<div {...stylex.props(styles.body)}>{tab === 'tools' ? tools : overview}- {/* Edit modal — only http connectors have a server URL to edit */}- {isMcpConnector && connector?.mcpConnectionType === 'http' && (+ {/* Edit modal for an http or stdio custom connector */}+ {isEditable && (<CustomConnectorModalconnectorId={connectorId}open={customModalOpen}diff --git a/src/features/Connectors/CustomConnectorModal/connectorEdit.test.ts b/src/features/Connectors/CustomConnectorModal/connectorEdit.test.tsnew file mode 100644index 00000000000..c40aeac4f57--- /dev/null+++ b/src/features/Connectors/CustomConnectorModal/connectorEdit.test.ts@@ -0,0 +1,75 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { restoreConnector } from '@/store/tool/slices/connector/replaceConnector';++import { saveConnectorEdit } from './connectorEdit';++vi.mock('@/store/tool/slices/connector/replaceConnector', () => ({+ restoreConnector: vi.fn().mockResolvedValue(undefined),+}));++const previous = {+ id: 'c1',+ mcpConnectionType: 'stdio',+ mcpStdioConfig: { args: ['-y', 'old-mcp'], command: 'npx' },+ sourceType: 'marketplace',+ status: 'connected',+};+const patch = {+ mcpConnectionType: 'stdio' as const,+ mcpStdioConfig: { args: [], command: 'not-a-command' },+};++const makeStore = () => {+ const state = {+ getConnectorForEdit: vi.fn().mockResolvedValue(previous),+ syncConnectorTools: vi.fn().mockResolvedValue(undefined),+ updateConnector: vi.fn().mockResolvedValue(undefined),+ };+ return { get: () => state as never, state };+};++beforeEach(() => {+ vi.clearAllMocks();+});++describe('saveConnectorEdit', () => {+ it('stores the edit, then lists its tools again, dropping the ones it no longer has', async () => {+ const { get, state } = makeStore();++ await saveConnectorEdit('c1', patch, get);++ expect(state.updateConnector).toHaveBeenCalledWith('c1', patch);+ expect(state.syncConnectorTools).toHaveBeenCalledWith('c1', { pruneMissingAutoTools: true });+ expect(state.syncConnectorTools.mock.invocationCallOrder[0]).toBeGreaterThan(+ state.updateConnector.mock.invocationCallOrder[0],+ );+ expect(restoreConnector).not.toHaveBeenCalled();+ });++ // The old tools would otherwise stay callable against the endpoint the edit stored+ it('puts the connector back when the edited endpoint lists no tools', async () => {+ const { get, state } = makeStore();+ const failure = new Error('spawn not-a-command ENOENT');+ state.syncConnectorTools.mockRejectedValueOnce(failure);++ await expect(saveConnectorEdit('c1', patch, get)).rejects.toBe(failure);++ // Read before the edit overwrote it+ expect(state.getConnectorForEdit.mock.invocationCallOrder[0]).toBeLessThan(+ state.updateConnector.mock.invocationCallOrder[0],+ );+ expect(restoreConnector).toHaveBeenCalledWith(previous, get);+ });++ it('still reports the failed save when the restore fails too', async () => {+ const { get, state } = makeStore();+ const failure = new Error('unreachable');+ state.syncConnectorTools.mockRejectedValueOnce(failure);+ vi.mocked(restoreConnector).mockRejectedValueOnce(new Error('offline'));+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ await expect(saveConnectorEdit('c1', patch, get)).rejects.toBe(failure);+ expect(consoleError).toHaveBeenCalled();+ });+});diff --git a/src/features/Connectors/CustomConnectorModal/connectorEdit.ts b/src/features/Connectors/CustomConnectorModal/connectorEdit.tsnew file mode 100644index 00000000000..06dfa9bc832--- /dev/null+++ b/src/features/Connectors/CustomConnectorModal/connectorEdit.ts@@ -0,0 +1,32 @@+import { restoreConnector } from '@/store/tool/slices/connector/replaceConnector';+import type { ToolStore } from '@/store/tool/store';++type ConnectorPatch = Parameters<ToolStore['updateConnector']>[1];++/**+ * Store a connector edit that needs no authorization (no auth, a bearer token,+ * custom headers), then list its tools again: a changed endpoint, command or+ * credential can expose different tools, so the new list replaces the stored+ * one.+ *+ * When that list can't be read (an unreachable endpoint, a stdio command that+ * doesn't start), the connector is put back the way it was. Otherwise its old+ * tools would stay listed and callable against the endpoint the edit stored.+ */+export const saveConnectorEdit = async (+ id: string,+ patch: ConnectorPatch,+ get: () => ToolStore,+): Promise<void> => {+ const previous = await get().getConnectorForEdit(id);+ await get().updateConnector(id, patch);++ try {+ await get().syncConnectorTools(id, { pruneMissingAutoTools: true });+ } catch (error) {+ await restoreConnector(previous, get).catch((restoreError) => {+ console.error('[connector] restore of connector %s failed:', id, restoreError);+ });+ throw error;+ }+};diff --git a/src/features/Connectors/CustomConnectorModal/index.test.tsx b/src/features/Connectors/CustomConnectorModal/index.test.tsxindex 8b7b3079d50..0b311b44e53 100644--- a/src/features/Connectors/CustomConnectorModal/index.test.tsx+++ b/src/features/Connectors/CustomConnectorModal/index.test.tsx@@ -4,13 +4,18 @@import { render, screen, waitFor } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { restoreConnector } from '@/store/tool/slices/connector/replaceConnector';+import CustomConnectorModal from './index';+import { saveOAuthConnectorEdit } from './oauthEdit';const mocks = vi.hoisted(() => ({+ onSave: undefined as undefined | ((value: unknown, ctx?: unknown) => Promise<void>),state: {connector: undefined as unknown,createConnector: vi.fn(),deleteConnector: vi.fn(),+ fetchConnectors: vi.fn(),getConnectorForEdit: vi.fn(),startConnectorOAuth: vi.fn(),syncConnectorTools: vi.fn(),@@ -27,7 +32,10 @@ vi.mock('react-i18next', () => ({}));vi.mock('@/store/tool', () => ({- useToolStore: (selector: (state: typeof mocks.state) => unknown) => selector(mocks.state),+ useToolStore: Object.assign(+ (selector: (state: typeof mocks.state) => unknown) => selector(mocks.state),+ { getState: () => mocks.state },+ ),}));vi.mock('@/store/tool/slices/connector', () => ({@@ -39,12 +47,17 @@ vi.mock('@/store/tool/slices/connector', () => ({// The form itself is a heavy antd form; what matters here is the value the// modal seeds it with.vi.mock('@/features/PluginDevModal', () => ({- default: ({ value }: { value?: unknown }) => (- <div data-testid="seed">{JSON.stringify(value ?? null)}</div>- ),+ default: ({ onSave, value }: { onSave?: (value: unknown) => Promise<void>; value?: unknown }) => {+ mocks.onSave = onSave;+ return <div data-testid="seed">{JSON.stringify(value ?? null)}</div>;+ },}));+vi.mock('@/store/tool/slices/connector/replaceConnector', () => ({+ restoreConnector: vi.fn().mockResolvedValue(undefined),+}));vi.mock('@/utils/connectorOAuth', () => ({ waitForConnectorOAuth: vi.fn() }));+vi.mock('./oauthEdit', () => ({ saveOAuthConnectorEdit: vi.fn() }));/*** The persisted list projection strips `mcpStdioConfig.env` and@@ -180,3 +193,134 @@ describe('CustomConnectorModal OAuth client pre-fill', () => {expect(auth.clientId).toBeUndefined();});});++describe('CustomConnectorModal edit save', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.state.connector = {+ id: 'c1',+ identifier: 'my-mcp',+ mcpConnectionType: 'stdio',+ mcpServerUrl: null,+ metadata: { description: 'My MCP' },+ name: 'My MCP',+ sourceType: 'marketplace',+ };+ mocks.state.getConnectorForEdit.mockResolvedValue({+ credentials: null,+ mcpStdioConfig: { args: ['-y'], command: 'npx', env: { API_KEY: 'old' } },+ metadata: { description: 'My MCP' },+ oidcConfig: null,+ });+ });++ it('persists an edited stdio command and lists its tools again', async () => {+ render(<CustomConnectorModal open connectorId="c1" onClose={() => {}} />);+ await waitFor(() => expect(screen.getByTestId('seed').textContent).not.toBe('null'));++ await mocks.onSave!({+ customParams: {+ mcp: { args: ['--port', '1'], command: ' uvx ', env: { API_KEY: 'new' }, type: 'stdio' },+ },+ identifier: 'my-mcp',+ });++ expect(mocks.state.updateConnector).toHaveBeenCalledWith(+ 'c1',+ expect.objectContaining({+ mcpConnectionType: 'stdio',+ mcpStdioConfig: { args: ['--port', '1'], command: 'uvx', env: { API_KEY: 'new' } },+ }),+ );+ // The edited endpoint's list replaces the stored one+ expect(mocks.state.syncConnectorTools).toHaveBeenCalledWith('c1', {+ pruneMissingAutoTools: true,+ });+ });++ it('lists the tools of an edited HTTP endpoint again', async () => {+ mocks.state.connector = {+ ...(mocks.state.connector as object),+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://old.example.com',+ };+ render(<CustomConnectorModal open connectorId="c1" onClose={() => {}} />);+ await waitFor(() => expect(screen.getByTestId('seed').textContent).not.toBe('null'));++ await mocks.onSave!({+ customParams: { mcp: { type: 'http', url: 'https://new.example.com' } },+ identifier: 'my-mcp',+ });++ expect(mocks.state.updateConnector).toHaveBeenCalledWith(+ 'c1',+ expect.objectContaining({+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://new.example.com',+ }),+ );+ // The edited endpoint's list replaces the stored one+ expect(mocks.state.syncConnectorTools).toHaveBeenCalledWith('c1', {+ pruneMissingAutoTools: true,+ });+ });++ // Its old tools would otherwise stay callable against the endpoint the edit stored+ it('puts the connector back when the edited stdio command lists no tools', async () => {+ const failure = new Error('spawn not-a-command ENOENT');+ mocks.state.syncConnectorTools.mockRejectedValueOnce(failure);+ render(<CustomConnectorModal open connectorId="c1" onClose={() => {}} />);+ await waitFor(() => expect(screen.getByTestId('seed').textContent).not.toBe('null'));++ await expect(+ mocks.onSave!({+ customParams: { mcp: { command: 'not-a-command', type: 'stdio' } },+ identifier: 'my-mcp',+ }),+ ).rejects.toBe(failure);++ expect(mocks.state.updateConnector).toHaveBeenCalled();+ expect(restoreConnector).toHaveBeenCalledWith(+ expect.objectContaining({+ mcpStdioConfig: { args: ['-y'], command: 'npx', env: { API_KEY: 'old' } },+ }),+ expect.any(Function),+ );+ });++ // Stored before its popup opens: the helper undoes it when authorization fails+ it('authorizes an OAuth edit through the helper that can undo it', async () => {+ mocks.state.connector = {+ ...(mocks.state.connector as object),+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://old.example.com',+ };+ const popup = { close: vi.fn() };+ render(<CustomConnectorModal open connectorId="c1" onClose={() => {}} />);+ await waitFor(() => expect(screen.getByTestId('seed').textContent).not.toBe('null'));++ await mocks.onSave!(+ {+ customParams: {+ mcp: { auth: { type: 'oauth2' }, type: 'http', url: 'https://new.example.com' },+ },+ identifier: 'my-mcp',+ },+ { oauthPopup: popup },+ );++ expect(saveOAuthConnectorEdit).toHaveBeenCalledWith(+ 'c1',+ expect.objectContaining({+ credentials: null,+ mcpServerUrl: 'https://new.example.com',+ oidcConfig: expect.objectContaining({ scheme: 'dcr' }),+ }),+ popup,+ expect.any(Function),+ );+ expect(mocks.state.updateConnector).not.toHaveBeenCalled();+ expect(mocks.state.syncConnectorTools).not.toHaveBeenCalled();+ expect(popup.close).toHaveBeenCalled();+ });+});diff --git a/src/features/Connectors/CustomConnectorModal/index.tsx b/src/features/Connectors/CustomConnectorModal/index.tsxindex 5c3cbe89ba1..f0f2f8a98b2 100644--- a/src/features/Connectors/CustomConnectorModal/index.tsx+++ b/src/features/Connectors/CustomConnectorModal/index.tsx@@ -9,7 +9,9 @@ import { connectorSelectors } from '@/store/tool/slices/connector';import { waitForConnectorOAuth } from '@/utils/connectorOAuth';import { executeOAuthCreate } from '@/utils/connectorOAuthCreate';+import { saveConnectorEdit } from './connectorEdit';import { executeLegacyMigrationSave } from './legacyPluginMigration';+import { saveOAuthConnectorEdit } from './oauthEdit';interface CustomConnectorModalProps {connectorId?: string;@@ -68,7 +70,6 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(({ open, onClose, connectorId, legacyPlugin, onEditSuccess }) => {const createConnector = useToolStore((s) => s.createConnector);const deleteConnector = useToolStore((s) => s.deleteConnector);- const updateConnector = useToolStore((s) => s.updateConnector);const getConnectorForEdit = useToolStore((s) => s.getConnectorForEdit);const startConnectorOAuth = useToolStore((s) => s.startConnectorOAuth);const syncConnectorTools = useToolStore((s) => s.syncConnectorTools);@@ -266,6 +267,16 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(if (newUrl !== undefined) patch.mcpServerUrl = newUrl;+ // The transport and a stdio command are edited here too, not only the URL.+ patch.mcpConnectionType = isHttp ? 'http' : 'stdio';+ if (!isHttp) {+ patch.mcpStdioConfig = {+ args: mcp.args ?? [],+ command: (mcp.command ?? '').trim(),+ env: cleanRecord(mcp.env),+ };+ }+// Custom headers live in metadata (independent of the auth credential and// of the server URL), so always re-sync them from the form. Merge into the// existing metadata — a jsonb update replaces the whole column, so other@@ -304,17 +315,18 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(};}- await updateConnector(connectorId, patch);-- if (authType === 'oauth2' && isHttp) {+ if (isHttp && authType === 'oauth2') {+ // Synced by its callback; a failed authorization undoes the editconst popup = ctx?.oauthPopup;try {- const authorizationUrl = await startConnectorOAuth(connectorId);- await waitForConnectorOAuth(popup, connectorId, authorizationUrl);+ await saveOAuthConnectorEdit(connectorId, patch, popup, useToolStore.getState);} finally {popup?.close();await fetchConnectors();}+ } else {+ // Re-lists the tools; an unreadable list undoes the edit+ await saveConnectorEdit(connectorId, patch, useToolStore.getState);}onEditSuccess?.();diff --git a/src/features/Connectors/CustomConnectorModal/oauthEdit.test.ts b/src/features/Connectors/CustomConnectorModal/oauthEdit.test.tsnew file mode 100644index 00000000000..7540a8b9177--- /dev/null+++ b/src/features/Connectors/CustomConnectorModal/oauthEdit.test.ts@@ -0,0 +1,129 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { restoreConnector } from '@/store/tool/slices/connector/replaceConnector';+import type * as ConnectorOAuthModule from '@/utils/connectorOAuth';+import { ConnectorOAuthError, waitForConnectorOAuth } from '@/utils/connectorOAuth';++import { saveOAuthConnectorEdit } from './oauthEdit';++vi.mock('@/store/tool/slices/connector/replaceConnector', () => ({+ restoreConnector: vi.fn().mockResolvedValue(undefined),+}));+vi.mock('@/utils/connectorOAuth', async (original) => ({+ ...(await original<typeof ConnectorOAuthModule>()),+ waitForConnectorOAuth: vi.fn(),+}));++const previous = { id: 'c1', mcpServerUrl: 'https://old.example.com', status: 'connected' };+const patch = {+ credentials: null,+ mcpServerUrl: 'https://new.example.com',+ oidcConfig: { scheme: 'dcr' as const },+};+const popup = { close: vi.fn() } as unknown as Window;++const makeStore = (statusAfterPopup: string) => {+ const state = {+ connectors: [] as Record<string, unknown>[],+ fetchConnectors: vi.fn(async () => {+ state.connectors = [{ id: 'c1', status: statusAfterPopup }];+ }),+ getConnectorForEdit: vi.fn().mockResolvedValue(previous),+ startConnectorOAuth: vi.fn().mockResolvedValue('https://auth.example.com/authorize'),+ syncConnectorTools: vi.fn().mockResolvedValue(undefined),+ updateConnector: vi.fn().mockResolvedValue(undefined),+ };+ return { get: () => state as never, state };+};++beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(waitForConnectorOAuth).mockResolvedValue(undefined);+});++describe('saveOAuthConnectorEdit', () => {+ it('stores the edit, then authorizes it', async () => {+ const { get, state } = makeStore('connected');++ await saveOAuthConnectorEdit('c1', patch, popup, get);++ expect(state.updateConnector).toHaveBeenCalledWith('c1', patch);+ expect(waitForConnectorOAuth).toHaveBeenCalledWith(+ popup,+ 'c1',+ 'https://auth.example.com/authorize',+ );+ expect(restoreConnector).not.toHaveBeenCalled();+ });++ // The callback's sync only adds tools: the edited endpoint's list replaces them+ it('lists the tools again once the edit is authorized, dropping the ones it no longer has', async () => {+ const { get, state } = makeStore('connected');++ await saveOAuthConnectorEdit('c1', patch, popup, get);++ expect(state.syncConnectorTools).toHaveBeenCalledWith('c1', { pruneMissingAutoTools: true });+ expect(state.syncConnectorTools.mock.invocationCallOrder[0]).toBeGreaterThan(+ vi.mocked(waitForConnectorOAuth).mock.invocationCallOrder[0],+ );+ });++ it('keeps an authorized edit when listing its tools again fails', async () => {+ const { get, state } = makeStore('connected');+ state.syncConnectorTools.mockRejectedValueOnce(new Error('unreachable'));+ vi.spyOn(console, 'error').mockImplementation(() => {});++ await expect(saveOAuthConnectorEdit('c1', patch, popup, get)).resolves.toBeUndefined();+ expect(restoreConnector).not.toHaveBeenCalled();+ });++ // The edit already pointed the connector at the new endpoint: its tools must+ // not keep running there unauthorized+ it.each([+ ['dismissed', new ConnectorOAuthError('dismissed')],+ ['denied', new ConnectorOAuthError('failed')],+ ['timed out', new ConnectorOAuthError('timeout')],+ ])('puts the connector back when authorization is %s', async (_, error) => {+ const { get, state } = makeStore('disconnected');+ vi.mocked(waitForConnectorOAuth).mockRejectedValueOnce(error);++ await expect(saveOAuthConnectorEdit('c1', patch, popup, get)).rejects.toBe(error);+ expect(state.syncConnectorTools).not.toHaveBeenCalled();++ // Read before the edit is stored+ expect(state.getConnectorForEdit.mock.invocationCallOrder[0]).toBeLessThan(+ state.updateConnector.mock.invocationCallOrder[0],+ );+ expect(restoreConnector).toHaveBeenCalledWith(previous, get);+ });++ it('puts the connector back when authorization cannot start', async () => {+ const { get, state } = makeStore('disconnected');+ state.startConnectorOAuth.mockRejectedValueOnce(new Error('Registration rejected'));++ await expect(saveOAuthConnectorEdit('c1', patch, popup, get)).rejects.toThrow(+ 'Registration rejected',+ );+ expect(restoreConnector).toHaveBeenCalledWith(previous, get);+ });++ it('keeps the edit when the callback connected the row but its message was lost', async () => {+ // A COOP provider severs window.opener; the stored edit left the row+ // disconnected, so only this callback can have connected it+ const { get } = makeStore('connected');+ vi.mocked(waitForConnectorOAuth).mockRejectedValueOnce(new ConnectorOAuthError('dismissed'));++ await expect(saveOAuthConnectorEdit('c1', patch, popup, get)).resolves.toBeUndefined();+ expect(restoreConnector).not.toHaveBeenCalled();+ });++ it('still reports the original failure when the restore fails', async () => {+ const { get } = makeStore('disconnected');+ const error = new ConnectorOAuthError('failed');+ vi.mocked(waitForConnectorOAuth).mockRejectedValueOnce(error);+ vi.mocked(restoreConnector).mockRejectedValueOnce(new Error('network'));+ vi.spyOn(console, 'error').mockImplementation(() => {});++ await expect(saveOAuthConnectorEdit('c1', patch, popup, get)).rejects.toBe(error);+ });+});diff --git a/src/features/Connectors/CustomConnectorModal/oauthEdit.ts b/src/features/Connectors/CustomConnectorModal/oauthEdit.tsnew file mode 100644index 00000000000..e982b4165fa--- /dev/null+++ b/src/features/Connectors/CustomConnectorModal/oauthEdit.ts@@ -0,0 +1,60 @@+import { restoreConnector } from '@/store/tool/slices/connector/replaceConnector';+import { connectorSelectors } from '@/store/tool/slices/connector/selectors';+import type { ToolStore } from '@/store/tool/store';+import { ConnectorOAuthError, waitForConnectorOAuth } from '@/utils/connectorOAuth';++type ConnectorPatch = Parameters<ToolStore['updateConnector']>[1];++/**+ * Store an OAuth connector edit, then authorize it in `popup` (or the native+ * desktop window). The authorization needs the edited endpoint and client, so+ * they are stored first; the server leaves the row disconnected until the+ * callback connects it. When the authorization is denied, dismissed or times+ * out, the connector is put back the way it was, so its tools never run+ * against an endpoint nobody authorized.+ *+ * A popup that closes without a result is a success when the callback did+ * connect the row: providers whose COOP policy severs `window.opener` lose the+ * callback's message.+ *+ * The callback's sync only adds tools, so an authorized edit lists them again+ * to drop the ones the edited endpoint no longer has.+ */+export const saveOAuthConnectorEdit = async (+ id: string,+ patch: ConnectorPatch,+ popup: Window | null | undefined,+ get: () => ToolStore,+): Promise<void> => {+ const previous = await get().getConnectorForEdit(id);+ await get().updateConnector(id, patch);++ try {+ const authorizationUrl = await get().startConnectorOAuth(id);+ await waitForConnectorOAuth(popup, id, authorizationUrl);+ } catch (error) {+ if (!(await isConnectedAfterDismiss(error, id, get))) {+ await restoreConnector(previous, get).catch((restoreError) => {+ console.error('[connector] restore of connector %s failed:', id, restoreError);+ });+ throw error;+ }+ }++ // The edit is authorized and stored: a failed re-list only leaves extra tools+ await get()+ .syncConnectorTools(id, { pruneMissingAutoTools: true })+ .catch((syncError) => {+ console.error('[connector] tool sync of connector %s failed:', id, syncError);+ });+};++const isConnectedAfterDismiss = async (error: unknown, id: string, get: () => ToolStore) => {+ if (!(error instanceof ConnectorOAuthError) || error.reason !== 'dismissed') return false;+ try {+ await get().fetchConnectors();+ return connectorSelectors.connectorById(id)(get())?.status === 'connected';+ } catch {+ return false;+ }+};diff --git a/src/features/Connectors/CustomConnectorModal/useConnectorConfigure.test.ts b/src/features/Connectors/CustomConnectorModal/useConnectorConfigure.test.tsnew file mode 100644index 00000000000..0ac46a9abf9--- /dev/null+++ b/src/features/Connectors/CustomConnectorModal/useConnectorConfigure.test.ts@@ -0,0 +1,68 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useUserStore } from '@/store/user';++import { useConnectorConfigure } from './useConnectorConfigure';++const mocks = vi.hoisted(() => ({+ isOwner: false,+ openConnectorEditDrawer: vi.fn(),+ policy: undefined as+ { canEditPolicy: boolean; canManage: boolean; memberManage: string } | undefined,+}));++vi.mock('@/libs/swr', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useClientDataSWR: () => ({ data: mocks.policy, error: undefined }),+}));+vi.mock('@/business/client/hooks/useIsWorkspaceOwner', () => ({+ useIsWorkspaceOwner: () => mocks.isOwner,+}));+vi.mock('./imperative', () => ({ openConnectorEditDrawer: mocks.openConnectorEditDrawer }));++const connector = (overrides: Record<string, unknown> = {}) => ({+ id: 'conn-1',+ mcpConnectionType: 'http',+ userId: 'me',+ ...overrides,+});++const configureOf = (row: ReturnType<typeof connector>) =>+ renderHook(() => useConnectorConfigure()).result.current(row);++describe('useConnectorConfigure', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.isOwner = false;+ mocks.policy = { canEditPolicy: false, canManage: true, memberManage: 'all_members' };+ useUserStore.setState({ user: { id: 'me' } } as never);+ });++ it("opens the edit drawer on the viewer's own connector", () => {+ configureOf(connector())?.onConfigure();++ expect(mocks.openConnectorEditDrawer).toHaveBeenCalledWith('conn-1');+ });++ // The drawer reads the stored credentials (`connector.getForEdit`), which the+ // server refuses to another workspace member: the picker must not offer it.+ it("offers no Configure on another member's connector unless the viewer owns the workspace", () => {+ expect(configureOf(connector({ userId: 'arvin' }))).toBeUndefined();++ mocks.isOwner = true;+ expect(configureOf(connector({ userId: 'arvin' }))).toBeDefined();+ });++ it('offers no Configure while the policy loads or when it restricts the viewer', () => {+ mocks.policy = undefined;+ expect(configureOf(connector())).toBeUndefined();++ mocks.policy = { canEditPolicy: false, canManage: false, memberManage: 'admins_only' };+ expect(configureOf(connector())).toBeUndefined();+ });++ it('offers no Configure on a market-hosted connector, which has no connection settings', () => {+ expect(configureOf(connector({ mcpConnectionType: 'cloud' }))).toBeUndefined();+ });+});diff --git a/src/features/Connectors/CustomConnectorModal/useConnectorConfigure.ts b/src/features/Connectors/CustomConnectorModal/useConnectorConfigure.tsnew file mode 100644index 00000000000..51e1b1bec9c--- /dev/null+++ b/src/features/Connectors/CustomConnectorModal/useConnectorConfigure.ts@@ -0,0 +1,31 @@+import { useCallback } from 'react';++import { useConnectorManageableChecker } from '@/hooks/useConnectorManagePolicy';++import { openConnectorEditDrawer } from './imperative';++interface ConfigurableConnector {+ agentId?: string | null;+ id: string;+ mcpConnectionType: string | null;+ userId?: string | null;+}++/**+ * The tool picker's "Configure" action for each connector row, one hook call+ * for the whole list. The drawer reads the stored credentials+ * (`connector.getForEdit`), so a viewer who may not manage them gets no action,+ * the rule Settings' Configure follows; while the policy loads nobody does yet.+ * A market-hosted (cloud) connector has no connection settings at all.+ */+export const useConnectorConfigure = () => {+ const checkManageable = useConnectorManageableChecker();++ return useCallback(+ (connector: ConfigurableConnector) =>+ connector.mcpConnectionType === 'cloud' || !checkManageable(connector).canManageCredentials+ ? undefined+ : { onConfigure: () => openConnectorEditDrawer(connector.id) },+ [checkManageable],+ );+};diff --git a/src/features/MCPApp/toolCallPolicy.test.ts b/src/features/MCPApp/toolCallPolicy.test.tsindex af54a25870c..5e01473f691 100644--- a/src/features/MCPApp/toolCallPolicy.test.ts+++ b/src/features/MCPApp/toolCallPolicy.test.ts@@ -358,6 +358,50 @@ describe('getAppToolCallPolicy', () => {plugins.set('weather', plugin('always'));expect(await getAppToolCallPolicy('weather', 'send')).toBe('confirm');});++ // A cloud marketplace MCP the market marks `always`: the connector's+ // three-state permission alone would let auto-run through+ it('still asks for a connector tool its manifest made mandatory, whatever its permission', async () => {+ for (const permission of ['needs_approval', 'auto']) {+ connectors.set('mail', {+ ...connector(permission),+ tools: [{ metadata: { mandatoryApproval: true }, permission, toolName: 'send' }],+ });+ expect(await getAppToolCallPolicy('mail', 'send')).toBe('confirm');+ }+ });++ it("keeps a plugin tool's own always when its connector marks it as needing approval", async () => {+ plugins.set('weather', plugin('always'));+ connectors.set('weather', {+ isEnabled: true,+ tools: [{ permission: 'needs_approval', toolName: 'send' }],+ });+ expect(await getAppToolCallPolicy('weather', 'send')).toBe('confirm');++ plugins.set('weather', plugin('required'));+ expect(await getAppToolCallPolicy('weather', 'send')).toBe('allow');+ });++ // An unfinished marketplace reinstall over a plugin row: the call runs the+ // plugin (`invokeMcpToolCall`), so the plugin's own `always` decides+ it('judges an unfinished marketplace reinstall by the plugin it falls back to', async () => {+ plugins.set('weather', plugin('always'));+ connectors.set('weather', {+ ...connector('needs_approval'),+ sourceType: 'marketplace',+ status: 'disconnected',+ });+ expect(await getAppToolCallPolicy('weather', 'send')).toBe('confirm');++ // Once the reinstall finishes, the connector it routes to decides+ connectors.set('weather', {+ ...connector('needs_approval'),+ sourceType: 'marketplace',+ status: 'connected',+ });+ expect(await getAppToolCallPolicy('weather', 'send')).toBe('allow');+ });});it('asks for arguments the security blacklist matches, in every mode', async () => {diff --git a/src/features/MCPApp/toolCallPolicy.ts b/src/features/MCPApp/toolCallPolicy.tsindex d648ec150ae..7f6a520027d 100644--- a/src/features/MCPApp/toolCallPolicy.ts+++ b/src/features/MCPApp/toolCallPolicy.ts@@ -1,5 +1,7 @@import { DEFAULT_SECURITY_BLACKLIST, InterventionChecker } from '@lobechat/agent-runtime';import { isSyncedMcpToolVisibleTo } from '@lobechat/const/mcpApp';+import { isMarketplaceInstallRunnable, mayRequireMandatoryApproval } from '@lobechat/const/plugin';+import { connectorToolIntervention } from '@lobechat/mecha';import type {HumanInterventionConfig,HumanInterventionPolicy,@@ -93,8 +95,14 @@ const findToolIntervention = (const s = getToolStoreState();const confirmed = revalidated && s.isConnectorListConfirmed(agentId);- const connector = connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(s);- // Same routing as `mcpService.invokeMcpToolCall`+ const resolved = connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(s);+ const plugin =+ pluginSelectors.getInstalledPluginById(identifier)(s) ||+ pluginSelectors.getCustomPluginById(identifier)(s);+ // Same routing as `mcpService.invokeMcpToolCall`: an unfinished marketplace+ // install is not run, so the plugin row it falls back to decides+ const connector =+ resolved && isMarketplaceInstallRunnable(resolved, !!plugin) ? resolved : undefined;if (connector?.isEnabled &&(!!connector.mcpServerUrl || connector.mcpConnectionType === 'stdio')@@ -109,13 +117,10 @@ const findToolIntervention = (if (!tool) return { missingFrom: connector.id };// A tool only the model may call is refused before anyone is asked about itif (tool.permission === 'disabled' || !isSyncedMcpToolVisibleTo(tool, 'app')) return null;- // Same mapping as the connector manifest (`patchManifestWithPermissions`)- return { intervention: tool.permission === 'needs_approval' ? 'required' : undefined };+ // Same mapping as the connector manifest (`buildConnectorManifest`)+ return { intervention: connectorToolIntervention(tool) };}- const plugin =- pluginSelectors.getInstalledPluginById(identifier)(s) ||- pluginSelectors.getCustomPluginById(identifier)(s);// An agent's own connector the client hasn't loaded: its permission is// unknown here, so treat it as needing approval.if (!plugin) return agentId ? { intervention: 'required' } : null;@@ -138,9 +143,17 @@ const findToolIntervention = (// (patchManifestWithPermissions). Until the server confirms the lists they// may be stale or missing, so ask.if (!confirmed) return { intervention: 'required' };- const permission = connector?.tools.find((t) => t.toolName === toolName)?.permission;+ const permission = resolved?.tools.find((t) => t.toolName === toolName)?.permission;if (permission === 'disabled') return null;- if (permission === 'needs_approval') return { intervention: 'required' };+ // Never looser than the tool's own `always` (`patchManifestWithPermissions`)+ if (permission === 'needs_approval')+ return {+ intervention: mayRequireMandatoryApproval(+ api?.humanIntervention ?? manifest?.humanIntervention,+ )+ ? 'always'+ : 'required',+ };// A manifest stored before MCP Apps was on lacks the tools its server offers// only to views. Ask rather than refuse: the session the call runs on stilldiff --git a/src/features/PluginDevModal/imperative.tsx b/src/features/PluginDevModal/imperative.tsxindex 248e4ea57c3..a31cdb4e8cf 100644--- a/src/features/PluginDevModal/imperative.tsx+++ b/src/features/PluginDevModal/imperative.tsx@@ -19,9 +19,9 @@ interface PluginEditDrawerProps {const PluginEditDrawer = memo<PluginEditDrawerProps>(({ identifier, onClose, open }) => {const { allowed: canEdit } = usePermission('edit_own_content');const value = useToolStore(pluginSelectors.getCustomPluginById(identifier), isEqual);- const [uninstallPlugin, installCustomPlugin, updateNewCustomPlugin] = useToolStore((s) => [+ const [uninstallPlugin, updateCustomPlugin, updateNewCustomPlugin] = useToolStore((s) => [s.uninstallCustomPlugin,- s.installCustomPlugin,+ s.updateCustomPlugin,s.updateNewCustomPlugin,]);@@ -41,7 +41,8 @@ const PluginEditDrawer = memo<PluginEditDrawerProps>(({ identifier, onClose, ope}}onSave={async (devPlugin) => {if (!canEdit) return;- await installCustomPlugin(devPlugin);+ // Edits the existing legacy row; new custom MCPs are added as connectors.+ await updateCustomPlugin(identifier, devPlugin);onClose();}}/>diff --git a/src/features/ProfileEditor/AgentTool.tsx b/src/features/ProfileEditor/AgentTool.tsxindex 93ec12ca859..fb110694bce 100644--- a/src/features/ProfileEditor/AgentTool.tsx+++ b/src/features/ProfileEditor/AgentTool.tsx@@ -205,8 +205,8 @@ const AgentTool = memo<AgentToolProps>(// Load user's LobeHub Skill connections via SWRuseFetchLobehubSkillConnections(isLobehubSkillEnabled);- // Custom connectors (user-added OAuth MCP servers) from the connector store- const customConnectors = useToolStore(connectorSelectors.customConnectors, isEqual);+ // MCP connectors the user added: custom ones and marketplace installs+ const customConnectors = useToolStore(connectorSelectors.userMcpConnectors, isEqual);// Agent-owned / linked connectors: when `excludeAgentConnectors` is set (the// two-section agent profile), these are rendered in the dedicated "Agent// Tools" section above, so they must be dropped from THIS base/user list —@@ -679,7 +679,7 @@ const AgentTool = memo<AgentToolProps>([marketAgentSkillItems, communityPluginItems],);- // Custom connector list items (user-added OAuth MCP servers)+ // Connector MCP list items (custom ones and marketplace installs)const customConnectorItems = useMemo(() =>customConnectors.map((connector) => {@@ -802,7 +802,7 @@ const AgentTool = memo<AgentToolProps>(// 7. User agent skillsfor (const skill of userAgentSkills) all.add(skill.identifier);- // 8. Custom connectors+ // 8. Connector MCPs: custom ones and marketplace installsfor (const connector of customConnectors) all.add(connector.identifier);return all;diff --git a/src/features/ProfileEditor/PluginTag.test.tsx b/src/features/ProfileEditor/PluginTag.test.tsxindex 3b737bdce9b..fd956c9e6e4 100644--- a/src/features/ProfileEditor/PluginTag.test.tsx+++ b/src/features/ProfileEditor/PluginTag.test.tsx@@ -23,6 +23,7 @@ const mocks = vi.hoisted(() => ({authorizedByName?: string | null;identifier: string;}>,+ marketplaceConnectors: [] as Array<Record<string, unknown>>,}));vi.mock('react-i18next', () => ({@@ -74,6 +75,7 @@ vi.mock('@/store/tool/slices/connector/selectors', () => ({agentConnectors: () => () => mocks.agentConnectors,connectorList: () => mocks.connectorList,customConnectors: () => [],+ marketplaceMcpConnectors: () => mocks.marketplaceConnectors,},}));vi.mock('@/store/tool/selectors', () => ({@@ -142,6 +144,39 @@ describe('PluginTag row variant', () => {beforeEach(() => {mocks.agentConnectors = [];mocks.connectorList = [];+ mocks.marketplaceConnectors = [];+ });++ // `isPluginInstalled` counts it, so no remote lookup would fill the gap+ it('resolves a marketplace MCP installed as a connector alone, with its tools', () => {+ mocks.marketplaceConnectors = [+ {+ identifier: 'github-mcp',+ metadata: { avatar: '🐙', description: 'Work with GitHub' },+ name: 'GitHub',+ tools: [+ { description: 'Open an issue', displayName: null, toolName: 'create_issue' },+ { description: null, displayName: null, toolName: 'search' },+ ],+ },+ ];+ const onOpen = vi.fn();+ render(<PluginTag pluginId="github-mcp" variant="row" onOpen={onOpen} />);++ expect(screen.queryByText(/tools\.notInstalled/)).toBeNull();+ expect(screen.getByText('settingAgent.tools.type.plugin')).toBeTruthy();+ expect(screen.getByText('settingAgent.tools.toolCount')).toBeTruthy();+ fireEvent.click(screen.getByText('GitHub'));+ expect(onOpen).toHaveBeenCalledWith(+ expect.objectContaining({+ description: 'Work with GitHub',+ identifier: 'github-mcp',+ tools: [+ { description: 'Open an issue', name: 'create_issue' },+ { description: null, name: 'search' },+ ],+ }),+ );});it('names the kind of tool and shows whose credentials it runs under', () => {diff --git a/src/features/ProfileEditor/PluginTag.tsx b/src/features/ProfileEditor/PluginTag.tsxindex f254f29b18f..e687dd513da 100644--- a/src/features/ProfileEditor/PluginTag.tsx+++ b/src/features/ProfileEditor/PluginTag.tsx@@ -240,6 +240,11 @@ const PluginTag = memo<PluginTagProps>(// Custom connector stateconst customConnectors = useToolStore(connectorSelectors.customConnectors, isEqual);+ // Marketplace MCPs installed on the connector path, without a legacy plugin row+ const marketplaceConnectors = useToolStore(+ connectorSelectors.marketplaceMcpConnectors,+ isEqual,+ );// Check if plugin is installedconst isInstalled = useToolStore(pluginSelectors.isPluginInstalled(identifier));@@ -324,6 +329,21 @@ const PluginTag = memo<PluginTagProps>(};}+ // A marketplace MCP installed as a connector alone: listed as the plugin it+ // replaces, as Settings lists it+ const marketplaceConnector = marketplaceConnectors.find((c) => c.identifier === identifier);+ if (marketplaceConnector) {+ const { avatar, description } = marketplaceConnector.metadata ?? {};+ return {+ availableInWeb: true,+ avatar: typeof avatar === 'string' ? avatar : undefined,+ description: typeof description === 'string' ? description : undefined,+ isInstalled: true,+ title: marketplaceConnector.name || identifier,+ type: 'plugin' as const,+ };+ }+// Agent-only connector not found in any user store: use its own row + MCP// icon so it renders installed (not a warning "Not Installed" chip).if (agentConn) {@@ -353,6 +373,7 @@ const PluginTag = memo<PluginTagProps>(isLobehubSkillEnabled,allLobehubSkillServers,customConnectors,+ marketplaceConnectors,useAllMetaList,]);@@ -441,7 +462,8 @@ const PluginTag = memo<PluginTagProps>();const connectorTools = (agentConnectors.find((c) => c.identifier === identifier) ??- customConnectors.find((c) => c.identifier === identifier)+ customConnectors.find((c) => c.identifier === identifier) ??+ marketplaceConnectors.find((c) => c.identifier === identifier))?.tools;const toolList: ItemDetail['tools'] = connectorTools?.length? connectorTools.map((tool) => ({diff --git a/src/features/ProtocolUrlHandler/InstallPlugin/CustomPluginInstallModal.tsx b/src/features/ProtocolUrlHandler/InstallPlugin/CustomPluginInstallModal.tsxindex da93797d9e5..182a5131755 100644--- a/src/features/ProtocolUrlHandler/InstallPlugin/CustomPluginInstallModal.tsx+++ b/src/features/ProtocolUrlHandler/InstallPlugin/CustomPluginInstallModal.tsx@@ -12,7 +12,6 @@ import { useAgentStore } from '@/store/agent';import { useToolStore } from '@/store/tool';import { mcpStoreSelectors } from '@/store/tool/selectors';import { type McpConnectionParams } from '@/types/plugins';-import { type LobeToolCustomPlugin } from '@/types/tool/plugin';import ConfigDisplay from './ConfigDisplay';import { type McpInstallRequest } from './types';@@ -36,7 +35,7 @@ const CustomPluginInstallModal = memo<CustomPluginInstallModalProps>(headers?: Record<string, string>;}>({});- const [installCustomPlugin] = useToolStore((s) => [s.installCustomPlugin]);+ const installCustomMcpConnector = useToolStore((s) => s.installCustomMcpConnector);const testMcpConnection = useToolStore((s) => s.testMcpConnection);const togglePlugin = useAgentStore((s) => s.togglePlugin);@@ -87,23 +86,14 @@ const CustomPluginInstallModal = memo<CustomPluginInstallModalProps>(throw new Error(t('protocolInstall.messages.manifestNotFound'));}- // Third-party marketplace and custom plugins: build custom plugin data- // Use the real manifest obtained from connection testing- const customPlugin: LobeToolCustomPlugin = {- customParams: {- avatar: schema.icon,- description: schema.description,- mcp: {- ...finalConfig, // Use the merged config- headers: finalConfig.type === 'http' ? finalConfig.headers : undefined,- },- },+ // Third-party marketplace and custom MCP servers are added as custom connectors+ await installCustomMcpConnector({+ config: finalConfig,+ description: schema.description,+ icon: schema.icon,identifier: schema.identifier,- manifest: testResult.manifest, // Use the real manifest- type: 'customPlugin',- };-- await installCustomPlugin(customPlugin);+ name: schema.name,+ });await togglePlugin(schema.identifier);toast.success(t('protocolInstall.messages.installSuccess', { name: schema.name }));@@ -120,7 +110,7 @@ const CustomPluginInstallModal = memo<CustomPluginInstallModalProps>(schema,updatedConfig,onComplete,- installCustomPlugin,+ installCustomMcpConnector,testMcpConnection,togglePlugin,t,diff --git a/src/features/Settings/skill/features/Actions.tsx b/src/features/Settings/skill/features/Actions.tsxindex 04dc8d67742..9bcf1f39bf4 100644--- a/src/features/Settings/skill/features/Actions.tsx+++ b/src/features/Settings/skill/features/Actions.tsx@@ -11,8 +11,10 @@ import { agentSelectors } from '@/store/agent/selectors';import { useServerConfigStore } from '@/store/serverConfig';import { pluginHelpers, useToolStore } from '@/store/tool';import { mcpStoreSelectors, pluginSelectors } from '@/store/tool/selectors';+import { connectorSelectors } from '@/store/tool/slices/connector';import { type LobeToolType } from '@/types/tool/tool';+import ConnectorConfigureButton from './ConnectorConfigureButton';import EditCustomPlugin from './EditCustomPlugin';interface ActionsProps {@@ -23,14 +25,16 @@ interface ActionsProps {const Actions = memo<ActionsProps>(({ identifier, type, isMCP }) => {const mobile = useServerConfigStore((s) => s.isMobile);+ const isCustomPlugin = type === 'customPlugin';+ const isCommunityMCP = !isCustomPlugin && isMCP;const [installed, installing, unInstallPlugin, installMCPPlugin] = useToolStore((s) => [pluginSelectors.isPluginInstalled(identifier)(s),mcpStoreSelectors.isPluginInstallLoading(identifier)(s),- s.uninstallCustomPlugin,+ // A community MCP may be installed as a connector, which only this removes.+ isCommunityMCP ? s.uninstallMCPPlugin : s.uninstallCustomPlugin,s.installMCPPlugin,]);- const isCustomPlugin = type === 'customPlugin';const { t } = useTranslation('plugin');const plugin = useToolStore(pluginSelectors.getToolManifestById(identifier));const { allowed: canCreate } = usePermission('create_content');@@ -39,6 +43,14 @@ const Actions = memo<ActionsProps>(({ identifier, type, isMCP }) => {s.togglePlugin,agentSelectors.currentAgentPlugins(s).includes(identifier),]);+ // A marketplace MCP installed as a connector, a reinstall over a legacy row+ // included: its tools run on the connector, so its settings are edited there,+ // not in the plugin settings modal.+ const marketConnector = useToolStore((s) =>+ isCommunityMCP+ ? connectorSelectors.marketplaceMcpConnectorByIdentifier(identifier)(s)+ : undefined,+ );const hasSettings = pluginHelpers.isSettingSchemaNonEmpty(plugin?.settings);// Painted from the local cache: settings and connection parameters only// arrive with the server's records, so configuring waits for them.@@ -46,15 +58,20 @@ const Actions = memo<ActionsProps>(({ identifier, type, isMCP }) => {const [showModal, setModal] = useState(false);- const isCommunityMCP = !isCustomPlugin && isMCP;- const showConfigureButton = isCustomPlugin || isMCP || hasSettings;+ // A market-hosted (cloud) connector has no connection settings to edit.+ const showConfigureButton = marketConnector+ ? marketConnector.mcpConnectionType !== 'cloud'+ : isCustomPlugin || isMCP || hasSettings;+ const confirming = isConfirming;- const configureButton = (+ const configureButton = marketConnector ? (+ <ConnectorConfigureButton canEdit={canEdit} connector={marketConnector} />+ ) : (<Button- disabled={!canEdit || isConfirming}- loading={isConfirming}+ disabled={!canEdit || confirming}+ loading={confirming}onClick={() => {- if (!canEdit || isConfirming) return;+ if (!canEdit || confirming) return;if (isCustomPlugin) {setModal(true);} else if (isCommunityMCP) {diff --git a/src/features/Settings/skill/features/ConnectorConfigureButton.tsx b/src/features/Settings/skill/features/ConnectorConfigureButton.tsxnew file mode 100644index 00000000000..f7abc830321--- /dev/null+++ b/src/features/Settings/skill/features/ConnectorConfigureButton.tsx@@ -0,0 +1,44 @@+import { Button, Tooltip } from '@lobehub/ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { openConnectorEditDrawer } from '@/features/Connectors/CustomConnectorModal/imperative';+import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';++import { useConnectorConfigureGate } from './useConnectorConfigureGate';++/**+ * Configure for a marketplace MCP installed as a connector, gated by+ * {@link useConnectorConfigureGate}. Mounted only for such rows, so the manage+ * policy is not read for every plugin row.+ */+const ConnectorConfigureButton = memo<{ canEdit: boolean; connector: ConnectorWithTools }>(+ ({ canEdit, connector }) => {+ const { t } = useTranslation('plugin');+ const { allowed, deniedTitle } = useConnectorConfigureGate(connector, canEdit);++ const button = (+ <Button+ disabled={!allowed}+ onClick={() => {+ if (allowed) openConnectorEditDrawer(connector.id);+ }}+ >+ {t('store.actions.configure')}+ </Button>+ );++ // A disabled button fires no pointer events: the tooltip needs a wrapper.+ return deniedTitle ? (+ <Tooltip title={deniedTitle}>+ <span style={{ display: 'inline-flex' }}>{button}</span>+ </Tooltip>+ ) : (+ button+ );+ },+);++ConnectorConfigureButton.displayName = 'ConnectorConfigureButton';++export default ConnectorConfigureButton;diff --git a/src/features/Settings/skill/features/SkillList.tsx b/src/features/Settings/skill/features/SkillList.tsxindex 816beee159b..ca85f3f405e 100644--- a/src/features/Settings/skill/features/SkillList.tsx+++ b/src/features/Settings/skill/features/SkillList.tsx@@ -93,6 +93,10 @@ const SkillList = memo<SkillListProps>(const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);const builtinSkills = useToolStore((s) => s.builtinSkills, isEqual);const customConnectors = useToolStore(connectorSelectors.customConnectors, isEqual);+ const marketplaceConnectors = useToolStore(+ connectorSelectors.marketplaceMcpConnectors,+ isEqual,+ );const isConnectorsInit = useToolStore((s) => s.isConnectorsInit);const fetchConnectors = useToolStore((s) => s.fetchConnectors);const agentBoundConnectors = useToolStore(connectorSelectors.agentBoundConnectors, isEqual);@@ -309,6 +313,7 @@ const SkillList = memo<SkillListProps>(marketAgentSkills.length > 0 ||userAgentSkills.length > 0 ||communityMCPs.length > 0 ||+ marketplaceConnectors.length > 0 ||customMCPs.length > 0 ||agentBoundConnectors.length > 0;@@ -350,8 +355,8 @@ const SkillList = memo<SkillListProps>(/>));- const renderCommunityMCPs = () =>- communityMCPs.map((plugin) => (+ const renderCommunityMCPs = () => [+ ...communityMCPs.map((plugin) => (<McpSkillItemauthor={plugin.author}avatar={plugin.avatar}@@ -363,7 +368,21 @@ const SkillList = memo<SkillListProps>(type={plugin.type as LobeToolType}onSelect={onSelect ? () => onSelect(plugin.identifier, 'plugin') : undefined}/>- ));+ )),+ // Marketplace installs made on the connector path (no legacy plugin row)+ ...marketplaceConnectors.map((c) => (+ <McpSkillItem+ avatar={c.metadata?.avatar as string | undefined}+ identifier={c.identifier}+ isSelected={selectedIdentifier === c.identifier}+ key={c.id}+ runtimeType="mcp"+ title={c.name || c.identifier}+ type={'plugin' as LobeToolType}+ onSelect={onSelect ? () => onSelect(c.identifier, 'mcp-connector') : undefined}+ />+ )),+ ];const renderCustomMCPs = () =>customMCPs.map((plugin) => (@@ -447,7 +466,8 @@ const SkillList = memo<SkillListProps>(// Skills tab only shows agent-based community skills; Lobehub/Composio OAuth// connectors live exclusively in the Connectors view (hasCommunityConnectors).const hasCommunitySkills = !isConnectorView && marketAgentSkills.length > 0;- const hasCommunityTools = communityMCPs.length > 0 && isConnectorView;+ const communityToolCount = communityMCPs.length + marketplaceConnectors.length;+ const hasCommunityTools = communityToolCount > 0 && isConnectorView;// In connector view: custom MCPs (old plugins) + custom connectors (new store).// In skill view: user agent skillsconst hasCustomConnectors =@@ -556,7 +576,7 @@ const SkillList = memo<SkillListProps>('communityTools',t('skillGroup.communityTools', 'Community Tools'),renderCommunityMCPs(),- communityMCPs.length,+ communityToolCount,)}{hasCustomConnectors &&diff --git a/src/features/Settings/skill/features/useConnectorConfigureGate.test.ts b/src/features/Settings/skill/features/useConnectorConfigureGate.test.tsnew file mode 100644index 00000000000..12aca5be1f2--- /dev/null+++ b/src/features/Settings/skill/features/useConnectorConfigureGate.test.ts@@ -0,0 +1,70 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useConnectorConfigureGate } from './useConnectorConfigureGate';++const mocks = vi.hoisted(() => ({+ manageable: {+ canManage: true,+ canManageCredentials: true,+ isPending: false,+ restrictedByPolicy: false,+ },+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string, fallback?: string) => fallback ?? key }),+}));+vi.mock('@/hooks/useConnectorManagePolicy', () => ({+ useConnectorManageable: () => mocks.manageable,+}));++const connector = { id: 'conn-1', identifier: 'market-mcp', userId: 'creator' } as never;+const gate = (canEdit = true) =>+ renderHook(() => useConnectorConfigureGate(connector, canEdit)).result.current;++describe('useConnectorConfigureGate', () => {+ beforeEach(() => {+ mocks.manageable = {+ canManage: true,+ canManageCredentials: true,+ isPending: false,+ restrictedByPolicy: false,+ };+ });++ it('lets the creator or a workspace owner open the edit drawer', () => {+ expect(gate()).toEqual({ allowed: true, deniedTitle: undefined });+ });++ // The drawer reads the stored credentials (`connector.getForEdit`), which+ // the server refuses to another workspace member+ it("refuses another member's connector, with the reason", () => {+ mocks.manageable.canManageCredentials = false;++ expect(gate()).toEqual({+ allowed: false,+ deniedTitle: 'Only the creator or a workspace owner can manage this connector',+ });+ });++ it('names the workspace policy when it is what restricts the viewer', () => {+ mocks.manageable = {+ ...mocks.manageable,+ canManageCredentials: false,+ restrictedByPolicy: true,+ };++ expect(gate().deniedTitle).toBe('tools.connectorFeedback.manageOnly');+ });++ it('refuses without a reason while the manage policy loads', () => {+ mocks.manageable = { ...mocks.manageable, canManageCredentials: false, isPending: true };++ expect(gate()).toEqual({ allowed: false, deniedTitle: undefined });+ });++ it('refuses without the edit permission', () => {+ expect(gate(false).allowed).toBe(false);+ });+});diff --git a/src/features/Settings/skill/features/useConnectorConfigureGate.ts b/src/features/Settings/skill/features/useConnectorConfigureGate.tsnew file mode 100644index 00000000000..589429f51e9--- /dev/null+++ b/src/features/Settings/skill/features/useConnectorConfigureGate.ts@@ -0,0 +1,29 @@+import { useTranslation } from 'react-i18next';++import { useConnectorManageable } from '@/hooks/useConnectorManagePolicy';+import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';++/**+ * Whether the viewer may open a marketplace connector's edit drawer. The drawer+ * reads the stored credentials (`connector.getForEdit`), which only the+ * creator or a workspace owner may, so this follows the credentials gate the+ * way ConnectorDetail's Edit does. `deniedTitle` explains a refusal; while the+ * policy loads the action is refused without a reason yet.+ */+export const useConnectorConfigureGate = (connector: ConnectorWithTools, canEdit: boolean) => {+ const { t: tTool } = useTranslation('tool');+ const { t: ts } = useTranslation('setting');+ const { canManageCredentials, isPending, restrictedByPolicy } = useConnectorManageable(connector);++ const deniedTitle =+ canManageCredentials || isPending+ ? undefined+ : restrictedByPolicy+ ? ts('tools.connectorFeedback.manageOnly')+ : tTool(+ 'connector.manageOnlyCreator',+ 'Only the creator or a workspace owner can manage this connector',+ );++ return { allowed: canEdit && canManageCredentials, deniedTitle };+};diff --git a/src/features/SkillStore/SkillList/MCP/index.tsx b/src/features/SkillStore/SkillList/MCP/index.tsxindex cc47d20484e..e0a8ddeb271 100644--- a/src/features/SkillStore/SkillList/MCP/index.tsx+++ b/src/features/SkillStore/SkillList/MCP/index.tsx@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next';import { VirtuosoGrid } from 'react-virtuoso';import AsyncError from '@/components/AsyncError';+import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';import { useToolStore } from '@/store/tool';import Item from '../Community/Item';@@ -39,6 +40,8 @@ export const MCPList = memo(() => {}, [keywords, resetMCPPluginList]);const { error, isValidating } = useFetchMCPPluginList({ pageSize: 20, q: keywords });+ // Each item shows whether it is installed: a plugin row or a connector install+ useFetchInstalledPlugins();const allItems = list?.items ?? [];const hasSearchKeywords = Boolean(keywords && keywords.trim());diff --git a/src/hooks/useConnectorManagePolicy.test.ts b/src/hooks/useConnectorManagePolicy.test.tsindex 26baa88901f..181baa36fa7 100644--- a/src/hooks/useConnectorManagePolicy.test.ts+++ b/src/hooks/useConnectorManagePolicy.test.ts@@ -1,7 +1,7 @@import { renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { useConnectorManageable } from './useConnectorManagePolicy';+import { useConnectorManageable, useConnectorManageableChecker } from './useConnectorManagePolicy';const mocks = vi.hoisted(() => ({error: undefined as Error | undefined,@@ -14,9 +14,13 @@ vi.mock('@/libs/swr', () => ({useClientDataSWR: () => ({ data: mocks.policy, error: mocks.error }),}));-vi.mock('@/hooks/useResourceManageable', () => ({- useResourceManageable: (userId?: string | null) => !userId || userId === 'me',-}));+vi.mock('@/hooks/useResourceManageable', () => {+ const isCreatorOrOwner = (userId?: string | null) => !userId || userId === 'me';+ return {+ useResourceManageable: isCreatorOrOwner,+ useResourceManageableChecker: () => isCreatorOrOwner,+ };+});const manageable = (connector?: { agentId?: string | null; userId?: string | null }) =>renderHook(() => useConnectorManageable(connector)).result.current;@@ -78,3 +82,23 @@ describe('useConnectorManageable', () => {expect(manageable({ agentId: 'a1', userId: 'arvin' })).toMatchObject({ canManage: false });});});++describe('useConnectorManageableChecker', () => {+ beforeEach(() => {+ mocks.error = undefined;+ mocks.policy = { canEditPolicy: false, canManage: true, memberManage: 'all_members' };+ });++ const check = (connector: { agentId?: string | null; userId?: string | null }) =>+ renderHook(() => useConnectorManageableChecker()).result.current(connector);++ // One hook call answers for every row of a list, by the same rule+ it('answers each row as useConnectorManageable does', () => {+ for (const connector of [{ userId: 'me' }, { userId: 'arvin' }, { agentId: 'a1' }]) {+ expect(check(connector)).toEqual(manageable(connector));+ }++ mocks.policy = undefined;+ expect(check({ userId: 'me' })).toMatchObject({ canManageCredentials: false, isPending: true });+ });+});diff --git a/src/hooks/useConnectorManagePolicy.ts b/src/hooks/useConnectorManagePolicy.tsindex d2014eb86f8..1e5496f324c 100644--- a/src/hooks/useConnectorManagePolicy.ts+++ b/src/hooks/useConnectorManagePolicy.ts@@ -1,4 +1,6 @@-import { useResourceManageable } from '@/hooks/useResourceManageable';+import { useCallback } from 'react';++import { useResourceManageable, useResourceManageableChecker } from '@/hooks/useResourceManageable';import { useClientDataSWR } from '@/libs/swr';import {CONNECTOR_MANAGE_POLICY_SWR_KEY,@@ -30,19 +32,17 @@ export interface ConnectorManageable {restrictedByPolicy: boolean;}-/**- * Client mirror of the server's connector manage gates- * (`assertConnectorMaintainable` / `assertConnectorCredentialsManageable`).- * Actions are enabled only once the server-computed policy says they are- * allowed; a restricted viewer gets disabled controls with the reason on hover.- */-export const useConnectorManageable = (connector?: {+interface ConnectorManageRow {agentId?: string | null;userId?: string | null;-}): ConnectorManageable => {- const { data: policy, error } = useConnectorManagePolicy();- const isCreatorOrOwner = useResourceManageable(connector?.userId);+}+const resolveConnectorManageable = (+ connector: ConnectorManageRow | undefined,+ policy: ConnectorManagePolicy | undefined,+ policyError: unknown,+ isCreatorOrOwner: boolean,+): ConnectorManageable => {// Agent-scoped rows belong to that agent's setup and keep the creator rule.if (connector?.agentId)return {@@ -52,7 +52,7 @@ export const useConnectorManageable = (connector?: {restrictedByPolicy: false,};- if (!policy && !error)+ if (!policy && !policyError)return {canManage: false,canManageCredentials: false,@@ -70,3 +70,33 @@ export const useConnectorManageable = (connector?: {restrictedByPolicy: !canManage,};};++/**+ * Client mirror of the server's connector manage gates+ * (`assertConnectorMaintainable` / `assertConnectorCredentialsManageable`).+ * Actions are enabled only once the server-computed policy says they are+ * allowed; a restricted viewer gets disabled controls with the reason on hover.+ */+export const useConnectorManageable = (connector?: ConnectorManageRow): ConnectorManageable => {+ const { data: policy, error } = useConnectorManagePolicy();+ const isCreatorOrOwner = useResourceManageable(connector?.userId);++ return resolveConnectorManageable(connector, policy, error, isCreatorOrOwner);+};++/**+ * Callback variant of {@link useConnectorManageable} for lists that check many+ * connectors under one hook call, such as the chat input's tool picker.+ */+export const useConnectorManageableChecker = (): ((+ connector: ConnectorManageRow,+) => ConnectorManageable) => {+ const { data: policy, error } = useConnectorManagePolicy();+ const checkCreatorOrOwner = useResourceManageableChecker();++ return useCallback(+ (connector: ConnectorManageRow) =>+ resolveConnectorManageable(connector, policy, error, checkCreatorOrOwner(connector.userId)),+ [checkCreatorOrOwner, error, policy],+ );+};diff --git a/src/hooks/useFetchInstalledPlugins.test.ts b/src/hooks/useFetchInstalledPlugins.test.tsnew file mode 100644index 00000000000..79ae2e3f44e--- /dev/null+++ b/src/hooks/useFetchInstalledPlugins.test.ts@@ -0,0 +1,26 @@+import { renderHook } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { useFetchInstalledPlugins } from './useFetchInstalledPlugins';++const store = vi.hoisted(() => ({+ isConnectorsInit: false,+ useFetchConnectors: vi.fn(),+ useFetchInstalledPlugins: vi.fn(() => ({ isLoading: false })),+}));++vi.mock('@/store/tool', () => ({+ useToolStore: (selector: (s: typeof store) => unknown) => selector(store),+}));++describe('useFetchInstalledPlugins', () => {+ // `isPluginInstalled` reads plugin rows and connector installs: a view that+ // shows install state must load both, or a connector-only install reads as+ // not installed after a reload+ it('loads the connector list along with the installed plugin rows', () => {+ renderHook(() => useFetchInstalledPlugins());++ expect(store.useFetchInstalledPlugins).toHaveBeenCalledWith(true);+ expect(store.useFetchConnectors).toHaveBeenCalledWith(true);+ });+});diff --git a/src/hooks/useFetchInstalledPlugins.ts b/src/hooks/useFetchInstalledPlugins.tsindex 8f71ec98a2b..636821402bf 100644--- a/src/hooks/useFetchInstalledPlugins.ts+++ b/src/hooks/useFetchInstalledPlugins.ts@@ -1,7 +1,19 @@import { useToolStore } from '@/store/tool';+/**+ * Load what decides whether a plugin or MCP is installed: the legacy plugin+ * rows, and the connectors a marketplace MCP install now lands in+ * (`pluginSelectors.isPluginInstalled` reads both).+ */export const useFetchInstalledPlugins = () => {- const [useFetchInstalledPlugins] = useToolStore((s) => [s.useFetchInstalledPlugins]);+ // `isConnectorsInit` drops on a cache-scope switch: re-rendering then moves+ // the connector load to the new identity+ const [useFetchInstalledPlugins, useFetchConnectors] = useToolStore((s) => [+ s.useFetchInstalledPlugins,+ s.useFetchConnectors,+ s.isConnectorsInit,+ ]);+ useFetchConnectors(true);return useFetchInstalledPlugins(true);};diff --git a/src/libs/mcp/buildConnectorManifests.test.ts b/src/libs/mcp/buildConnectorManifests.test.tsindex 0ed52ef0f09..749fb372c40 100644--- a/src/libs/mcp/buildConnectorManifests.test.ts+++ b/src/libs/mcp/buildConnectorManifests.test.ts@@ -1,3 +1,5 @@+import { type AgentState, GeneralChatAgent } from '@lobechat/agent-runtime';+import { withMandatoryApprovalMark } from '@lobechat/const';import { describe, expect, it } from 'vitest';import type { DecryptedConnector } from '@/database/models/connector';@@ -73,3 +75,96 @@ describe('buildConnectorManifests mcpParams headers', () => {expect(params.headers).toBeUndefined();});});++describe('buildConnectorManifests cloud connectors', () => {+ it('routes a cloud connector to the cloud executor by identifier', () => {+ const connector = {+ ...httpConnector(null, { cloudEndPoint: 'https://cloud.example', customHeaders: { A: '1' } }),+ mcpConnectionType: 'cloud',+ mcpServerUrl: null,+ } as DecryptedConnector;++ expect(mcpParamsOf(connector)).toEqual({+ headers: { A: '1' },+ name: 'my-conn',+ type: 'cloud',+ url: 'https://cloud.example',+ });+ });+});++describe('buildConnectorManifests approval', () => {+ const cloudConnector = {+ ...httpConnector(null, { cloudEndPoint: 'https://cloud.example' }),+ mcpConnectionType: 'cloud',+ mcpServerUrl: null,+ } as DecryptedConnector;++ /** A tool as `syncToolsFromClientById` stores it from the market's manifest. */+ const syncedTool = (toolName: string, humanIntervention: unknown, permission: string) =>+ ({+ ...tool(),+ metadata: withMandatoryApprovalMark(null, humanIntervention),+ permission,+ toolName,+ }) as UserConnectorToolItem;++ /** What the runtime's approval gate does with one call under `approvalMode`. */+ const gate = async (manifests: ReturnType<typeof buildConnectorManifests>, apiName: string) => {+ const toolCalling = {+ apiName,+ arguments: '{}',+ id: `call-${apiName}`,+ identifier: 'my-conn',+ type: 'mcp',+ } as const;+ const now = new Date().toISOString();+ const state = {+ cost: { calculatedAt: now, currency: 'USD', total: 0 },+ createdAt: now,+ lastModified: now,+ messages: [],+ operationId: 'op',+ status: 'running',+ stepCount: 0,+ toolManifestMap: Object.fromEntries(manifests.map((m) => [m.identifier, m])),+ usage: {},+ userInterventionConfig: { allowList: [], approvalMode: 'auto-run' },+ } as unknown as AgentState;+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 10 },+ modelRuntimeConfig: { model: 'm', provider: 'p' },+ operationId: 'op',+ });+ const [instruction] = await agent.runner(+ {+ payload: { hasToolsCalling: true, parentMessageId: 'msg', toolsCalling: [toolCalling] },+ phase: 'llm_result',+ session: { messageCount: 0, sessionId: 'op', status: 'running', stepCount: 0 },+ } as any,+ state,+ );+ return (instruction as { type: string }).type;+ };++ // Auto-run skips `required`; a market `always` must still stop the call+ it('keeps a cloud tool the market marks always behind approval in auto-run', async () => {+ const manifests = buildConnectorManifests(+ [cloudConnector],+ [+ syncedTool('delete_repo', 'always', 'needs_approval'),+ syncedTool('purge', [{ match: { force: true }, policy: 'always' }], 'auto'),+ syncedTool('send_mail', 'required', 'needs_approval'),+ ],+ );++ expect(manifests[0].api.map((a) => [a.name, a.humanIntervention])).toEqual([+ ['delete_repo', 'always'],+ ['purge', 'always'],+ ['send_mail', 'required'],+ ]);+ expect(await gate(manifests, 'delete_repo')).toBe('request_human_approve');+ expect(await gate(manifests, 'purge')).toBe('request_human_approve');+ expect(await gate(manifests, 'send_mail')).toBe('call_tool');+ });+});diff --git a/src/libs/mcp/buildConnectorManifests.ts b/src/libs/mcp/buildConnectorManifests.tsindex 782cb77d861..59ecf4b5a88 100644--- a/src/libs/mcp/buildConnectorManifests.ts+++ b/src/libs/mcp/buildConnectorManifests.ts@@ -12,6 +12,8 @@ import type { UserConnectorToolItem } from '@/database/schemas';* - 'auto' → humanIntervention: undefined (AI calls freely)* - 'needs_approval' → humanIntervention: 'required' (human must confirm)* - 'disabled' → tool included with blocking description; AI knows it exists but is told it cannot be called+ * A tool whose manifest made approval mandatory (`metadata.mandatoryApproval`)+ * is `humanIntervention: 'always'` unless disabled: auto-run cannot skip it.*/export function buildConnectorManifests(connectors: DecryptedConnector[],@@ -66,6 +68,17 @@ function buildMcpParams(connector: DecryptedConnector) {const customHeaders = connector.metadata?.customHeaders as Record<string, string> | undefined;const mergedHeaders = headers || customHeaders ? { ...headers, ...customHeaders } : undefined;+ // A marketplace stdio server the market hosts: the tool executor calls it+ // through the market's cloud gateway by identifier.+ if (connector.mcpConnectionType === 'cloud') {+ return {+ headers: mergedHeaders,+ name: connector.identifier,+ type: 'cloud' as const,+ url: (connector.metadata?.cloudEndPoint as string | undefined) ?? '',+ };+ }+return {auth,headers: mergedHeaders,diff --git a/src/services/chat/mecha/contextFactProviders.test.ts b/src/services/chat/mecha/contextFactProviders.test.tsindex 70ece604e76..f6cf6688fa2 100644--- a/src/services/chat/mecha/contextFactProviders.test.ts+++ b/src/services/chat/mecha/contextFactProviders.test.ts@@ -29,6 +29,7 @@ beforeEach(() => {} as any);useToolStore.setState({composioServers: [],+ connectors: [],installedPlugins: [],lobehubSkillServers: [],uninstalledBuiltinTools: [],@@ -68,6 +69,37 @@ describe('createBrowserContextFactProviders', () => {expect(agentService.queryAgents).toHaveBeenCalledTimes(1);});+ // Installs now land only in user_connectors: a connector-only custom MCP+ // must still reach the builder's inventory, once per identifier.+ it('lists custom connectors beside legacy custom plugin rows', async () => {+ useToolStore.setState({+ connectors: [+ {+ identifier: 'repo-mcp',+ metadata: { description: 'Repo tools' },+ name: 'Repo',+ sourceType: 'custom',+ },+ { identifier: 'my-mcp', metadata: null, name: '', sourceType: 'custom' },+ { identifier: 'market-mcp', metadata: null, name: 'Docs', sourceType: 'marketplace' },+ ],+ installedPlugins: [+ {+ identifier: 'my-mcp',+ manifest: { meta: { description: 'Stale', title: 'Old title' } },+ type: 'customPlugin',+ },+ { identifier: 'legacy-mcp', manifest: { meta: { title: 'Legacy' } }, type: 'customPlugin' },+ ],+ } as any);++ await expect(createBrowserContextFactProviders().listCustomPlugins!()).resolves.toEqual([+ { description: 'Repo tools', identifier: 'repo-mcp', name: 'Repo', type: 'custom' },+ { description: undefined, identifier: 'my-mcp', name: 'my-mcp', type: 'custom' },+ { description: undefined, identifier: 'legacy-mcp', name: 'Legacy', type: 'custom' },+ ]);+ });+it('treats only active Composio connections and every installed LobeHub skill provider as connected', async () => {useToolStore.setState({composioServers: [diff --git a/src/services/chat/mecha/contextFactProviders.ts b/src/services/chat/mecha/contextFactProviders.tsindex ce489765477..08dcbd14106 100644--- a/src/services/chat/mecha/contextFactProviders.ts+++ b/src/services/chat/mecha/contextFactProviders.ts@@ -1,4 +1,5 @@import { AGENT_PLAN_FILE_TYPE, isDesktop } from '@lobechat/const';+import type { AvailablePluginInfo } from '@lobechat/context-engine';import type { ContextFactProviders, ContextFactRequest, CredentialSummary } from '@lobechat/mecha';import { type AgentShareVisitorContext, getActivePluginIds } from '@lobechat/types';@@ -27,6 +28,7 @@ import {pluginSelectors,} from '@/store/tool/selectors';import { ComposioServerStatus } from '@/store/tool/slices/composioStore';+import { connectorSelectors } from '@/store/tool/slices/connector';import { getUserStoreState } from '@/store/user';import { userGeneralSettingsSelectors, userProfileSelectors } from '@/store/user/selectors';@@ -199,13 +201,31 @@ export const createBrowserContextFactProviders = ({return result.data as CredentialSummary[];},- listCustomPlugins: async () =>- pluginSelectors.installedCustomPluginMetaList(getToolStoreState()).map((plugin) => ({- description: plugin.description,- identifier: plugin.identifier,- name: plugin.title || plugin.identifier,- type: 'custom' as const,- })),+ // Custom connectors (every install now) and the custom plugin rows older+ // installs left, one entry per identifier: the server provider's rule.+ listCustomPlugins: async () => {+ const toolState = getToolStoreState();+ const plugins = new Map<string, AvailablePluginInfo>();+ for (const connector of connectorSelectors.customConnectors(toolState)) {+ const description = connector.metadata?.description;+ plugins.set(connector.identifier, {+ description: typeof description === 'string' ? description : undefined,+ identifier: connector.identifier,+ name: connector.name || connector.identifier,+ type: 'custom',+ });+ }+ for (const plugin of pluginSelectors.installedCustomPluginMetaList(toolState)) {+ if (plugins.has(plugin.identifier)) continue;+ plugins.set(plugin.identifier, {+ description: plugin.description,+ identifier: plugin.identifier,+ name: plugin.title || plugin.identifier,+ type: 'custom',+ });+ }+ return [...plugins.values()];+ },listEnabledProviders: async () =>(getAiInfraStoreState().enabledChatModelList || []).map((provider) => ({diff --git a/src/services/ensureAgentMarketSkills.test.ts b/src/services/ensureAgentMarketSkills.test.tsindex df311bafb98..83264ed2684 100644--- a/src/services/ensureAgentMarketSkills.test.ts+++ b/src/services/ensureAgentMarketSkills.test.ts@@ -112,6 +112,35 @@ describe('ensureAgentMarketSkills', () => {expect(ensureFromMarket).toHaveBeenCalledWith(['my-own-skill', 'fresh-skill']);});+ // An MCP pinned to an agent is no Market skill: a `notSkill` answer for it+ // would let the profile's stale-plugin cleanup unpin it+ it('leaves out MCP connectors: custom ones and finished marketplace installs', async () => {+ const state = useToolStore.getState();+ vi.spyOn(useToolStore, 'getState').mockReturnValue({+ ...state,+ connectors: [+ { identifier: 'custom-mcp', mcpServerUrl: 'https://c.example.com', sourceType: 'custom' },+ {+ identifier: 'market-mcp',+ mcpConnectionType: 'cloud',+ metadata: { marketplaceInstalled: true },+ sourceType: 'marketplace',+ },+ // A canceled install's row is not an install+ {+ identifier: 'unfinished-mcp',+ mcpServerUrl: 'https://u.example.com',+ metadata: {},+ sourceType: 'marketplace',+ },+ ],+ } as unknown as ReturnType<typeof useToolStore.getState>);++ await ensureAgentMarketSkills(['custom-mcp', 'market-mcp', 'unfinished-mcp']);++ expect(ensureFromMarket).toHaveBeenCalledWith(['unfinished-mcp']);+ });+it('still asks the server about installed Market skills while the list is only the persisted copy', async () => {// A hydrated list can predate a skill installed elsewhere; the server is// idempotent and answers `installed` for the ones already there.diff --git a/src/services/ensureAgentMarketSkills.ts b/src/services/ensureAgentMarketSkills.tsindex e813ad3518a..ff74ca2e051 100644--- a/src/services/ensureAgentMarketSkills.ts+++ b/src/services/ensureAgentMarketSkills.ts@@ -61,7 +61,8 @@ const getResolvedIdentifiers = (): Set<string> => {for (const plugin of pluginSelectors.installedPluginMetaList(state)) {resolved.add(plugin.identifier);}- for (const connector of connectorSelectors.customConnectors(state)) {+ // Custom MCP connectors and finished marketplace installs+ for (const connector of connectorSelectors.userMcpConnectors(state)) {resolved.add(connector.identifier);}// Catalog membership does not depend on which providers this deployment enables.diff --git a/src/services/mcp.callReport.test.ts b/src/services/mcp.callReport.test.tsnew file mode 100644index 00000000000..8993d27edd5--- /dev/null+++ b/src/services/mcp.callReport.test.ts@@ -0,0 +1,184 @@+import { type ChatToolPayload } from '@lobechat/types';+import superjson from 'superjson';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { lambdaClient } from '@/libs/trpc/client';++import { discoverService } from './discover';+import { mcpService } from './mcp';++/**+ * Marketplace MCP servers used to run as plugins, and the Market was told about+ * each call: by the server for the calls it ran, by this client for the ones a+ * desktop ran itself. Installed as connectors, they are reported the same way.+ */++const environment = vi.hoisted(() => ({ isDesktop: true }));+const ipc = vi.hoisted(() => ({ callTool: vi.fn() }));+const toolState = vi.hoisted(() => ({ current: {} as Record<string, unknown> }));+const pluginLookup = vi.hoisted(() => ({+ getCustomPluginById: vi.fn(() => () => undefined as unknown),+ getInstalledPluginById: vi.fn(() => () => undefined as unknown),+}));++vi.mock('@lobechat/const', async (importOriginal) => ({+ ...((await importOriginal()) as Record<string, unknown>),+ CURRENT_VERSION: '2.0.0',+ get isDesktop() {+ return environment.isDesktop;+ },+}));+vi.mock('@/store/serverConfig/store', () => ({+ getServerConfigStoreState: () => ({+ featureFlags: { enableMcpApps: false },+ serverConfig: { deviceGatewayConfigured: true },+ }),+}));+vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ connector: { callTool: { mutate: vi.fn() }, getForEdit: { query: vi.fn() } },+ },+ toolsClient: { mcp: { callTool: { mutate: vi.fn() } } },+}));+vi.mock('@/utils/electron/ipc', () => ({ ensureElectronIpc: () => ({ mcp: ipc }) }));+vi.mock('./discover', () => ({+ discoverService: {+ reportPluginCall: vi.fn().mockResolvedValue(undefined),+ safeInjectMPToken: vi.fn().mockResolvedValue(undefined),+ },+}));+vi.mock('@/store/tool/store', () => ({ getToolStoreState: () => toolState.current }));+vi.mock('@/store/tool/selectors', () => ({ pluginSelectors: pluginLookup }));++const payload = {+ apiName: 'read_file',+ arguments: '{"path":"a.txt"}',+ id: 'call-1',+ identifier: 'files-mcp',+ type: 'standalone',+} as ChatToolPayload;+const marketplace = {+ id: 'connector-id',+ identifier: 'files-mcp',+ isEnabled: true,+ mcpConnectionType: 'stdio',+ metadata: { marketplaceInstalled: true, version: '1.2.0' },+ sourceType: 'marketplace',+ status: 'connected',+};+const detail = {+ ...marketplace,+ mcpStdioConfig: { args: ['files-mcp'], command: 'npx' },+ tools: [{ permission: 'auto', toolName: 'read_file' }],+};+const localResult = {+ content: 'contents',+ state: { content: [{ text: 'contents', type: 'text' }] },+ success: true,+};++beforeEach(() => {+ vi.clearAllMocks();+ environment.isDesktop = true;+ toolState.current = { connectors: [marketplace] };+ pluginLookup.getInstalledPluginById.mockReturnValue(() => undefined);+ vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue(detail as never);+ ipc.callTool.mockResolvedValue(superjson.serialize(localResult));+});++describe('Market call reports for connector calls', () => {+ it('reports a marketplace stdio call this desktop ran, with its session and version', async () => {+ await mcpService.invokeMcpToolCall(payload, { topicId: 'tpc_1' });++ expect(discoverService.reportPluginCall).toHaveBeenCalledTimes(1);+ expect(discoverService.reportPluginCall).toHaveBeenCalledWith(+ expect.objectContaining({+ identifier: 'files-mcp',+ isCustomPlugin: false,+ metadata: { appVersion: '2.0.0', command: 'npx', mcpType: 'stdio' },+ methodName: 'read_file',+ methodType: 'tool',+ responseSizeBytes: expect.any(Number),+ sessionId: 'tpc_1',+ success: true,+ version: '1.2.0',+ }),+ );+ });++ it('reports a failed local call as failed and still throws its error', async () => {+ ipc.callTool.mockRejectedValue(new Error('process exited'));++ await expect(mcpService.invokeMcpToolCall(payload, {})).rejects.toThrow('process exited');++ expect(discoverService.reportPluginCall).toHaveBeenCalledWith(+ expect.objectContaining({+ errorCode: 'CALL_FAILED',+ errorMessage: 'process exited',+ responseSizeBytes: 0,+ success: false,+ }),+ );+ });++ it("does not report a custom connector's local call", async () => {+ const custom = {+ ...marketplace,+ metadata: { desktopStdioExecution: true },+ sourceType: 'custom',+ };+ toolState.current = { connectors: [custom] };+ vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue({+ ...detail,+ ...custom,+ } as never);++ await mcpService.invokeMcpToolCall(payload, {});++ expect(ipc.callTool).toHaveBeenCalled();+ expect(discoverService.reportPluginCall).not.toHaveBeenCalled();+ });++ // The connector route reports the calls the server runs+ it('sends the session to the connector route and reports nothing itself', async () => {+ environment.isDesktop = false;+ toolState.current = {+ connectors: [+ { ...marketplace, mcpConnectionType: 'http', mcpServerUrl: 'https://a.example' },+ ],+ };+ vi.mocked(lambdaClient.connector.callTool.mutate).mockResolvedValue(localResult as never);++ await mcpService.invokeMcpToolCall(payload, { topicId: 'tpc_1' });++ expect(lambdaClient.connector.callTool.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ identifier: 'files-mcp', topicId: 'tpc_1' }),+ expect.anything(),+ );+ expect(discoverService.reportPluginCall).not.toHaveBeenCalled();+ });+});++describe('Market call reports for plugin calls', () => {+ it('still reports a stdio plugin call this desktop ran', async () => {+ toolState.current = { connectors: [] };+ pluginLookup.getInstalledPluginById.mockReturnValue(() => ({+ customParams: { mcp: { args: ['files-mcp'], command: 'npx', type: 'stdio' } },+ identifier: 'files-mcp',+ manifest: { meta: { title: 'Files' }, version: '0.9.0' },+ }));++ await mcpService.invokeMcpToolCall(payload, { topicId: 'tpc_2' });++ expect(discoverService.reportPluginCall).toHaveBeenCalledWith(+ expect.objectContaining({+ identifier: 'files-mcp',+ isCustomPlugin: false,+ metadata: { appVersion: '2.0.0', command: 'npx', mcpType: 'stdio' },+ sessionId: 'tpc_2',+ success: true,+ version: '0.9.0',+ }),+ );+ });+});diff --git a/src/services/mcp.test.ts b/src/services/mcp.test.tsindex ce089a1ad09..62edf10ce29 100644--- a/src/services/mcp.test.ts+++ b/src/services/mcp.test.ts@@ -162,6 +162,93 @@ describe('MCPService', () => {);});+ it('runs a market-hosted (cloud) connector through the server connector route', async () => {+ const { lambdaClient } = await import('@/libs/trpc/client');+ mockGetToolStoreState.mockReturnValue({+ connectors: [+ {+ id: 'cloud-id',+ identifier: 'cloud-mcp',+ isEnabled: true,+ mcpConnectionType: 'cloud',+ mcpServerUrl: null,+ },+ ],+ });+ vi.mocked(lambdaClient.connector.callTool.mutate).mockResolvedValue({+ content: 'ok',+ success: true,+ } as never);++ await mcpService.invokeMcpToolCall(+ { apiName: 'search', arguments: '{}', identifier: 'cloud-mcp' } as ChatToolPayload,+ {},+ );++ expect(lambdaClient.connector.callTool.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ identifier: 'cloud-mcp', toolName: 'search' }),+ expect.anything(),+ );+ });++ describe('a marketplace connector reinstalled over a plugin row', () => {+ const payload = {+ apiName: 'search',+ arguments: '{}',+ identifier: 'market-mcp',+ } as ChatToolPayload;+ const legacyPlugin = {+ customParams: { mcp: { type: 'http', url: 'https://old.example.com/mcp' } },+ };+ const withConnector = (over: Record<string, unknown>) => {+ mockGetToolStoreState.mockReturnValue({+ connectors: [+ {+ id: 'market-id',+ identifier: 'market-mcp',+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://new.example.com/mcp',+ metadata: {},+ sourceType: 'marketplace',+ ...over,+ },+ ],+ });+ mockPluginSelectors.getInstalledPluginById.mockReturnValue(() => legacyPlugin);+ };++ // Its tool rows may not match the new endpoint until the install finishes+ it('keeps calling the plugin while the reinstall is pending', async () => {+ const { lambdaClient, toolsClient } = await import('@/libs/trpc/client');+ withConnector({ status: 'disconnected' });+ vi.mocked(toolsClient.mcp.callTool.mutate).mockResolvedValue('plugin result');++ await expect(mcpService.invokeMcpToolCall(payload, {})).resolves.toBe('plugin result');++ expect(lambdaClient.connector.callTool.mutate).not.toHaveBeenCalled();+ const [request] = vi.mocked(toolsClient.mcp.callTool.mutate).mock.calls[0];+ expect(request.params).toMatchObject({ url: 'https://old.example.com/mcp' });+ });++ it('calls the connector once its install has finished', async () => {+ const { lambdaClient, toolsClient } = await import('@/libs/trpc/client');+ withConnector({ metadata: { marketplaceInstalled: true }, status: 'connected' });+ vi.mocked(lambdaClient.connector.callTool.mutate).mockResolvedValue({+ content: 'ok',+ success: true,+ } as never);++ await mcpService.invokeMcpToolCall(payload, {});++ expect(lambdaClient.connector.callTool.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ identifier: 'market-mcp' }),+ expect.anything(),+ );+ expect(toolsClient.mcp.callTool.mutate).not.toHaveBeenCalled();+ });+ });+describe('stdio connectors', () => {const payload: ChatToolPayload = {id: 'local-call',@@ -234,6 +321,55 @@ describe('MCPService', () => {},);+ // Marketplace and protocol-link stdio servers ran over IPC as plugins;+ // installed as connectors they still do, while the connector route refuses stdio+ const marketplace = {+ metadata: { marketplaceInstalled: true },+ sourceType: 'marketplace',+ status: 'connected',+ };+ const protocolLink = { metadata: { desktopStdioExecution: true }, sourceType: 'custom' };+ it.each([+ { gateway: true, install: 'marketplace', source: marketplace },+ { gateway: undefined, install: 'marketplace', source: marketplace },+ { gateway: true, install: 'protocol-link', source: protocolLink },+ ])(+ 'runs a $install stdio install over local IPC when gateway=$gateway',+ async ({ gateway, source }) => {+ environment.deviceGatewayConfigured = gateway;+ mockGetToolStoreState.mockReturnValue({ connectors: [{ ...connector, ...source }] });+ const { lambdaClient } = await import('@/libs/trpc/client');+ const result = {+ content: 'local result',+ state: { content: [{ type: 'text', text: 'local result' }] },+ success: true,+ };+ mockElectronIpc.mcp.callTool.mockResolvedValue(superjson.serialize(result));++ await expect(mcpService.invokeMcpToolCall(payload, {})).resolves.toEqual(result);+ expect(lambdaClient.connector.getForEdit.query).toHaveBeenCalledWith({+ id: connector.id,+ });+ expect(lambdaClient.connector.callTool.mutate).not.toHaveBeenCalled();+ },+ );++ it('sends a marketplace stdio install to the server route on the web', async () => {+ environment.isDesktop = false;+ mockGetToolStoreState.mockReturnValue({+ connectors: [{ ...connector, ...marketplace }],+ });+ const { lambdaClient } = await import('@/libs/trpc/client');+ vi.mocked(lambdaClient.connector.callTool.mutate).mockResolvedValue({+ success: true,+ } as never);++ await mcpService.invokeMcpToolCall(payload, {});++ expect(mockElectronIpc.mcp.callTool).not.toHaveBeenCalled();+ expect(lambdaClient.connector.callTool.mutate).toHaveBeenCalled();+ });+it.each([{ ...detail, isEnabled: false },{ ...detail, tools: [] },diff --git a/src/services/mcp.ts b/src/services/mcp.tsindex 5eb7478ba92..0b509828a06 100644--- a/src/services/mcp.ts+++ b/src/services/mcp.ts@@ -1,4 +1,10 @@-import { CURRENT_VERSION, isDesktop } from '@lobechat/const';+import {+ CURRENT_VERSION,+ hasCallableMcpEndpoint,+ isDesktop,+ isMarketplaceInstallRunnable,+ keepsDesktopStdioExecution,+} from '@lobechat/const';import {getMcpServerFingerprint,isSyncedMcpToolVisibleTo,@@ -42,6 +48,48 @@ function calculateObjectSizeBytes(obj: any): number {}}+/**+ * Report a tool call this machine ran to the Market, without affecting the+ * call. The server reports the calls it runs (`tools.mcp.callTool`,+ * `market.callCloudMcpEndpoint`, `connector.callTool`).+ */+const reportLocalCall = (call: {+ args?: string;+ command?: string;+ customPluginInfo?: CallReportRequest['customPluginInfo'];+ failure?: unknown;+ identifier: string;+ isCustomPlugin: boolean;+ mcpType?: string;+ result?: MCPToolCallResult;+ sessionId?: string;+ startTime: number;+ toolName: string;+ version: string;+}) => {+ const success = call.failure === undefined;+ const reportData: CallReportRequest = {+ callDurationMs: Date.now() - call.startTime,+ customPluginInfo: call.customPluginInfo,+ errorCode: success ? undefined : 'CALL_FAILED',+ errorMessage: success ? undefined : (call.failure as Error)?.message,+ identifier: call.identifier,+ isCustomPlugin: call.isCustomPlugin,+ metadata: { appVersion: CURRENT_VERSION, command: call.command, mcpType: call.mcpType },+ methodName: call.toolName,+ methodType: 'tool' as const,+ requestSizeBytes: calculateObjectSizeBytes(safeParseJSON(call.args) || call.args),+ responseSizeBytes: success && call.result ? calculateObjectSizeBytes(call.result.state) : 0,+ sessionId: call.sessionId,+ success,+ version: call.version,+ };++ discoverService.reportPluginCall(reportData).catch((reportError) => {+ console.warn('Failed to report MCP tool call:', reportError);+ });+};+/** A tool a local MCP server lists, as the desktop main process reports it. */export interface LocalMcpTool {description?: string;@@ -217,21 +265,28 @@ class MCPService {// Connector-first: HTTP connectors use their server-held credentials.// Standalone desktop stdio connectors use local IPC; configured device- // gateways keep the existing server route for conversation calls.+ // gateways keep the existing server route for conversation calls, except+ // for marketplace and protocol-link stdio installs, which ran here as plugins.// Only connectors with a real MCP endpoint are routed here — Lobehub/Composio// skills synced into the connector store have no mcpServerUrl and keep their// original executor path.const { connectorSelectors } = await import('@/store/tool/slices/connector/selectors');- const connector = connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(s);const installPlugin = pluginSelectors.getInstalledPluginById(identifier)(s);const customPlugin = pluginSelectors.getCustomPluginById(identifier)(s);const plugin = installPlugin || customPlugin;+ // An unfinished marketplace install (an interrupted reinstall over a plugin+ // row, a late OAuth callback after a cancel) is not routed to: its tool rows+ // may not match its endpoint. A plugin row still serves the call.+ const resolved = connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(s);+ const connector =+ resolved && isMarketplaceInstallRunnable(resolved, !!plugin) ? resolved : undefined;// An agent's own connectors may not be loaded on the client yet; with no// plugin to fall back to, let the server resolve the identifier for the agent.+ // A market-hosted (cloud) connector has no URL: the server's connector route runs it.const isConnector = connector- ? connector.isEnabled && (!!connector.mcpServerUrl || connector.mcpConnectionType === 'stdio')+ ? connector.isEnabled && hasCallableMcpEndpoint(connector): !!agentId && !plugin;if (isConnector) {const { lambdaClient } = await import('@/libs/trpc/client');@@ -239,7 +294,10 @@ class MCPService {connector &&isDesktop &&connector.mcpConnectionType === 'stdio' &&- (fromMcpApp || getServerConfigStoreState()?.serverConfig.deviceGatewayConfigured === false);+ (fromMcpApp ||+ // These stdio servers ran on this desktop as plugins, gateway or not+ keepsDesktopStdioExecution(connector) ||+ getServerConfigStoreState()?.serverConfig.deviceGatewayConfigured === false);// A view's calls run where its result was producedif (fromMcpApp && !!runsHere !== !!onThisDevice) throw new Error(VIEW_SITE_MISMATCH);if (runsHere) {@@ -270,22 +328,49 @@ class MCPService {throw new Error(VIEW_SERVER_MOVED);}throwIfAborted(signal);- const result = await ensureElectronIpc().mcp.callTool(- serializeMcpIpcPayload({- args: safeParseJSON(args) ?? {},- env: config.env,- ...(fromMcpApp && { fromApp: true }),- mcpApps,- params: {- args: config.args ?? [],+ const startTime = Date.now();+ let failure: unknown;+ let result: MCPToolCallResult | undefined;+ try {+ const serialized = await ensureElectronIpc().mcp.callTool(+ serializeMcpIpcPayload({+ args: safeParseJSON(args) ?? {},+ env: config.env,+ ...(fromMcpApp && { fromApp: true }),+ mcpApps,+ params: {+ args: config.args ?? [],+ command: config.command,+ name: detail.identifier,+ type: 'stdio',+ },+ toolName: apiName,+ }),+ );+ result = await markLocalView(deserializeMcpIpcPayload<MCPToolCallResult>(serialized));+ return result;+ } catch (error) {+ failure = error ?? new Error('MCP tool call failed');+ throw error;+ } finally {+ // A marketplace server's calls are reported as its plugin's were+ if (connector.sourceType === 'marketplace') {+ const version = (detail.metadata as { version?: unknown } | null)?.version;+ reportLocalCall({+ args,command: config.command,- name: detail.identifier,- type: 'stdio',- },- toolName: apiName,- }),- );- return markLocalView(deserializeMcpIpcPayload<MCPToolCallResult>(result));+ failure,+ identifier,+ isCustomPlugin: false,+ mcpType: 'stdio',+ result,+ sessionId: topicId,+ startTime,+ toolName: apiName,+ version: typeof version === 'string' ? version : 'unknown',+ });+ }+ }}try {return (await lambdaClient.connector.callTool.mutate(@@ -296,6 +381,7 @@ class MCPService {...(fromMcpApp && { fromApp: true, server }),identifier,toolName: apiName,+ topicId,},{ signal },)) as MCPToolCallResult;@@ -373,9 +459,7 @@ class MCPService {// Record call start timeconst callStartTime = Date.now();- let success = false;- let errorCode: string | undefined;- let errorMessage: string | undefined;+ let failure: unknown;let result: MCPToolCallResult | undefined;try {@@ -421,12 +505,9 @@ class MCPService {result = await toolsClient.mcp.callTool.mutate(data, { signal });}- success = true;return result;} catch (error) {- const err = error as Error;- errorCode = 'CALL_FAILED';- errorMessage = err.message;+ failure = error ?? new Error('MCP tool call failed');// Rethrow error, maintain original error handling logicthrow error;@@ -435,40 +516,19 @@ class MCPService {// Cloud type: reporting is handled by server-side via market.callCloudMcpEndpoint// Only report from frontend for calls that ran on this machine (desktop only)if (isStdio || isLocalHttp) {- const callEndTime = Date.now();- const callDurationMs = callEndTime - callStartTime;-- // Calculate request size- const inputParams = safeParseJSON(args) || args;- const requestSizeBytes = calculateObjectSizeBytes(inputParams);- // Calculate response size- const responseSizeBytes = success && result ? calculateObjectSizeBytes(result.state) : 0;-- // Construct report data- const reportData: CallReportRequest = {- callDurationMs,+ reportLocalCall({+ args,+ command: plugin.customParams?.mcp?.command,customPluginInfo: meta.customPluginInfo,- errorCode,- errorMessage,+ failure,identifier,isCustomPlugin,- metadata: {- appVersion: CURRENT_VERSION,- command: plugin.customParams?.mcp?.command,- mcpType: plugin.customParams?.mcp?.type,- },- methodName: apiName,- methodType: 'tool' as const,- requestSizeBytes,- responseSizeBytes,+ mcpType: plugin.customParams?.mcp?.type,+ result,sessionId: topicId,- success,+ startTime: callStartTime,+ toolName: apiName,version: meta.version,- };-- // Asynchronously report without affecting main flow- discoverService.reportPluginCall(reportData).catch((reportError) => {- console.warn('Failed to report MCP tool call:', reportError);});}}@@ -519,22 +579,29 @@ class MCPService {}const { connectorSelectors } = await import('@/store/tool/slices/connector/selectors');- const connector = connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(s);+ const resolved = connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(s);// Same test as `invokeMcpToolCall`: only an enabled connector with its own- // endpoint serves the view. Any other (e.g. the endpoint-less row a plugin's- // tools are synced to) leaves it to the plugin.- const connectorServes =- !!connector?.isEnabled &&- (!!connector.mcpServerUrl || connector.mcpConnectionType === 'stdio');+ // endpoint and a finished install serves the view. Any other (e.g. the+ // endpoint-less row a plugin's tools are synced to) leaves it to the plugin.+ const serves = (c: typeof resolved, hasPluginRow: boolean) =>+ !!c?.isEnabled &&+ (!!c.mcpServerUrl || c.mcpConnectionType === 'stdio') &&+ isMarketplaceInstallRunnable(c, hasPluginRow);// A conversation opened cold has not loaded the installed plugins yet, and an// unloaded list would lose a plugin's view or send it to the connector route.// Load the server's records first, as the tool call did before it ran.- if (!connectorServes && !pluginSelectors.isInstalledPluginsServerConfirmed(s)) {+ if (!serves(resolved, false) && !pluginSelectors.isInstalledPluginsServerConfirmed(s)) {await s.refreshPlugins();s = getToolStoreState();}+ const plugin =+ pluginSelectors.getInstalledPluginById(identifier)(s) ||+ pluginSelectors.getCustomPluginById(identifier)(s);+ const connectorServes = serves(resolved, !!plugin);+ const connector = connectorServes ? resolved : undefined;+// Stdio connectors run on a desktop app, never on the server, so only the// desktop can read their view: it spawns the same command over IPC.if (connectorServes && connector?.mcpConnectionType === 'stdio') {@@ -572,10 +639,6 @@ class MCPService {return deserializeMcpIpcPayload(result) as ReadResourceResult;}- const plugin =- pluginSelectors.getInstalledPluginById(identifier)(s) ||- pluginSelectors.getCustomPluginById(identifier)(s);-// Same resolution as `invokeMcpToolCall`: the view comes from the connector// the tool ran on. The agent's lists are loaded by now, so an identifier// with no connector here has none on the server either.diff --git a/src/services/plugin/index.ts b/src/services/plugin/index.tsindex 6f45728bdfd..342b464d4a6 100644--- a/src/services/plugin/index.ts+++ b/src/services/plugin/index.ts@@ -12,6 +12,10 @@ export interface InstallPluginParams {}export class PluginService {+ /**+ * @deprecated No in-app caller: marketplace MCPs install as connectors+ * (`connector.create`). Kept until the legacy create routes are removed.+ */installPlugin = async (plugin: InstallPluginParams): Promise<void> => {await lambdaClient.plugin.createOrInstallPlugin.mutate(plugin);};@@ -24,6 +28,10 @@ export class PluginService {await lambdaClient.plugin.removePlugin.mutate({ id: identifier });};+ /**+ * @deprecated No in-app caller: custom MCPs are added as connectors+ * (`connector.create`). Kept until the legacy create routes are removed.+ */createCustomPlugin = async (customPlugin: LobeToolCustomPlugin): Promise<void> => {await lambdaClient.plugin.createPlugin.mutate({ ...customPlugin, type: 'customPlugin' });};diff --git a/src/store/chat/slices/plugin/actions/internals.test.ts b/src/store/chat/slices/plugin/actions/internals.test.tsnew file mode 100644index 00000000000..42d17f299b9--- /dev/null+++ b/src/store/chat/slices/plugin/actions/internals.test.ts@@ -0,0 +1,73 @@+import { ToolNameResolver } from '@lobechat/context-engine';+import { beforeEach, describe, expect, it } from 'vitest';++import { useToolStore } from '@/store/tool';++import { PluginInternalsActionImpl } from './internals';++// Marketplace and custom MCP installs land only in `user_connectors` now. The+// tools engine offers their tools; the names it generated must resolve back.+const identifier = 'acceptance-notes-mcp-server';+const apiName = 'search_notes_by_keyword_and_date_range';+const tool = {+ crudType: 'read',+ description: 'Search notes',+ displayName: null,+ id: 't1',+ inputSchema: { properties: { q: { type: 'string' } }, type: 'object' },+ permission: 'auto',+ toolName: apiName,+ userConnectorId: 'c1',+};+const marketplaceConnector = {+ id: 'c1',+ identifier,+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://notes.example.com/mcp',+ metadata: { marketplaceInstalled: true },+ name: 'Acceptance Notes',+ sourceType: 'marketplace',+ status: 'connected',+ tools: [tool],+};++const transform = (name: string) =>+ new PluginInternalsActionImpl(+ () => {},+ () => ({}) as never,+ ).internal_transformToolCalls([+ { function: { arguments: '{"q":"x"}', name }, id: 'call-1', type: 'function' },+ ]);++beforeEach(() => {+ useToolStore.setState({ connectors: [], installedPlugins: [] } as never);+});++describe('internal_transformToolCalls with connector-only MCPs', () => {+ it("resolves a connector tool's MD5-hashed wire name back to the connector", () => {+ useToolStore.setState({ connectors: [marketplaceConnector] } as never);+ const wireName = new ToolNameResolver().generate(identifier, apiName, 'mcp');+ expect(wireName).toContain('MD5HASH_');++ const [payload] = transform(wireName);++ expect(payload).toMatchObject({+ apiName,+ arguments: '{"q":"x"}',+ identifier,+ source: 'mcp',+ type: 'mcp',+ });+ });++ it('does not resolve the tools of an unfinished marketplace install', () => {+ useToolStore.setState({+ connectors: [{ ...marketplaceConnector, metadata: {}, status: 'disconnected' }],+ } as never);+ const wireName = new ToolNameResolver().generate(identifier, apiName, 'mcp');++ // Its tools are not offered either, so the hashed API name stays opaque+ expect(transform(wireName)[0]?.apiName).not.toBe(apiName);+ });+});diff --git a/src/store/chat/slices/plugin/actions/internals.ts b/src/store/chat/slices/plugin/actions/internals.tsindex 23c9633d544..b7422beae87 100644--- a/src/store/chat/slices/plugin/actions/internals.ts+++ b/src/store/chat/slices/plugin/actions/internals.ts@@ -8,6 +8,7 @@ import {composioStoreSelectors,lobehubSkillStoreSelectors,pluginSelectors,+ toolSelectors,} from '@/store/tool/selectors';import { type StoreSetter } from '@/store/types';@@ -49,6 +50,13 @@ export class PluginInternalsActionImpl {}}+ // MCP connectors (every install now): the tools engine lets one replace a+ // same-named plugin, so the names it offered come from the connector+ for (const manifest of toolSelectors.executableConnectorManifests(toolStoreState)) {+ manifests[manifest.identifier] = manifest;+ sourceMap[manifest.identifier] = 'mcp';+ }+// Get all builtin toolsfor (const tool of builtinTools) {if (tool.manifest) {diff --git a/src/store/tool/selectors/tool.test.ts b/src/store/tool/selectors/tool.test.tsindex 2d9708c8a2b..67f855d96e0 100644--- a/src/store/tool/selectors/tool.test.ts+++ b/src/store/tool/selectors/tool.test.ts@@ -209,3 +209,76 @@ describe('toolSelectors', () => {});});});++// Marketplace and custom MCP installs land only in `user_connectors` now: chat+// must discover and activate them the way it did their plugin rows+describe('MCP connectors in tool discovery', () => {+ const connectorTool = (toolName: string) => ({+ crudType: 'read',+ description: `${toolName} tool`,+ displayName: null,+ id: toolName,+ inputSchema: { properties: {}, type: 'object' },+ permission: 'auto',+ toolName,+ userConnectorId: 'c',+ });+ const marketplace = (identifier: string, patch: Record<string, unknown> = {}) => ({+ id: identifier,+ identifier,+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: `https://${identifier}.example.com/mcp`,+ metadata: { marketplaceInstalled: true },+ name: `${identifier} name`,+ sourceType: 'marketplace',+ status: 'connected',+ tools: [connectorTool('search')],+ ...patch,+ });+ const state = (connectors: unknown[]) =>+ ({ ...mockState, connectors }) as unknown as ToolStoreState;++ it('lists a finished marketplace install and a custom connector', () => {+ const s = state([+ marketplace('notes-mcp'),+ marketplace('my-custom', { metadata: {}, sourceType: 'custom' }),+ ]);++ const ids = toolSelectors.availableToolsForDiscovery(s).map((tool) => tool.identifier);++ expect(ids).toEqual(expect.arrayContaining(['notes-mcp', 'my-custom']));+ expect(toolSelectors.availableToolsForDiscovery(s)).toContainEqual({+ description: 'notes-mcp name connector with 1 tools',+ identifier: 'notes-mcp',+ name: 'notes-mcp name',+ });+ });++ it('leaves out unfinished installs, stdio servers off desktop, and plugin-served ids', () => {+ const s = state([+ marketplace('pending-mcp', { metadata: {}, status: 'disconnected' }),+ marketplace('local-mcp', { mcpConnectionType: 'stdio', mcpServerUrl: null }),+ // A plugin row still serves this identifier: one entry, the plugin's+ marketplace('plugin-1'),+ ]);++ const ids = toolSelectors.availableToolsForDiscovery(s).map((tool) => tool.identifier);++ expect(ids).not.toContain('pending-mcp');+ expect(ids).not.toContain('local-mcp');+ expect(ids.filter((id) => id === 'plugin-1')).toHaveLength(1);+ });++ it("reads a connector-only identifier's manifest from its connector", () => {+ const s = state([marketplace('notes-mcp'), marketplace('plugin-1')]);++ expect(toolSelectors.getManifestById('notes-mcp')(s)).toMatchObject({+ api: [expect.objectContaining({ name: 'search' })],+ identifier: 'notes-mcp',+ type: 'mcp',+ });+ // A plugin row keeps serving its identifier+ expect(toolSelectors.getManifestById('plugin-1')(s)?.api).toEqual([{ name: 'api-1' }]);+ });+});diff --git a/src/store/tool/selectors/tool.ts b/src/store/tool/selectors/tool.tsindex 776141483a5..f3ee778114e 100644--- a/src/store/tool/selectors/tool.ts+++ b/src/store/tool/selectors/tool.ts@@ -1,11 +1,16 @@import { getBuiltinRenderDisplayControl } from '@lobechat/builtin-tools/displayControls';-import { getComposioAppByIdentifier, getLobehubSkillProviderById } from '@lobechat/const';+import {+ getComposioAppByIdentifier,+ getLobehubSkillProviderById,+ isDesktop,+} from '@lobechat/const';import { type RenderDisplayControl, type ToolManifest } from '@lobechat/types';import {isInstalledPluginAvailableInCurrentEnv,isToolAvailableInCurrentEnv,} from '@/helpers/toolAvailability';+import { buildClientConnectorManifests } from '@/helpers/toolEngineering/buildClientConnectorManifests';import { type MetaData } from '@/types/meta';import { type LobeToolMeta } from '@/types/tool/tool';@@ -13,6 +18,7 @@ import { type ToolStoreState } from '../initialState';import { agentSkillsSelectors } from '../slices/agentSkills/selectors';import { builtinToolSelectors } from '../slices/builtin/selectors';import { ComposioServerStatus } from '../slices/composioStore';+import { connectorSelectors } from '../slices/connector/selectors';import { lobehubSkillStoreSelectors } from '../slices/lobehubSkillStore';import { LobehubSkillStatus } from '../slices/lobehubSkillStore/types';import { pluginSelectors } from '../slices/plugin/selectors';@@ -54,13 +60,25 @@ const getMetaById =};};+/**+ * The MCP connectors chat can run, as the tools engine offers them: custom+ * ones and finished marketplace installs (every MCP install lands here now).+ */+const executableConnectorManifests = (s: ToolStoreState): ToolManifest[] =>+ buildClientConnectorManifests(connectorSelectors.executableMcpConnectors(s));++/**+ * A connector-only identifier is read from its connector; one that still has+ * a plugin row is read from the plugin, as before.+ */const getManifestById =(id: string) =>(s: ToolStoreState): ToolManifest | undefined =>pluginSelectors.installedPluginManifestList(s).concat(s.builtinTools.map((b) => b.manifest as ToolManifest))- .find((i) => i.identifier === id);+ .find((i) => i.identifier === id) ??+ executableConnectorManifests(s).find((i) => i.identifier === id);// Get plugin manifest loading statusconst getManifestLoadingStatus = (id: string) => (s: ToolStoreState) => {@@ -129,6 +147,8 @@ export interface AvailableToolForDiscovery {* 2. User-installed plugins (from s.installedPlugins) — exclude Composio/LobeHub Skill/agent skill overlap* 3. Composio MCP servers (connected) — description from COMPOSIO_APP_TYPES* 4. LobeHub Skill servers (connected) — description from LOBEHUB_SKILL_PROVIDERS+ * 5. MCP connectors chat can run (custom, finished marketplace installs) that no+ * entry above already lists — stdio ones only on desktop*/const availableToolsForDiscovery = (s: ToolStoreState): AvailableToolForDiscovery[] => {// Build exclusion sets for deduplication@@ -203,12 +223,39 @@ const availableToolsForDiscovery = (s: ToolStoreState): AvailableToolForDiscover};});- return [...builtinItems, ...pluginItems, ...composioItems, ...lobehubSkillItems];+ // 5. MCP connectors no plugin row serves (every MCP install now), as the+ // tools engine offers them. Stdio servers run only on a desktop.+ const listed = new Set([...builtinItems, ...pluginItems].map((item) => item.identifier));+ const runnableHere = new Set(+ connectorSelectors+ .executableMcpConnectors(s)+ .filter((connector) => isDesktop || connector.mcpConnectionType !== 'stdio')+ .map((connector) => connector.identifier),+ );+ const connectorItems = executableConnectorManifests(s)+ .filter((manifest) => runnableHere.has(manifest.identifier))+ .filter((manifest) => !listed.has(manifest.identifier))+ .filter((manifest) => !composioIds.has(manifest.identifier))+ .filter((manifest) => !lobehubSkillIds.has(manifest.identifier))+ .map((manifest) => ({+ description: manifest.meta?.description || '',+ identifier: manifest.identifier,+ name: manifest.meta?.title || manifest.identifier,+ }));++ return [+ ...builtinItems,+ ...pluginItems,+ ...composioItems,+ ...lobehubSkillItems,+ ...connectorItems,+ ];};export const toolSelectors = {availableToolsForDiscovery,discoverableMetaList,+ executableConnectorManifests,getManifestById,getManifestLoadingStatus,getPluginInstallError,diff --git a/src/store/tool/slices/builtin/executors/__tests__/lobe-activator.test.ts b/src/store/tool/slices/builtin/executors/__tests__/lobe-activator.test.tsindex 55476a08bde..015fdcb94d7 100644--- a/src/store/tool/slices/builtin/executors/__tests__/lobe-activator.test.ts+++ b/src/store/tool/slices/builtin/executors/__tests__/lobe-activator.test.ts@@ -12,9 +12,11 @@ vi.mock('@/store/tool', () => ({// Mock toolSelectors.availableToolsForDiscoveryconst mockAvailableToolsForDiscovery = vi.fn();+const mockConnectorManifests = vi.fn((): unknown[] => []);vi.mock('@/store/tool/selectors/tool', () => ({toolSelectors: {availableToolsForDiscovery: (s: any) => mockAvailableToolsForDiscovery(s),+ executableConnectorManifests: () => mockConnectorManifests(),},}));@@ -42,6 +44,7 @@ const makePlugin = (identifier: string) => ({describe('lobe-activator executor discovery allowlist', () => {beforeEach(() => {vi.clearAllMocks();+ mockConnectorManifests.mockReturnValue([]);});it('should only return manifests for discoverable tools', async () => {@@ -275,4 +278,32 @@ describe('lobe-activator executor discovery allowlist', () => {const activatedIds = state.activatedTools?.map((t: any) => t.identifier) ?? [];expect(activatedIds).toContain('notion');}, 10_000);++ // Marketplace and custom MCP installs land only in `user_connectors` now+ it('activates a connector-only MCP with its connector manifest', async () => {+ mockGetState.mockReturnValue({ builtinTools: [], installedPlugins: [] });+ mockAvailableToolsForDiscovery.mockReturnValue([+ { description: 'Notes', identifier: 'notes-mcp', name: 'Notes' },+ ]);+ mockConnectorManifests.mockReturnValue([+ {+ api: [{ description: 'Search notes', name: 'search', parameters: { type: 'object' } }],+ identifier: 'notes-mcp',+ meta: { avatar: 'MCP_AVATAR', description: 'Notes connector', title: 'Notes' },+ type: 'mcp',+ },+ ]);++ const result = await activatorExecutor.invoke(+ 'activateTools',+ { identifiers: ['notes-mcp'], reason: 'Search the notes the user asked about.' },+ { messageId: 'msg-1', operationId: 'op-1' },+ );++ expect(result.success).toBe(true);+ const activated = (result.state as any).activatedTools?.find(+ (t: any) => t.identifier === 'notes-mcp',+ );+ expect(activated).toMatchObject({ apiCount: 1, identifier: 'notes-mcp', name: 'Notes' });+ }, 10_000);});diff --git a/src/store/tool/slices/builtin/executors/lobe-activator.ts b/src/store/tool/slices/builtin/executors/lobe-activator.tsindex 8c519ebe532..b2ceb4a58bd 100644--- a/src/store/tool/slices/builtin/executors/lobe-activator.ts+++ b/src/store/tool/slices/builtin/executors/lobe-activator.ts@@ -3,7 +3,7 @@** Creates and exports the ActivatorExecutor instance for registration.* Resolves tool manifests from the tool store (installedPlugins + builtinTools +- * lobehubSkillServers + composio servers).+ * lobehubSkillServers + composio servers + MCP connectors).** State tracking (getActivatedToolIds / markActivated) is intentionally a no-op* because the activated state is persisted in message pluginState and accumulated@@ -132,6 +132,24 @@ const service: ActivatorRuntimeService = {});continue;}++ // MCP connectors no plugin row serves (every MCP install now), built the+ // way the tools engine offers them+ const connectorManifest = toolSelectors+ .executableConnectorManifests(s)+ .find((manifest) => manifest.identifier === id);+ if (connectorManifest) {+ results.push({+ apiDescriptions: connectorManifest.api.map((a) => ({+ description: a.description,+ name: a.name,+ })),+ avatar: connectorManifest.meta?.avatar,+ identifier: connectorManifest.identifier,+ name: connectorManifest.meta?.title ?? connectorManifest.identifier,+ type: connectorManifest.type,+ });+ }}return results;diff --git a/src/store/tool/slices/connector/action.cloudSync.test.ts b/src/store/tool/slices/connector/action.cloudSync.test.tsnew file mode 100644index 00000000000..15248bbf1c7--- /dev/null+++ b/src/store/tool/slices/connector/action.cloudSync.test.ts@@ -0,0 +1,104 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { lambdaClient } from '@/libs/trpc/client';+import { discoverService } from '@/services/discover';++import { useToolStore } from '../../store';+import { initialConnectorState } from './initialState';+import type { ConnectorWithTools } from './types';++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ connector: {+ getForEdit: { query: vi.fn() },+ list: { query: vi.fn().mockResolvedValue([]) },+ syncTools: { mutate: vi.fn() },+ syncToolsFromClientById: { mutate: vi.fn() },+ },+ },+}));++vi.mock('@/services/discover', () => ({+ discoverService: { getMCPPluginManifest: vi.fn() },+}));++const cloudConnector = {+ id: 'c1',+ identifier: 'market-mcp',+ isEnabled: true,+ mcpConnectionType: 'cloud',+ mcpServerUrl: null,+ metadata: { marketplaceInstalled: true },+ sourceType: 'marketplace',+ status: 'connected',+ tools: [],+} as unknown as ConnectorWithTools;++// A market-hosted server has no endpoint of its own: Refresh re-reads its tools+// from the market manifest, the way the install did.+describe('syncConnectorTools for a cloud connector', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ useToolStore.setState({ ...initialConnectorState, connectors: [cloudConnector] });+ });++ it('syncs the tools of the market manifest, approval requirements included', async () => {+ vi.mocked(discoverService.getMCPPluginManifest).mockResolvedValue({+ tools: [{ description: 'Search', inputSchema: { type: 'object' }, name: 'search' }],+ } as any);++ const { result } = renderHook(() => useToolStore());+ await act(async () => {+ await result.current.syncConnectorTools('c1');+ });++ expect(discoverService.getMCPPluginManifest).toHaveBeenCalledWith('market-mcp');+ expect(lambdaClient.connector.syncToolsFromClientById.mutate).toHaveBeenCalledWith({+ id: 'c1',+ tools: [+ {+ description: 'Search',+ humanIntervention: undefined,+ inputSchema: { type: 'object' },+ toolName: 'search',+ },+ ],+ });+ // Never asks the server to connect to an endpoint the row does not have+ expect(lambdaClient.connector.syncTools.mutate).not.toHaveBeenCalled();+ expect(lambdaClient.connector.getForEdit.query).not.toHaveBeenCalled();+ });++ it('keeps a manifest api entry and its intervention policy', async () => {+ vi.mocked(discoverService.getMCPPluginManifest).mockResolvedValue({+ api: [{ description: 'Send', humanIntervention: 'required', name: 'send', parameters: {} }],+ } as any);++ const { result } = renderHook(() => useToolStore());+ await act(async () => {+ await result.current.syncConnectorTools('c1');+ });++ expect(lambdaClient.connector.syncToolsFromClientById.mutate).toHaveBeenCalledWith({+ id: 'c1',+ tools: [+ { description: 'Send', humanIntervention: 'required', inputSchema: {}, toolName: 'send' },+ ],+ });+ });++ it('syncs any other connector on the server', async () => {+ useToolStore.setState({+ connectors: [{ ...cloudConnector, mcpConnectionType: 'http', mcpServerUrl: 'https://x.dev' }],+ });++ const { result } = renderHook(() => useToolStore());+ await act(async () => {+ await result.current.syncConnectorTools('c1');+ });++ expect(discoverService.getMCPPluginManifest).not.toHaveBeenCalled();+ expect(lambdaClient.connector.syncTools.mutate).toHaveBeenCalledWith({ id: 'c1' });+ });+});diff --git a/src/store/tool/slices/connector/action.test.ts b/src/store/tool/slices/connector/action.test.tsindex 89e590ad227..d28d5b268b0 100644--- a/src/store/tool/slices/connector/action.test.ts+++ b/src/store/tool/slices/connector/action.test.ts@@ -10,6 +10,7 @@ import { initialConnectorState } from './initialState';vi.mock('@/libs/trpc/client', () => ({lambdaClient: {connector: {+ create: { mutate: vi.fn() },list: { query: vi.fn() },listAgentBound: { query: vi.fn() },listByAgent: { query: vi.fn() },@@ -124,3 +125,40 @@ describe('createConnectorSlice — scope guard', () => {expect(useToolStore.getState().agentConnectorsInit['agt_1']).toBeUndefined();});});++describe('createConnector', () => {+ beforeEach(() => {+ useToolStore.setState({ ...initialConnectorState });+ vi.spyOn(cacheScope, 'get').mockReturnValue('user-a:personal');+ vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ // An install rolls back by the returned id: a create that rejected after the+ // server wrote the row would leave the row it replaced unrecoverable+ it('returns the written row even when the list refresh after it fails', async () => {+ vi.mocked(lambdaClient.connector.create.mutate).mockResolvedValue({+ id: 'conn-1',+ isNew: false,+ } as never);+ listQuery.mockRejectedValue(new Error('network down'));++ await expect(+ useToolStore.getState().createConnector({ identifier: 'mcp', name: 'MCP' } as never),+ ).resolves.toEqual({ id: 'conn-1', isNew: false });+ expect(useToolStore.getState().connectorCreating).toBe(false);+ });++ it('still fails a create the server refused', async () => {+ vi.mocked(lambdaClient.connector.create.mutate).mockRejectedValue(new Error('conflict'));++ await expect(+ useToolStore.getState().createConnector({ identifier: 'mcp', name: 'MCP' } as never),+ ).rejects.toThrow('conflict');+ expect(listQuery).not.toHaveBeenCalled();+ });+});diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.tsindex 3c4fa871a0b..fe4888e946a 100644--- a/src/store/tool/slices/connector/action.ts+++ b/src/store/tool/slices/connector/action.ts@@ -1,5 +1,6 @@import { isDesktop } from '@lobechat/const';import { isLocalOrPrivateUrl } from '@lobechat/utils';+import type { SWRResponse } from 'swr';import type { ConnectorToolPermission } from '@/database/schemas';import {@@ -9,11 +10,14 @@ import {type ReplicaLens,} from '@/libs/replica';import { subscribeCacheScope } from '@/libs/replica/cacheScopeEvents';+import { useClientDataSWR } from '@/libs/swr';import { lambdaClient } from '@/libs/trpc/client';+import { discoverService } from '@/services/discover';import { type LocalMcpTool, mcpService } from '@/services/mcp';import type { StoreSetter } from '@/store/types';import type { ToolStore } from '../../store';+import { buildCloudMcpManifest, cloudManifestTools } from '../mcpStore/cloudManifest';import {agentBoundConnectorsEntity,agentBoundConnectorsResource,@@ -23,10 +27,13 @@ import {connectorsResource,withoutConnectorSecrets,} from './projection';+import { connectorSelectors } from './selectors';import type { AgentBoundConnector, ConnectorWithTools } from './types';type Setter = StoreSetter<ToolStore>;+const CONNECTOR_LIST_SWR_KEY = 'connectorList';+/** The connector lists are one entry per scope, so every sync shares these params. */const LIST_PARAMS = {} as Record<string, never>;@@ -228,6 +235,21 @@ export class ConnectorActionImpl {if (result.applied) this.#confirmed.add(`${scope}|${BASE_LIST_KEY}`);};+ /**+ * Load the base connector list for a view that reads it, e.g. the install+ * state of a marketplace MCP that only exists as a connector. Loads through+ * {@link fetchConnectors}, so the list is confirmed for this cache scope like+ * any other load; a view mounting after the first load reuses it. Keyed by+ * the cache scope: a caller that re-renders when a scope switch drops the+ * list (`isConnectorsInit`) loads the new identity's list.+ */+ useFetchConnectors = (enable: boolean): SWRResponse =>+ useClientDataSWR(+ enable ? [CONNECTOR_LIST_SWR_KEY, cacheScope.get()] : null,+ () => this.fetchConnectors(),+ { revalidateIfStale: false, revalidateOnFocus: false },+ );+/*** Refresh the connector lists after a mutation. Always refreshes the base* list; also refreshes the agent-bound aggregate when it has been loaded (the@@ -375,7 +397,15 @@ export class ConnectorActionImpl {this.#set({ connectorCreating: true }, false, 'createConnector/start');try {const created = await lambdaClient.connector.create.mutate(params);- await this.fetchConnectors();+ // The row is written: a list refresh that fails now must not fail the+ // create, or the caller could not roll back the row it replaced+ await this.fetchConnectors().catch((error) => {+ console.error(+ '[connector] refreshing the list after creating %s failed:',+ created.id,+ error,+ );+ });return { id: created.id, isNew: created.isNew };} finally {this.#set({ connectorCreating: false }, false, 'createConnector/end');@@ -414,29 +444,44 @@ export class ConnectorActionImpl {| { headers: Record<string, string>; type: 'header' }| null;isEnabled?: boolean;- mcpServerUrl?: string;+ /** `null` clears the field, as on an endpoint-less row being put back. */+ mcpConnectionType?: 'cloud' | 'http' | 'stdio' | null;+ mcpServerUrl?: string | null;+ mcpStdioConfig?: { args?: string[]; command: string; env?: Record<string, string> } | null;metadata?: Record<string, unknown>;name?: string;+ /** A new client leaves the row disconnected until it is authorized; `null` drops it. */oidcConfig?: {clientId?: string;clientSecret?: string;scheme?: 'pre_registration' | 'dcr' | 'client_id_metadata_document';- };+ } | null;+ /** Puts back the source a failed install's `createConnector` moved the row off. */+ sourceType?: 'custom' | 'marketplace';},): Promise<void> => {await lambdaClient.connector.update.mutate({ id, patch: patch as any });await this.#refreshConnectorLists();};- syncConnectorTools = async (id: string): Promise<void> => {+ /**+ * List the connector's tools and store them. `pruneMissingAutoTools` is for+ * an install: the `auto` tools the server no longer lists are dropped.+ */+ syncConnectorTools = async (+ id: string,+ options: { pruneMissingAutoTools?: boolean } = {},+ ): Promise<void> => {this.#set((s) => ({ connectorSyncing: { ...s.connectorSyncing, [id]: true } }),false,'syncConnectorTools/start',);try {- const syncedLocally = await this.#syncLocalConnectorTools(id);- if (!syncedLocally) await lambdaClient.connector.syncTools.mutate({ id });+ const synced =+ (await this.#syncCloudConnectorTools(id, options)) ||+ (await this.#syncLocalConnectorTools(id, options));+ if (!synced) await lambdaClient.connector.syncTools.mutate({ id, ...options });await this.#refreshConnectorLists();} finally {this.#set(@@ -447,6 +492,28 @@ export class ConnectorActionImpl {}};+ /**+ * A market-hosted (`cloud`) server has no endpoint to list tools from: the+ * market serves them in the server's manifest. Returns false for any other+ * connector.+ */+ #syncCloudConnectorTools = async (+ id: string,+ options: { pruneMissingAutoTools?: boolean },+ ): Promise<boolean> => {+ const connector = connectorSelectors.connectorById(id)(this.#get());+ if (connector?.mcpConnectionType !== 'cloud') return false;++ const { identifier } = connector;+ const data = await discoverService.getMCPPluginManifest(identifier);+ await lambdaClient.connector.syncToolsFromClientById.mutate({+ id,+ ...options,+ tools: cloudManifestTools(buildCloudMcpManifest({ data, plugin: { identifier } })),+ });+ return true;+ };+/*** Desktop-only install/refresh path for connectors the cloud server cannot* reach itself: stdio MCP (must spawn on this machine) and local/private@@ -459,7 +526,10 @@ export class ConnectorActionImpl {* Returns false when the connector is server-reachable (public HTTP) or when* not running in desktop — the caller falls back to the server-side sync.*/- #syncLocalConnectorTools = async (id: string): Promise<boolean> => {+ #syncLocalConnectorTools = async (+ id: string,+ options: { pruneMissingAutoTools?: boolean },+ ): Promise<boolean> => {if (!isDesktop) return false;// `getForEdit` returns the decrypted user-set credentials (bearer/apikey/@@ -506,6 +576,7 @@ export class ConnectorActionImpl {await lambdaClient.connector.syncToolsFromClientById.mutate({id,+ ...options,tools: tools.map((tool) => ({description: tool.description,inputSchema: tool.inputSchema,diff --git a/src/store/tool/slices/connector/action.useFetchConnectors.test.ts b/src/store/tool/slices/connector/action.useFetchConnectors.test.tsnew file mode 100644index 00000000000..456e4858237--- /dev/null+++ b/src/store/tool/slices/connector/action.useFetchConnectors.test.ts@@ -0,0 +1,52 @@+import { renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { lambdaClient } from '@/libs/trpc/client';++import { useToolStore } from '../../store';+import { initialConnectorState } from './initialState';++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ connector: { list: { query: vi.fn() } },+ },+}));++const installed = {+ id: 'c1',+ identifier: 'market-mcp',+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://mcp.example.com',+ metadata: { marketplaceInstalled: true },+ sourceType: 'marketplace',+ status: 'connected',+ tools: [],+};++describe('useFetchConnectors', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ useToolStore.setState({ ...initialConnectorState });+ vi.mocked(lambdaClient.connector.list.query).mockResolvedValue([installed] as never);+ });++ it('loads the connector list once for every view that mounts it', async () => {+ renderHook(() => {+ const useFetchConnectors = useToolStore((s) => s.useFetchConnectors);+ useFetchConnectors(true);+ useFetchConnectors(true);+ });++ await waitFor(() => expect(useToolStore.getState().isConnectorsInit).toBe(true));+ expect(useToolStore.getState().connectors.map((c) => c.identifier)).toEqual(['market-mcp']);+ expect(lambdaClient.connector.list.query).toHaveBeenCalledTimes(1);+ });++ it('loads nothing when disabled', async () => {+ renderHook(() => useToolStore((s) => s.useFetchConnectors)(false));++ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(lambdaClient.connector.list.query).not.toHaveBeenCalled();+ });+});diff --git a/src/store/tool/slices/connector/replaceConnector.test.ts b/src/store/tool/slices/connector/replaceConnector.test.tsnew file mode 100644index 00000000000..c1cd64e14f8--- /dev/null+++ b/src/store/tool/slices/connector/replaceConnector.test.ts@@ -0,0 +1,248 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { lambdaClient } from '@/libs/trpc/client';++import { restoreConnector, snapshotReplacedConnector } from './replaceConnector';++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: { connector: { syncToolsFromClientById: { mutate: vi.fn() } } },+}));++const makeStore = (connectors: Record<string, unknown>[]) => {+ const state = {+ connectors,+ fetchConnectors: vi.fn().mockResolvedValue(undefined),+ getConnectorForEdit: vi.fn(async (id: string) => ({ id, snapshot: true })),+ syncConnectorTools: vi.fn().mockResolvedValue(undefined),+ updateConnector: vi.fn().mockResolvedValue(undefined),+ };+ return { get: () => state as never, state };+};++beforeEach(() => {+ vi.clearAllMocks();+});++describe('snapshotReplacedConnector', () => {+ const row = (over: Record<string, unknown>) => ({+ id: 'c1',+ identifier: 'gmail',+ mcpConnectionType: null,+ mcpServerUrl: null,+ metadata: {},+ ...over,+ });++ it.each([+ { case: 'a builtin tool', existing: row({ sourceType: 'builtin' }), source: 'custom' },+ { case: 'a builtin tool', existing: row({ sourceType: 'builtin' }), source: 'marketplace' },+ {+ case: 'a Composio connection',+ existing: row({+ metadata: { composio: { connectedAccountId: 'ca_1' } },+ sourceType: 'marketplace',+ }),+ source: 'custom',+ },+ {+ case: 'a Composio connection',+ existing: row({+ metadata: { composio: { connectedAccountId: 'ca_1' } },+ sourceType: 'marketplace',+ }),+ source: 'marketplace',+ },+ {+ case: 'an MCP server from another source',+ existing: row({ mcpConnectionType: 'http', mcpServerUrl: 'https://x', sourceType: 'custom' }),+ source: 'marketplace',+ },+ ] as const)('refuses to replace $case with a $source install', async ({ existing, source }) => {+ const { get, state } = makeStore([existing]);++ await expect(snapshotReplacedConnector('gmail', source, get)).rejects.toThrow('already exists');+ expect(state.getConnectorForEdit).not.toHaveBeenCalled();+ });++ it.each([+ {+ case: 'a legacy plugin projection',+ existing: row({ sourceType: 'marketplace' }),+ source: 'custom',+ },+ {+ case: 'its own source',+ existing: row({ mcpConnectionType: 'http', mcpServerUrl: 'https://x', sourceType: 'custom' }),+ source: 'custom',+ },+ ] as const)('snapshots $case for a $source install', async ({ existing, source }) => {+ const { get } = makeStore([existing]);++ await expect(snapshotReplacedConnector('gmail', source, get)).resolves.toEqual({+ id: 'c1',+ snapshot: true,+ });+ });+});++describe('restoreConnector', () => {+ const snapshot = (over: Record<string, unknown> = {}) =>+ ({+ credentials: null,+ id: 'c1',+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://old.example.com',+ mcpStdioConfig: null,+ metadata: { marketplaceInstalled: true },+ name: 'Old MCP',+ oidcConfig: null,+ status: 'connected',+ tools: [{ description: null, inputSchema: null, metadata: null, toolName: 'search' }],+ ...over,+ }) as never;++ it('puts back a non-OAuth row, drops the OAuth client it gained and re-marks it connected', async () => {+ const { get, state } = makeStore([{ id: 'c1', mcpServerUrl: 'https://new.example.com' }]);+ const bearer = { token: 'old', type: 'bearer' };++ await restoreConnector(snapshot({ credentials: bearer }), get);++ expect(state.updateConnector).toHaveBeenCalledWith(+ 'c1',+ expect.objectContaining({+ credentials: bearer,+ mcpServerUrl: 'https://old.example.com',+ oidcConfig: null,+ }),+ );+ // Its own tool list replaces the one the failed install synced+ expect(lambdaClient.connector.syncToolsFromClientById.mutate).toHaveBeenCalledWith({+ id: 'c1',+ pruneMissingAutoTools: true,+ tools: [expect.objectContaining({ toolName: 'search' })],+ });+ expect(state.syncConnectorTools).not.toHaveBeenCalled();+ });++ // The sync rebuilds metadata from what it is sent: a rollback that dropped+ // the mark would leave an `always` tool on a `required` auto-run skips+ it('keeps the mandatory approval of a cloud tool the market made always', async () => {+ const { get } = makeStore([{ id: 'c1', mcpConnectionType: 'cloud', mcpServerUrl: null }]);++ await restoreConnector(+ snapshot({+ mcpConnectionType: 'cloud',+ mcpServerUrl: null,+ tools: [+ {+ description: 'Delete a repo',+ inputSchema: null,+ metadata: { mandatoryApproval: true, visibility: ['model'] },+ toolName: 'delete_repo',+ },+ { description: null, inputSchema: null, metadata: null, toolName: 'search' },+ ],+ }),+ get,+ );++ expect(lambdaClient.connector.syncToolsFromClientById.mutate).toHaveBeenCalledWith({+ id: 'c1',+ pruneMissingAutoTools: true,+ tools: [+ {+ description: 'Delete a repo',+ humanIntervention: 'always',+ inputSchema: undefined,+ toolName: 'delete_repo',+ visibility: ['model'],+ },+ {+ description: undefined,+ humanIntervention: undefined,+ inputSchema: undefined,+ toolName: 'search',+ visibility: undefined,+ },+ ],+ });+ });++ describe('an OAuth row, whose tokens the edit read withholds', () => {+ const oauth = { oidcConfig: { clientId: 'client', scheme: 'dcr' } };++ it('keeps the tokens it holds on the same endpoint and asks its server', async () => {+ const { get, state } = makeStore([{ id: 'c1', mcpServerUrl: 'https://old.example.com' }]);++ await restoreConnector(snapshot(oauth), get);++ const patch = state.updateConnector.mock.calls[0][1];+ expect(patch).not.toHaveProperty('credentials');+ expect(patch).not.toHaveProperty('oidcConfig');+ // Never re-marked connected on the strength of a tool list alone+ expect(lambdaClient.connector.syncToolsFromClientById.mutate).not.toHaveBeenCalled();+ expect(state.syncConnectorTools).toHaveBeenCalledWith('c1', { pruneMissingAutoTools: true });+ });++ it('drops the tokens of the endpoint it moves back off', async () => {+ const { get, state } = makeStore([{ id: 'c1', mcpServerUrl: 'https://new.example.com' }]);+ state.syncConnectorTools.mockRejectedValue(new Error('401'));++ await expect(restoreConnector(snapshot(oauth), get)).resolves.toBeUndefined();++ expect(state.updateConnector).toHaveBeenCalledWith(+ 'c1',+ expect.objectContaining({ credentials: null, mcpServerUrl: 'https://old.example.com' }),+ );+ });+ });++ it('clears the endpoint a failed install wrote over an endpoint-less legacy projection', async () => {+ const { get, state } = makeStore([{ id: 'c1', mcpServerUrl: 'https://new.example.com' }]);++ await restoreConnector(+ snapshot({ mcpConnectionType: null, mcpServerUrl: null, mcpStdioConfig: null }),+ get,+ );++ expect(state.updateConnector).toHaveBeenCalledWith(+ 'c1',+ expect.objectContaining({+ mcpConnectionType: null,+ mcpServerUrl: null,+ mcpStdioConfig: null,+ }),+ );+ });++ it('puts back the marketplace source a failed custom install moved the row off', async () => {+ const { get, state } = makeStore([+ { id: 'c1', mcpServerUrl: 'https://new.example.com', sourceType: 'custom' },+ ]);++ await restoreConnector(+ snapshot({+ mcpConnectionType: null,+ mcpServerUrl: null,+ sourceType: 'marketplace',+ }),+ get,+ );++ expect(state.updateConnector).toHaveBeenCalledWith(+ 'c1',+ expect.objectContaining({ mcpServerUrl: null, sourceType: 'marketplace' }),+ );+ });++ it('leaves a row that was not connected disconnected', async () => {+ const { get, state } = makeStore([{ id: 'c1', mcpServerUrl: 'https://old.example.com' }]);++ await restoreConnector(snapshot({ status: 'disconnected' }), get);++ expect(state.updateConnector).toHaveBeenCalled();+ expect(lambdaClient.connector.syncToolsFromClientById.mutate).not.toHaveBeenCalled();+ expect(state.syncConnectorTools).not.toHaveBeenCalled();+ });+});diff --git a/src/store/tool/slices/connector/replaceConnector.ts b/src/store/tool/slices/connector/replaceConnector.tsnew file mode 100644index 00000000000..4605f1251c6--- /dev/null+++ b/src/store/tool/slices/connector/replaceConnector.ts@@ -0,0 +1,111 @@+import { hasCallableMcpEndpoint, hasMandatoryApproval } from '@lobechat/const';++import { lambdaClient } from '@/libs/trpc/client';++import type { ToolStore } from '../../store';+import { connectorSelectors } from './selectors';+import type { ConnectorWithTools } from './types';++export type ConnectorSnapshot = Awaited<ReturnType<ToolStore['getConnectorForEdit']>>;+type ConnectorPatch = Parameters<ToolStore['updateConnector']>[1];++/**+ * Whether an MCP install from `sourceType` may overwrite a stored row of the+ * same identifier: one from the same source, or the endpoint-less tool+ * projection a legacy marketplace plugin left (`connector.syncPluginTools`).+ * Builtin tools and Composio connections are never MCP servers to replace.+ */+const isReplaceableBy = (existing: ConnectorWithTools, sourceType: 'custom' | 'marketplace') => {+ if (existing.metadata?.composio) return false;+ if (existing.sourceType === sourceType) return true;+ return existing.sourceType === 'marketplace' && !hasCallableMcpEndpoint(existing);+};++/**+ * Read the connector an install is about to overwrite: `connector.create`+ * upserts on the identifier, whatever source the stored row came from, so a+ * row the install may not replace (see {@link isReplaceableBy}) is refused.+ * Returns the stored row's snapshot for {@link restoreConnector}.+ */+export const snapshotReplacedConnector = async (+ identifier: string,+ sourceType: 'custom' | 'marketplace',+ get: () => ToolStore,+): Promise<ConnectorSnapshot | undefined> => {+ await get().fetchConnectors();+ const existing = connectorSelectors.connectorByIdentifier(identifier)(get());+ if (!existing) return;+ if (!isReplaceableBy(existing, sourceType)) {+ throw new Error(+ `A connector with the identifier "${identifier}" already exists. Remove it before adding this MCP server.`,+ );+ }+ return get().getConnectorForEdit(existing.id);+};++/**+ * Put a connector back the way it was before an install's `create` or an+ * OAuth edit overwrote it. A row that was connected is connected again:+ *+ * - the edit read withholds OAuth tokens, so an OAuth row keeps the tokens it+ * holds now (dropped when they belong to the endpoint it moves back off),+ * and its server answers whether it still connects;+ * - any other row is re-marked connected from its own tool list without+ * reaching the server.+ *+ * Either way the row's tool list replaces the one the install synced, so+ * tools only the failed install listed are dropped again, and a tool the+ * market made `always` keeps its mandatory approval.+ */+export const restoreConnector = async (snapshot: ConnectorSnapshot, get: () => ToolStore) => {+ const { credentials, id, mcpServerUrl, mcpStdioConfig, oidcConfig, status, tools } = snapshot;+ const tokensWithheld = !!oidcConfig && !credentials;+ const current = connectorSelectors.connectorById(id)(get());+ const movesEndpoint = (current?.mcpServerUrl ?? null) !== (mcpServerUrl ?? null);++ await get().updateConnector(id, {+ ...(!tokensWithheld+ ? { credentials: (credentials ?? null) as ConnectorPatch['credentials'] }+ : movesEndpoint+ ? { credentials: null }+ : {}),+ isEnabled: snapshot.isEnabled,+ // `null` clears what the failed install wrote, so an endpoint-less row+ // (a legacy plugin's tool projection) is not left on the new endpoint+ mcpConnectionType: (snapshot.mcpConnectionType ?? null) as ConnectorPatch['mcpConnectionType'],+ mcpServerUrl: mcpServerUrl ?? null,+ mcpStdioConfig: mcpStdioConfig ?? null,+ metadata: snapshot.metadata ?? {},+ name: snapshot.name,+ // `create` re-sources the row: a custom install over a legacy marketplace+ // projection left it `custom`, which a marketplace reinstall would refuse+ ...(snapshot.sourceType === 'custom' || snapshot.sourceType === 'marketplace'+ ? { sourceType: snapshot.sourceType }+ : {}),+ // A row without an OAuth client drops the one the failed attempt stored.+ // One that had a client keeps the stored one: its secret is withheld too.+ ...(oidcConfig ? {} : { oidcConfig: null }),+ });+ if (status !== 'connected') return;+ if (tokensWithheld) {+ // Connected or `error`, as its server answers+ await get()+ .syncConnectorTools(id, { pruneMissingAutoTools: true })+ .catch(() => {});+ return;+ }+ await lambdaClient.connector.syncToolsFromClientById.mutate({+ id,+ pruneMissingAutoTools: true,+ tools: tools.map((tool) => ({+ description: tool.description ?? undefined,+ // The sync rebuilds each tool's metadata from what it is sent, so a+ // tool the market made `always` must say so again to keep its mark+ humanIntervention: hasMandatoryApproval(tool.metadata) ? ('always' as const) : undefined,+ inputSchema: (tool.inputSchema ?? undefined) as Record<string, unknown> | undefined,+ toolName: tool.toolName,+ visibility: (tool.metadata as { visibility?: string[] } | null)?.visibility,+ })),+ });+ await get().fetchConnectors();+};diff --git a/src/store/tool/slices/connector/selectors.runtime.test.ts b/src/store/tool/slices/connector/selectors.runtime.test.tsindex 1e871665be1..5c85ac40f86 100644--- a/src/store/tool/slices/connector/selectors.runtime.test.ts+++ b/src/store/tool/slices/connector/selectors.runtime.test.ts@@ -60,6 +60,100 @@ describe('marketplace MCP runtime manifests', () => {buildClientConnectorManifests(connectorSelectors.executableMcpConnectors(state)),).toEqual([]);});++ it('offers a finished connector install of any transport without a plugin row', () => {+ const marked = { marketplaceInstalled: true };+ const state = {+ connectors: [+ connector({ id: 'http', identifier: 'http-mcp', metadata: marked }),+ connector({+ id: 'stdio',+ identifier: 'stdio-mcp',+ mcpConnectionType: 'stdio',+ mcpServerUrl: null,+ metadata: marked,+ }),+ connector({+ id: 'cloud',+ identifier: 'cloud-mcp',+ mcpConnectionType: 'cloud',+ mcpServerUrl: null,+ metadata: marked,+ }),+ ],+ installedPlugins: [],+ } as unknown as ToolStore;+ expect(connectorSelectors.executableMcpConnectors(state).map((c) => c.identifier)).toEqual([+ 'http-mcp',+ 'stdio-mcp',+ 'cloud-mcp',+ ]);+ });+});++describe('marketplace MCPs installed as connectors', () => {+ const marked = connector({ metadata: { marketplaceInstalled: true } });+ const state = (patch: Partial<ToolStore>) =>+ ({ connectors: [], installedPlugins: [], ...patch }) as unknown as ToolStore;++ it('counts only a finished install as installed', () => {+ expect(+ connectorSelectors.isMarketplaceConnectorInstalled('oauth-market')(+ state({ connectors: [marked] }),+ ),+ ).toBe(true);+ // A connected OAuth row without the install mark is not an install+ expect(+ connectorSelectors.isMarketplaceConnectorInstalled('oauth-market')(+ state({ connectors: [connector({})] }),+ ),+ ).toBe(false);+ });++ it('lists a connector install beside custom connectors unless a legacy row lists it', () => {+ const custom = connector({ id: 'custom', identifier: 'my-mcp', sourceType: 'custom' });+ expect(+ connectorSelectors+ .userMcpConnectors(state({ connectors: [custom, marked] }))+ .map((c) => c.identifier),+ ).toEqual(['my-mcp', 'oauth-market']);+ expect(+ connectorSelectors+ .userMcpConnectors(+ state({+ connectors: [custom, marked],+ installedPlugins: [{ identifier: 'oauth-market' }] as never,+ }),+ )+ .map((c) => c.identifier),+ ).toEqual(['my-mcp']);+ });++ it('resolves the connector a reinstall over a legacy row runs on, for its settings', () => {+ const withLegacyRow = state({+ connectors: [marked],+ installedPlugins: [{ identifier: 'oauth-market' }] as never,+ });++ // The list shows the legacy plugin, but its tools run on the connector+ expect(connectorSelectors.marketplaceMcpConnectors(withLegacyRow)).toEqual([]);+ expect(+ connectorSelectors.marketplaceMcpConnectorByIdentifier('oauth-market')(withLegacyRow),+ ).toBe(marked);+ });++ it('resolves no connector for a row that only projects a plugin or comes from another source', () => {+ const projection = connector({ mcpConnectionType: null, mcpServerUrl: null });+ const custom = connector({ sourceType: 'custom' });++ for (const row of [projection, custom]) {+ expect(+ connectorSelectors.marketplaceMcpConnectorByIdentifier('oauth-market')(+ state({ connectors: [row] }),+ ),+ ).toBeUndefined();+ }+ });});describe('connectorSelectors.connectorByIdentifierForAgent', () => {diff --git a/src/store/tool/slices/connector/selectors.ts b/src/store/tool/slices/connector/selectors.tsindex 6ada04601b2..ce020255bbb 100644--- a/src/store/tool/slices/connector/selectors.ts+++ b/src/store/tool/slices/connector/selectors.ts@@ -1,3 +1,10 @@+import {+ hasCallableMcpEndpoint,+ isMarketplaceInstallCompleted,+ isMarketplaceInstallRunnable,+} from '@lobechat/const';++import type { ToolStoreState } from '../../initialState';import type { ToolStore } from '../../store';import type { AgentBoundConnector, ConnectorTool, ConnectorWithTools } from './types';@@ -38,18 +45,65 @@ const connectedConnectors = (s: ToolStore): ConnectorWithTools[] =>const customConnectors = (s: ToolStore): ConnectorWithTools[] =>(s.connectors ?? []).filter((c) => c.sourceType === 'custom');+/**+ * Marketplace MCPs whose install finished on the connector path. An OAuth row+ * can connect after the user canceled, so only the install's own mark counts.+ */+const installedMarketplaceConnectors = (s: ToolStoreState): ConnectorWithTools[] =>+ (s.connectors ?? []).filter(+ (c) =>+ c.sourceType === 'marketplace' &&+ hasCallableMcpEndpoint(c) &&+ isMarketplaceInstallCompleted(c.metadata),+ );++const isMarketplaceConnectorInstalled =+ (identifier: string) =>+ (s: ToolStoreState): boolean =>+ installedMarketplaceConnectors(s).some((c) => c.identifier === identifier);++/**+ * Finished marketplace installs that have no legacy plugin row. Lists show+ * them beside installed plugins; one with a legacy row is listed as that plugin.+ */+const marketplaceMcpConnectors = (s: ToolStoreState): ConnectorWithTools[] => {+ const legacy = new Set((s.installedPlugins ?? []).map((plugin) => plugin.identifier));+ return installedMarketplaceConnectors(s).filter((c) => !legacy.has(c.identifier));+};++/**+ * The marketplace connector `identifier`'s tools run on, whether or not a+ * legacy plugin row remains: a call goes to a connector with an endpoint+ * before the plugin, so its connection settings are edited on the connector.+ */+const marketplaceMcpConnectorByIdentifier =+ (identifier: string) =>+ (s: ToolStoreState): ConnectorWithTools | undefined =>+ (s.connectors ?? []).find(+ (c) =>+ c.identifier === identifier && c.sourceType === 'marketplace' && hasCallableMcpEndpoint(c),+ );++/** MCP servers the user added as connectors: custom ones and marketplace installs. */+const userMcpConnectors = (s: ToolStoreState): ConnectorWithTools[] => [+ ...(s.connectors ?? []).filter((c) => c.sourceType === 'custom'),+ ...marketplaceMcpConnectors(s),+];+/** Remote marketplace OAuth MCPs also execute with server-held credentials. */-const executableMcpConnectors = (s: ToolStore): ConnectorWithTools[] => {+const executableMcpConnectors = (+ s: Pick<ToolStoreState, 'connectors' | 'installedPlugins'>,+): ConnectorWithTools[] => {// A late OAuth callback may connect after the user canceled installation.- // Marketplace tools enter the runtime only after the plugin install completes.+ // Marketplace tools enter the runtime only once the install has finished and+ // the row is connected, the rule every call path applies.const installed = new Set((s.installedPlugins ?? []).map((plugin) => plugin.identifier));return (s.connectors ?? []).filter((c) =>c.sourceType === 'custom' ||(c.sourceType === 'marketplace' &&- !!c.mcpServerUrl &&- c.status === 'connected' &&- installed.has(c.identifier)),+ hasCallableMcpEndpoint(c) &&+ isMarketplaceInstallRunnable(c, installed.has(c.identifier))),);};@@ -166,6 +220,10 @@ export const connectorSelectors = {connectorToolsGrouped,customConnectors,executableMcpConnectors,+ installedMarketplaceConnectors,+ isMarketplaceConnectorInstalled,+ marketplaceMcpConnectorByIdentifier,+ marketplaceMcpConnectors,connectorToolsGroupedByIdentifier:(identifier: string) =>(s: ToolStore): GroupedTools => {@@ -182,4 +240,5 @@ export const connectorSelectors = {return connector ? (s.connectorSyncing[connector.id] ?? false) : false;},notConnectedConnectors,+ userMcpConnectors,};diff --git a/src/store/tool/slices/customPlugin/action.test.ts b/src/store/tool/slices/customPlugin/action.test.tsindex c8802bd8c85..22b45ee7fa4 100644--- a/src/store/tool/slices/customPlugin/action.test.ts+++ b/src/store/tool/slices/customPlugin/action.test.ts@@ -6,7 +6,6 @@ import { pluginService } from '@/services/plugin';import { type LobeToolCustomPlugin } from '@/types/tool/plugin';import { useToolStore } from '../../store';-import { defaultCustomPlugin } from './initialState';beforeEach(() => {vi.resetAllMocks();@@ -14,7 +13,6 @@ beforeEach(() => {vi.mock('@/services/plugin', () => ({pluginService: {updatePlugin: vi.fn(),- createCustomPlugin: vi.fn(),uninstallPlugin: vi.fn(),updatePluginManifest: vi.fn(),getInstalledPlugins: vi.fn().mockResolvedValue([]),@@ -54,32 +52,259 @@ describe('useToolStore:customPlugin', () => {});});- describe('saveToCustomPluginList', () => {- it('should add a plugin to the custom plugin list and reset newCustomPlugin', async () => {- const newPlugin = {- type: 'customPlugin',- manifest: {- identifier: 'plugin2',- meta: { title: 'New Plugin' },+ describe('installCustomMcpConnector', () => {+ const mockConnectorActions = () => {+ const createConnector = vi.fn().mockResolvedValue({ id: 'conn-1', isNew: true });+ const deleteConnector = vi.fn().mockResolvedValue(undefined);+ const syncConnectorTools = vi.fn().mockResolvedValue(undefined);+ const fetchConnectors = vi.fn().mockResolvedValue(undefined);+ const getConnectorForEdit = vi.fn();+ const updateConnector = vi.fn().mockResolvedValue(undefined);+ act(() => {+ useToolStore.setState({+ connectors: [],+ createConnector,+ deleteConnector,+ fetchConnectors,+ getConnectorForEdit,+ syncConnectorTools,+ updateConnector,+ });+ });+ return {+ createConnector,+ deleteConnector,+ getConnectorForEdit,+ syncConnectorTools,+ updateConnector,+ };+ };++ it('adds an http MCP as a custom connector and syncs its tools, writing no plugin row', async () => {+ const { createConnector, deleteConnector, syncConnectorTools } = mockConnectorActions();++ await act(async () => {+ await useToolStore.getState().installCustomMcpConnector({+ config: { headers: { 'X-Key': 'k' }, type: 'http', url: ' https://mcp.example.com ' },+ description: 'desc',+ icon: 'icon',+ identifier: 'my-mcp',+ name: 'My MCP',+ });+ });++ expect(createConnector).toHaveBeenCalledWith({+ identifier: 'my-mcp',+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://mcp.example.com',+ mcpStdioConfig: undefined,+ metadata: {+ avatar: 'icon',+ customHeaders: { 'X-Key': 'k' },+ description: 'desc',+ desktopStdioExecution: true,},- } as LobeToolCustomPlugin;+ name: 'My MCP',+ sourceType: 'custom',+ });+ // A reinstall's tool list replaces the stored one+ expect(syncConnectorTools).toHaveBeenCalledWith('conn-1', { pruneMissingAutoTools: true });+ expect(deleteConnector).not.toHaveBeenCalled();+ expect(pluginService.updatePlugin).not.toHaveBeenCalled();+ expect(pluginService.uninstallPlugin).not.toHaveBeenCalled();+ });++ // The lists would show the plugin in the connector's place, so their+ // Configure and Delete would act on a row the calls no longer run on. The+ // protocol-install popup mounts no plugin list, so the store may hold none.+ it('removes a legacy custom plugin of the same identifier once the connector is synced', async () => {+ const { syncConnectorTools } = mockConnectorActions();+ act(() => {+ useToolStore.setState({ installedPlugins: [] });+ });+ vi.mocked(pluginService.getInstalledPlugins).mockResolvedValue([+ { identifier: 'my-mcp', manifest: { identifier: 'my-mcp' }, type: 'customPlugin' },+ ] as never);++ await act(async () => {+ await useToolStore.getState().installCustomMcpConnector({+ config: { type: 'http', url: 'https://mcp.example.com' },+ identifier: 'my-mcp',+ });+ });++ expect(pluginService.uninstallPlugin).toHaveBeenCalledWith('my-mcp');+ expect(vi.mocked(pluginService.uninstallPlugin).mock.invocationCallOrder[0]).toBeGreaterThan(+ syncConnectorTools.mock.invocationCallOrder[0],+ );+ });++ it('keeps a same-identifier plugin the server does not list as a custom plugin', async () => {+ mockConnectorActions();+ vi.mocked(pluginService.getInstalledPlugins).mockResolvedValue([+ { identifier: 'my-mcp', manifest: { identifier: 'my-mcp' }, type: 'plugin' },+ ] as never);++ await act(async () => {+ await useToolStore.getState().installCustomMcpConnector({+ config: { type: 'http', url: 'https://mcp.example.com' },+ identifier: 'my-mcp',+ });+ });++ expect(pluginService.uninstallPlugin).not.toHaveBeenCalled();+ });++ it('keeps the legacy custom plugin when the connector sync fails', async () => {+ const { syncConnectorTools } = mockConnectorActions();+ syncConnectorTools.mockRejectedValue(new Error('unreachable'));act(() => {useToolStore.setState({- installedPlugins: [],- newCustomPlugin: newPlugin,+ installedPlugins: [+ { identifier: 'my-mcp', manifest: { identifier: 'my-mcp' }, type: 'customPlugin' },+ ] as never,});});- const { result } = renderHook(() => useToolStore());+ await expect(+ useToolStore.getState().installCustomMcpConnector({+ config: { type: 'http', url: 'https://mcp.example.com' },+ identifier: 'my-mcp',+ }),+ ).rejects.toThrow('unreachable');+ expect(pluginService.uninstallPlugin).not.toHaveBeenCalled();+ });++ it('stores a stdio MCP command on the connector', async () => {+ const { createConnector } = mockConnectorActions();await act(async () => {- await result.current.installCustomPlugin(newPlugin);+ await useToolStore.getState().installCustomMcpConnector({+ config: { args: ['-y', 'pkg'], command: 'npx', env: { A: '1' }, type: 'stdio' },+ identifier: 'local-mcp',+ });});- expect(result.current.newCustomPlugin).toEqual(defaultCustomPlugin);- expect(pluginService.createCustomPlugin).toBeCalledWith(newPlugin);+ expect(createConnector).toHaveBeenCalledWith(+ expect.objectContaining({+ mcpConnectionType: 'stdio',+ mcpServerUrl: undefined,+ mcpStdioConfig: { args: ['-y', 'pkg'], command: 'npx', env: { A: '1' } },+ // Its calls stay on the desktop, as the custom plugin's did+ metadata: expect.objectContaining({ desktopStdioExecution: true }),+ name: 'local-mcp',+ }),+ );+ });++ it('removes the connector it created when the tool sync fails', async () => {+ const { deleteConnector, syncConnectorTools } = mockConnectorActions();+ syncConnectorTools.mockRejectedValue(new Error('unreachable'));++ await expect(+ useToolStore.getState().installCustomMcpConnector({+ config: { type: 'http', url: 'https://down.example.com' },+ identifier: 'down',+ }),+ ).rejects.toThrow('unreachable');+ expect(deleteConnector).toHaveBeenCalledWith('conn-1');+ });++ it('keeps a connector that already existed when the tool sync fails', async () => {+ const { createConnector, deleteConnector, syncConnectorTools } = mockConnectorActions();+ createConnector.mockResolvedValue({ id: 'conn-old', isNew: false });+ syncConnectorTools.mockRejectedValue(new Error('unreachable'));++ await expect(+ useToolStore.getState().installCustomMcpConnector({+ config: { type: 'http', url: 'https://down.example.com' },+ identifier: 'down',+ }),+ ).rejects.toThrow('unreachable');+ expect(deleteConnector).not.toHaveBeenCalled();+ });++ it('refuses to replace a marketplace connector with the same identifier', async () => {+ const { createConnector } = mockConnectorActions();+ act(() => {+ useToolStore.setState({+ connectors: [+ {+ id: 'market-1',+ identifier: 'shared',+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://market.example.com',+ sourceType: 'marketplace',+ },+ ] as never,+ });+ });++ await expect(+ useToolStore.getState().installCustomMcpConnector({+ config: { type: 'http', url: 'https://mine.example.com' },+ identifier: 'shared',+ }),+ ).rejects.toThrow('already exists');+ expect(createConnector).not.toHaveBeenCalled();+ });++ it('restores the custom connector it reinstalled over when the tool sync fails', async () => {+ const {+ createConnector,+ deleteConnector,+ getConnectorForEdit,+ syncConnectorTools,+ updateConnector,+ } = mockConnectorActions();+ act(() => {+ useToolStore.setState({+ connectors: [+ {+ id: 'conn-old',+ identifier: 'down',+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://old.example.com',+ sourceType: 'custom',+ },+ ] as never,+ });+ });+ getConnectorForEdit.mockResolvedValue({+ credentials: { token: 'old-token', type: 'bearer' },+ id: 'conn-old',+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://old.example.com',+ mcpStdioConfig: null,+ metadata: { description: 'old' },+ name: 'Old',+ oidcConfig: null,+ status: 'disconnected',+ tools: [],+ });+ createConnector.mockResolvedValue({ id: 'conn-old', isNew: false });+ syncConnectorTools.mockRejectedValue(new Error('unreachable'));++ await expect(+ useToolStore.getState().installCustomMcpConnector({+ config: { type: 'http', url: 'https://down.example.com' },+ identifier: 'down',+ }),+ ).rejects.toThrow('unreachable');+ expect(deleteConnector).not.toHaveBeenCalled();+ expect(updateConnector).toHaveBeenCalledWith(+ 'conn-old',+ expect.objectContaining({+ credentials: { token: 'old-token', type: 'bearer' },+ mcpServerUrl: 'https://old.example.com',+ metadata: { description: 'old' },+ name: 'Old',+ }),+ );});});+describe('updateCustomPlugin', () => {it('should update a specific plugin in the custom plugin list and reinstall the plugin', async () => {const pluginId = 'test-plugin';@@ -115,6 +340,48 @@ describe('useToolStore:customPlugin', () => {expect(pluginService.updatePlugin).toHaveBeenCalledWith(pluginId, updatedPlugin);});++ // The loaded row still points at the old server until the list refreshes+ it('lists the tools of the server the edit saved, not the one the row had', async () => {+ const pluginId = 'moved-mcp';+ act(() => {+ useToolStore.setState({+ installedPlugins: [+ {+ customParams: {+ mcp: { headers: { 'x-env': 'a' }, url: 'https://a.example.com/mcp' },+ },+ identifier: pluginId,+ type: 'customPlugin',+ } as LobeToolCustomPlugin,+ ],+ });+ });+ vi.mocked(mcpService.getStreamableMcpServerManifest).mockResolvedValueOnce({} as never);+ const { result } = renderHook(() => useToolStore());++ await act(async () => {+ await result.current.updateCustomPlugin(pluginId, {+ customParams: {+ mcp: {+ auth: { token: 'b-token', type: 'bearer' },+ headers: { 'x-env': 'b' },+ url: 'https://b.example.com/mcp',+ },+ },+ identifier: pluginId,+ type: 'customPlugin',+ } as LobeToolCustomPlugin);+ });++ expect(mcpService.getStreamableMcpServerManifest).toHaveBeenCalledWith(+ expect.objectContaining({+ auth: { token: 'b-token', type: 'bearer' },+ headers: { 'x-env': 'b' },+ url: 'https://b.example.com/mcp',+ }),+ );+ });});describe('reinstallCustomPlugin', () => {diff --git a/src/store/tool/slices/customPlugin/action.ts b/src/store/tool/slices/customPlugin/action.tsindex 0810982afa5..c8042dcbe49 100644--- a/src/store/tool/slices/customPlugin/action.ts+++ b/src/store/tool/slices/customPlugin/action.ts@@ -1,3 +1,4 @@+import { DESKTOP_STDIO_EXECUTION_KEY } from '@lobechat/const';import { merge } from 'es-toolkit/compat';import { mcpService } from '@/services/mcp';@@ -7,11 +8,26 @@ import { type LobeToolCustomPlugin, type PluginInstallError } from '@/types/toolimport { setNamespace } from '@/utils/storeDebug';import { type ToolStore } from '../../store';+import { restoreConnector, snapshotReplacedConnector } from '../connector/replaceConnector';import { pluginSelectors } from '../plugin/selectors';-import { defaultCustomPlugin } from './initialState';const n = setNamespace('customPlugin');+export interface CustomMcpConnectorParams {+ config: {+ args?: string[];+ command?: string;+ env?: Record<string, string>;+ headers?: Record<string, string>;+ type: 'http' | 'stdio';+ url?: string;+ };+ description?: string;+ icon?: string;+ identifier: string;+ name?: string;+}+type Setter = StoreSetter<ToolStore>;export const createCustomPluginSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>new CustomPluginActionImpl(set, get, _api);@@ -26,15 +42,84 @@ export class CustomPluginActionImpl {this.#get = get;}- installCustomPlugin = async (value: LobeToolCustomPlugin): Promise<void> => {- await pluginService.createCustomPlugin(value);+ /**+ * Add a custom MCP server from a protocol link as a `custom` connector and+ * sync its tools. Its stdio calls keep running on the desktop, as the custom+ * plugin's did. When the tool sync fails, a row this call created is removed+ * again and a row it reinstalled over is restored. Once it succeeds, a legacy+ * custom plugin of the same identifier is removed: the connector runs its+ * calls now, while the lists would show that plugin in its place, so their+ * Configure and Delete would act on the plugin alone.+ */+ installCustomMcpConnector = async ({+ config,+ description,+ icon,+ identifier,+ name,+ }: CustomMcpConnectorParams): Promise<void> => {+ const {+ createConnector,+ deleteConnector,+ refreshPlugins,+ syncConnectorTools,+ uninstallPlugin,+ } = this.#get();+ const isHttp = config.type === 'http';+ // Set whatever the transport: it can be edited to stdio later+ const metadata: Record<string, unknown> = {+ avatar: icon,+ description,+ [DESKTOP_STDIO_EXECUTION_KEY]: true,+ };+ if (isHttp && config.headers && Object.keys(config.headers).length > 0)+ metadata.customHeaders = config.headers;++ const snapshot = await snapshotReplacedConnector(identifier, 'custom', this.#get);+ const { id, isNew } = await createConnector({+ identifier,+ mcpConnectionType: config.type,+ mcpServerUrl: isHttp ? config.url?.trim() : undefined,+ mcpStdioConfig: isHttp+ ? undefined+ : { args: config.args ?? [], command: (config.command ?? '').trim(), env: config.env },+ metadata,+ name: name || identifier,+ sourceType: 'custom',+ });+ try {+ // A reinstall's tool list replaces the stored one+ await syncConnectorTools(id, { pruneMissingAutoTools: true });+ } catch (error) {+ const rollback = isNew+ ? deleteConnector(id)+ : snapshot+ ? restoreConnector(snapshot, this.#get)+ : undefined;+ await rollback?.catch((rollbackError) => {+ console.error('[customMcp] rollback of connector %s failed:', id, rollbackError);+ });+ throw error;+ }- await this.#get().refreshPlugins();- this.#set({ newCustomPlugin: defaultCustomPlugin }, false, n('saveToCustomPluginList'));+ // The install itself succeeded: a plugin row left behind is only logged+ try {+ // The protocol-install popup mounts no plugin list: ask the server+ await refreshPlugins();+ if (!pluginSelectors.getCustomPluginById(identifier)(this.#get())) return;+ await uninstallPlugin(identifier);+ } catch (error) {+ console.error('[customMcp] removing legacy custom plugin %s failed:', identifier, error);+ }};- reinstallCustomPlugin = async (id: string): Promise<void> => {- const plugin = pluginSelectors.getCustomPluginById(id)(this.#get());+ /**+ * Rediscover a legacy custom MCP's tools. `saved` is the configuration an+ * edit just stored: the loaded row still holds the previous server until the+ * list refreshes, so reading it would list the old server's tools.+ */+ reinstallCustomPlugin = async (id: string, saved?: LobeToolCustomPlugin): Promise<void> => {+ const plugin = saved ?? pluginSelectors.getCustomPluginById(id)(this.#get());if (!plugin) return;const { refreshPlugins, updateInstallError, updateInstallLoadingState } = this.#get();@@ -75,8 +160,8 @@ export class CustomPluginActionImpl {// 1. Update list item informationawait pluginService.updatePlugin(id, value);- // 2. Reinstall plugin- await reinstallCustomPlugin(id);+ // 2. Reinstall plugin from the values just saved+ await reinstallCustomPlugin(id, value);};updateNewCustomPlugin = (newCustomPlugin: Partial<LobeToolCustomPlugin>): void => {diff --git a/src/store/tool/slices/mcpStore/action.hostedConfig.test.ts b/src/store/tool/slices/mcpStore/action.hostedConfig.test.tsindex 917aac6d221..b282a04a1ff 100644--- a/src/store/tool/slices/mcpStore/action.hostedConfig.test.ts+++ b/src/store/tool/slices/mcpStore/action.hostedConfig.test.ts@@ -3,10 +3,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type * as ReplicaModule from '@/libs/replica';import { discoverService } from '@/services/discover';import { mcpService } from '@/services/mcp';-import { pluginService } from '@/services/plugin';import type { ToolStore } from '@/store/tool/store';import { createMCPPluginStoreSlice } from './action';+import { installMarketplaceConnector } from './installMarketplaceConnector';const environment = vi.hoisted(() => ({ isDesktop: true }));@@ -40,7 +40,7 @@ vi.mock('@/services/discover', () => ({vi.mock('@/services/mcp', () => ({mcpService: { checkInstallation: vi.fn(), getStdioMcpServerManifest: vi.fn() },}));-vi.mock('@/services/plugin', () => ({ pluginService: { installPlugin: vi.fn() } }));+vi.mock('./installMarketplaceConnector', () => ({ installMarketplaceConnector: vi.fn() }));vi.mock('@/utils/sleep', () => ({ sleep: async () => {} }));const HOSTED_URL = 'https://runtime.example.com/runtimes/hosted-mcp/invocations';@@ -106,7 +106,7 @@ beforeEach(() => {identifier: 'hosted-mcp',meta: { title: 'Hosted MCP' },} as never);- vi.mocked(pluginService.installPlugin).mockResolvedValue(undefined);+ vi.mocked(installMarketplaceConnector).mockResolvedValue(undefined);});afterEach(() => vi.restoreAllMocks());@@ -130,13 +130,17 @@ describe('hosted MCP plugins that need user config', () => {expect.anything(),expect.any(AbortSignal),);- expect(pluginService.installPlugin).toHaveBeenCalledWith(+ expect(installMarketplaceConnector).toHaveBeenCalledWith(expect.objectContaining({- // The stored connection keeps the template; the key stays in settings- customParams: {- mcp: expect.objectContaining({ args: stdioConnection.args, type: 'stdio' }),- },+ // A connector has no settings to fill the args on each call: it stores them filled+ connection: expect.objectContaining({+ args: ['-y', 'hosted-mcp', 'API_KEY=user-key'],+ command: 'npx',+ env: { API_KEY: 'user-key' },+ type: 'stdio',+ }),}),+ expect.any(Function),);});@@ -146,10 +150,9 @@ describe('hosted MCP plugins that need user config', () => {await actions.installMCPPlugin('hosted-mcp');expect(mcpService.checkInstallation).not.toHaveBeenCalled();- expect(pluginService.installPlugin).toHaveBeenCalledWith(- expect.objectContaining({- customParams: { mcp: expect.objectContaining({ type: 'cloud' }) },- }),+ expect(installMarketplaceConnector).toHaveBeenCalledWith(+ expect.objectContaining({ connection: expect.objectContaining({ type: 'cloud' }) }),+ expect.any(Function),);});@@ -159,10 +162,9 @@ describe('hosted MCP plugins that need user config', () => {await actions.installMCPPlugin('hosted-mcp', { config: { API_KEY: 'user-key' } });expect(mcpService.checkInstallation).not.toHaveBeenCalled();- expect(pluginService.installPlugin).toHaveBeenCalledWith(- expect.objectContaining({- customParams: { mcp: expect.objectContaining({ type: 'cloud' }) },- }),+ expect(installMarketplaceConnector).toHaveBeenCalledWith(+ expect.objectContaining({ connection: expect.objectContaining({ type: 'cloud' }) }),+ expect.any(Function),);});});diff --git a/src/store/tool/slices/mcpStore/action.oauth.test.ts b/src/store/tool/slices/mcpStore/action.oauth.test.tsindex b873b25a19b..9e1353a244c 100644--- a/src/store/tool/slices/mcpStore/action.oauth.test.ts+++ b/src/store/tool/slices/mcpStore/action.oauth.test.ts@@ -4,7 +4,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type * as ReplicaModule from '@/libs/replica';import { discoverService } from '@/services/discover';import { mcpService } from '@/services/mcp';-import { pluginService } from '@/services/plugin';import type { ToolStore } from '@/store/tool/store';import { MCPInstallStep } from '@/types/plugins';import type * as ConnectorOAuthModule from '@/utils/connectorOAuth';@@ -31,7 +30,6 @@ vi.mock('@/services/discover', () => ({},}));vi.mock('@/services/mcp', () => ({ mcpService: { getStreamableMcpServerManifest: vi.fn() } }));-vi.mock('@/services/plugin', () => ({ pluginService: { installPlugin: vi.fn() } }));vi.mock('@/utils/sleep', () => ({ sleep: async () => {} }));vi.mock('@/utils/connectorOAuth', async (original) => ({...(await original<typeof ConnectorOAuthModule>()),@@ -55,6 +53,8 @@ const manifestData = {};let state: ToolStore;let actions: ReturnType<typeof createMCPPluginStoreSlice>;+/** Whether the server holds the marketplace row: a fresh install has none until `create`. */+let stored: boolean;const connected = () => ({id: 'connector-1',identifier: 'market-mcp',@@ -83,18 +83,31 @@ const connected = () => ({beforeEach(() => {vi.clearAllMocks();vi.spyOn(console, 'error').mockImplementation(() => {});+ stored = false;state = {mcpInstallProgress: {},mcpInstallAbortControllers: {},connectors: [],installedPlugins: [],- createConnector: vi.fn().mockResolvedValue({ id: 'connector-1', isNew: true }),- deleteConnector: vi.fn().mockResolvedValue(undefined),+ createConnector: vi.fn(async () => {+ const isNew = !stored;+ stored = true;+ state.connectors = [connected() as never];+ return { id: 'connector-1', isNew };+ }),+ deleteConnector: vi.fn(async () => {+ stored = false;+ state.connectors = [];+ }),+ // An OAuth row's edit read: its client config, never its tokens+ getConnectorForEdit: vi.fn(async () => ({ ...connected(), oidcConfig: { scheme: 'dcr' } })),startConnectorOAuth: vi.fn().mockResolvedValue('https://oauth.example/authorize'),fetchConnectors: vi.fn(async () => {- state.connectors = [connected() as never];+ state.connectors = stored ? [connected() as never] : [];}),refreshPlugins: vi.fn().mockResolvedValue(undefined),+ syncConnectorTools: vi.fn().mockResolvedValue(undefined),+ updateConnector: vi.fn().mockResolvedValue(undefined),uninstallPlugin: vi.fn().mockResolvedValue(undefined),updateInstallLoadingState: vi.fn(),updateMCPInstallProgress: (id: string, progress: unknown) => {@@ -111,7 +124,6 @@ beforeEach(() => {structuredClone(manifestData) as never,);vi.mocked(waitForConnectorOAuth).mockResolvedValue(undefined);- vi.mocked(pluginService.installPlugin).mockResolvedValue(undefined);});afterEach(() => vi.restoreAllMocks());@@ -126,7 +138,7 @@ describe('marketplace OAuth MCP installation', () => {MCPInstallStep.AUTHORIZATION_REQUIRED,);expect(mcpService.getStreamableMcpServerManifest).not.toHaveBeenCalled();- expect(pluginService.installPlugin).not.toHaveBeenCalled();+ expect(state.updateConnector).not.toHaveBeenCalled();});it('offers OAuth discovery when an unmarked endpoint returns an authorization challenge', async () => {@@ -143,7 +155,7 @@ describe('marketplace OAuth MCP installation', () => {step: MCPInstallStep.AUTHORIZATION_REQUIRED,connection: { auth: { type: 'oauth2' } },});- expect(pluginService.installPlugin).not.toHaveBeenCalled();+ expect(state.updateConnector).not.toHaveBeenCalled();});it('does not infer OAuth from an unrelated server failure', async () => {@@ -158,15 +170,17 @@ describe('marketplace OAuth MCP installation', () => {expect(mcpStoreSelectors.isMCPInstalling('market-mcp')(state)).toBe(false);});- it('installs the synchronized tools only after successful OAuth without copying tokens to the plugin', async () => {+ it('marks the authorized connector installed only after successful OAuth', async () => {await prepare();expect(await actions.authorizeMCPPlugin('market-mcp')).toBe(true);expect(state.startConnectorOAuth).toHaveBeenCalled();expect(waitForConnectorOAuth).toHaveBeenCalled();- const installed = vi.mocked(pluginService.installPlugin).mock.calls[0][0];- expect(installed.manifest.api.map((tool) => tool.name)).toEqual(['list_tasks']);- expect(installed.manifest.meta?.title).toBe('Market MCP');- expect(JSON.stringify(installed)).not.toContain('accessToken');+ expect(state.updateConnector).toHaveBeenCalledWith('connector-1', {+ metadata: { marketplaceInstalled: true },+ });+ // OAuth already synced the tools on the server; nothing else is written.+ expect(state.syncConnectorTools).not.toHaveBeenCalled();+ expect(state.refreshPlugins).not.toHaveBeenCalled();expect(state.mcpInstallProgress['market-mcp']).toBeUndefined();expect(popup.close).toHaveBeenCalled();});@@ -176,7 +190,7 @@ describe('marketplace OAuth MCP installation', () => {vi.mocked(state.startConnectorOAuth).mockRejectedValueOnce(new Error('Registration rejected'));await actions.authorizeMCPPlugin('market-mcp');expect(state.deleteConnector).toHaveBeenCalledWith('connector-1');- expect(pluginService.installPlugin).not.toHaveBeenCalled();+ expect(state.updateConnector).not.toHaveBeenCalled();expect(state.mcpInstallProgress['market-mcp']).toMatchObject({step: MCPInstallStep.AUTHORIZATION_REQUIRED,errorInfo: { message: 'Registration rejected' },@@ -185,18 +199,52 @@ describe('marketplace OAuth MCP installation', () => {});it('keeps an existing connector if authorization cannot start', async () => {+ stored = true;await prepare();- vi.mocked(state.createConnector).mockResolvedValue({ id: 'connector-1', isNew: false });vi.mocked(state.startConnectorOAuth).mockRejectedValueOnce(new Error('Registration rejected'));await actions.authorizeMCPPlugin('market-mcp');expect(state.deleteConnector).not.toHaveBeenCalled();});+ // `create` rewrote the installed row before the popup opened: a reinstall+ // whose authorization fails must not leave it on the unauthorized endpoint+ it.each([+ ['dismissed', new ConnectorOAuthError('dismissed')],+ ['denied', new ConnectorOAuthError('failed')],+ ['timed out', new ConnectorOAuthError('timeout')],+ ])('restores the row a reinstall replaced when authorization is %s', async (_, error) => {+ stored = true;+ vi.mocked(state.getConnectorForEdit).mockResolvedValue({+ ...connected(),+ metadata: { marketplaceInstalled: true },+ mcpServerUrl: 'https://old.example/mcp',+ oidcConfig: { scheme: 'dcr' },+ } as never);+ vi.mocked(waitForConnectorOAuth).mockRejectedValueOnce(error);+ await prepare();++ await actions.authorizeMCPPlugin('market-mcp');++ expect(state.deleteConnector).not.toHaveBeenCalled();+ expect(state.updateConnector).toHaveBeenCalledTimes(1);+ expect(state.updateConnector).toHaveBeenCalledWith(+ 'connector-1',+ expect.objectContaining({+ metadata: { marketplaceInstalled: true },+ mcpServerUrl: 'https://old.example/mcp',+ }),+ );+ // Its OAuth tokens are withheld from the edit read: its server decides its status+ expect(state.syncConnectorTools).toHaveBeenCalledWith('connector-1', {+ pruneMissingAutoTools: true,+ });+ });+it('does not install when the provider authorization fails', async () => {await prepare();vi.mocked(waitForConnectorOAuth).mockRejectedValueOnce(new ConnectorOAuthError('failed'));await actions.authorizeMCPPlugin('market-mcp');- expect(pluginService.installPlugin).not.toHaveBeenCalled();+ expect(state.updateConnector).not.toHaveBeenCalled();expect(state.mcpInstallProgress['market-mcp']).toMatchObject({step: MCPInstallStep.AUTHORIZATION_REQUIRED,errorInfo: { message: 'failed' },@@ -217,7 +265,7 @@ describe('marketplace OAuth MCP installation', () => {await actions.cancelInstallMCPPlugin('market-mcp');complete();await installation;- expect(pluginService.installPlugin).not.toHaveBeenCalled();+ expect(state.updateConnector).not.toHaveBeenCalled();expect(state.mcpInstallProgress['market-mcp']).toBeUndefined();});@@ -234,7 +282,7 @@ describe('marketplace OAuth MCP installation', () => {);});- it('keeps OAuth credentials and custom headers out of the installed plugin snapshot', async () => {+ it('keeps OAuth credentials out of the install mark', async () => {const data = structuredClone(manifestData);Object.assign(data.deploymentOptions[0].connection.auth, {accessToken: 'private-access-token',@@ -247,13 +295,13 @@ describe('marketplace OAuth MCP installation', () => {vi.mocked(discoverService.getMCPPluginManifest).mockResolvedValue(data as never);await prepare();await actions.authorizeMCPPlugin('market-mcp');- const installed = JSON.stringify(vi.mocked(pluginService.installPlugin).mock.calls[0][0]);- expect(installed).not.toContain('private-access-token');- expect(installed).not.toContain('private-client-secret');- expect(installed).not.toContain('private-header');+ const marked = JSON.stringify(vi.mocked(state.updateConnector).mock.calls[0]);+ expect(marked).toContain('marketplaceInstalled');+ expect(marked).not.toContain('private-access-token');+ expect(marked).not.toContain('private-client-secret');});- it('keeps regular HTTP installations on the existing direct connection path', async () => {+ it('stores a regular HTTP installation as a marketplace connector without OAuth', async () => {const data = structuredClone(manifestData);data.deploymentOptions[0].connection.auth.type = 'none';vi.mocked(discoverService.getMCPPluginManifest).mockResolvedValue(data as never);@@ -262,8 +310,23 @@ describe('marketplace OAuth MCP installation', () => {identifier: 'market-mcp',} as unknown as ToolManifest);expect(await actions.installMCPPlugin('market-mcp')).toBe(true);- expect(state.createConnector).not.toHaveBeenCalled();expect(mcpService.getStreamableMcpServerManifest).toHaveBeenCalled();+ expect(state.startConnectorOAuth).not.toHaveBeenCalled();+ expect(state.createConnector).toHaveBeenCalledWith(+ expect.objectContaining({+ identifier: 'market-mcp',+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://oauth.example/mcp',+ sourceType: 'marketplace',+ }),+ );+ expect(vi.mocked(state.createConnector).mock.calls[0][0]).not.toHaveProperty('oidcConfig');+ expect(state.syncConnectorTools).toHaveBeenCalledWith('connector-1', {+ pruneMissingAutoTools: true,+ });+ expect(state.updateConnector).toHaveBeenCalledWith('connector-1', {+ metadata: { marketplaceInstalled: true },+ });});it('removes the server-held marketplace credential when uninstalling', async () => {@@ -275,39 +338,35 @@ describe('marketplace OAuth MCP installation', () => {},} as never,];- state.connectors = [connected() as never];+ stored = true;await actions.uninstallMCPPlugin('market-mcp');expect(state.deleteConnector).toHaveBeenCalledWith('connector-1');expect(state.uninstallPlugin).toHaveBeenCalledWith('market-mcp');});- it('uninstalls a regular MCP without removing any connector', async () => {+ it('still removes the legacy row when the connector list cannot load', async () => {vi.mocked(state.fetchConnectors).mockRejectedValueOnce(new Error('Connector API unavailable'));await actions.uninstallMCPPlugin('market-mcp');- expect(state.fetchConnectors).not.toHaveBeenCalled();expect(state.deleteConnector).not.toHaveBeenCalled();expect(state.uninstallPlugin).toHaveBeenCalledWith('market-mcp');});- it('confirms cached plugin records before deciding whether to remove OAuth credentials', async () => {- state.installedPlugins = [- { identifier: 'market-mcp', customParams: { mcp: { type: 'http' } } } as never,- ];- state.installedPluginsReplica = { entries: { installed: { source: 'storage' } } } as never;- vi.mocked(state.refreshPlugins).mockImplementationOnce(async () => {- state.installedPluginsReplica = { entries: { installed: { source: 'server' } } } as never;- state.installedPlugins = [- {- identifier: 'market-mcp',- customParams: {- mcp: { type: 'http', url: 'https://oauth.example/mcp', auth: { type: 'oauth2' } },- },- } as never,- ];+ it('removes a connector-only install', async () => {+ vi.mocked(state.fetchConnectors).mockImplementationOnce(async () => {+ state.connectors = [+ { ...connected(), metadata: { marketplaceInstalled: true }, mcpConnectionType: 'cloud' },+ ] as never;});await actions.uninstallMCPPlugin('market-mcp');- expect(state.refreshPlugins).toHaveBeenCalledOnce();expect(state.deleteConnector).toHaveBeenCalledWith('connector-1');expect(state.uninstallPlugin).toHaveBeenCalledWith('market-mcp');});++ it('keeps an endpoint-less marketplace tool projection', async () => {+ vi.mocked(state.fetchConnectors).mockImplementationOnce(async () => {+ state.connectors = [{ ...connected(), mcpConnectionType: null, mcpServerUrl: null }] as never;+ });+ await actions.uninstallMCPPlugin('market-mcp');+ expect(state.deleteConnector).not.toHaveBeenCalled();+ });});diff --git a/src/store/tool/slices/mcpStore/action.test.ts b/src/store/tool/slices/mcpStore/action.test.tsindex f61a9f88955..58dfc315594 100644--- a/src/store/tool/slices/mcpStore/action.test.ts+++ b/src/store/tool/slices/mcpStore/action.test.ts@@ -6,7 +6,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { discoverService } from '@/services/discover';import { mcpService } from '@/services/mcp';-import { pluginService } from '@/services/plugin';import { globalHelpers } from '@/store/global/helpers';import { type CheckMcpInstallResult } from '@/types/plugins';import { MCPInstallStep } from '@/types/plugins';@@ -23,6 +22,7 @@ vi.mock('@/utils/platform', async (importOriginal) => ({vi.mock('@/libs/trpc/client', () => ({asyncClient: {},lambdaClient: {+ connector: { syncToolsFromClientById: { mutate: vi.fn() } },market: {getMcpCategories: { query: vi.fn() },getMcpDetail: { query: vi.fn() },@@ -707,7 +707,16 @@ describe('mcpStore actions', () => {vi.spyOn(discoverService, 'getMCPPluginManifest').mockResolvedValue(mockManifest as any);vi.spyOn(mcpService, 'checkInstallation').mockResolvedValue(mockCheckResult);vi.spyOn(mcpService, 'getStdioMcpServerManifest').mockResolvedValue(mockServerManifest);- vi.spyOn(pluginService, 'installPlugin').mockResolvedValue(undefined);+ // The install lands in user_connectors (payloads: installMarketplaceConnector.test.ts)+ const row = { id: 'connector-1', metadata: null } as any;+ const createConnector = vi.fn(async () => {+ useToolStore.setState({ connectors: [row] });+ return { id: row.id, isNew: true };+ });+ const syncConnectorTools = vi.fn();+ const fetchConnectors = vi.fn();+ act(() => useToolStore.setState({ createConnector, fetchConnectors, syncConnectorTools }));+ act(() => useToolStore.setState({ updateConnector: vi.fn() }));vi.spyOn(discoverService, 'reportMcpInstallResult').mockResolvedValue(undefined as any);vi.spyOn(discoverService, 'getMcpDetail').mockResolvedValue(mockPlugin as any);});@@ -733,8 +742,10 @@ describe('mcpStore actions', () => {});expect(mcpService.checkInstallation).toHaveBeenCalled();expect(mcpService.getStdioMcpServerManifest).toHaveBeenCalled();- expect(pluginService.installPlugin).toHaveBeenCalled();- expect(result.current.refreshPlugins).toHaveBeenCalled();+ expect(result.current.syncConnectorTools).toHaveBeenCalledWith('connector-1', {+ pruneMissingAutoTools: true,+ });+ expect(result.current.refreshPlugins).not.toHaveBeenCalled(); // no legacy plugin row});it('should update progress through installation steps', async () => {@@ -842,7 +853,7 @@ describe('mcpStore actions', () => {});expect(installResult).toBe(false);- expect(pluginService.installPlugin).not.toHaveBeenCalled();+ expect(useToolStore.getState().createConnector).not.toHaveBeenCalled();});it('should skip dependencies check when skipDepsCheck is true', async () => {@@ -867,7 +878,7 @@ describe('mcpStore actions', () => {});expect(installResult).toBe(true);- expect(pluginService.installPlugin).toHaveBeenCalled();+ expect(useToolStore.getState().createConnector).toHaveBeenCalled();});});@@ -898,7 +909,7 @@ describe('mcpStore actions', () => {});expect(installResult).toBe(false);- expect(pluginService.installPlugin).not.toHaveBeenCalled();+ expect(useToolStore.getState().createConnector).not.toHaveBeenCalled();});});@@ -964,8 +975,6 @@ describe('mcpStore actions', () => {});});- const installPluginSpy = vi.spyOn(pluginService, 'installPlugin');-let installResult;await act(async () => {installResult = await result.current.installMCPPlugin('test-plugin');@@ -973,16 +982,9 @@ describe('mcpStore actions', () => {expect(installResult).toBe(true);- // Should create cloud type connection- expect(installPluginSpy).toHaveBeenCalledWith(- expect.objectContaining({- customParams: expect.objectContaining({- mcp: expect.objectContaining({- type: 'cloud',- cloudEndPoint: true,- }),- }),- }),+ // Should create a cloud type connector+ expect(result.current.createConnector).toHaveBeenCalledWith(+ expect.objectContaining({ mcpConnectionType: 'cloud', sourceType: 'marketplace' }),);// Should NOT call stdio connection@@ -1169,18 +1171,12 @@ describe('mcpStore actions', () => {});});- const installPluginSpy = vi.spyOn(pluginService, 'installPlugin');-await act(async () => {await result.current.installMCPPlugin('test-plugin');});- expect(installPluginSpy).toHaveBeenCalledWith(- expect.objectContaining({- manifest: expect.objectContaining({- version: '1.5.0',- }),- }),+ expect(discoverService.reportMcpInstallResult).toHaveBeenCalledWith(+ expect.objectContaining({ success: true, version: '1.5.0' }),);});});@@ -1211,7 +1207,7 @@ describe('mcpStore actions', () => {});// Should not install if cancelled- expect(pluginService.installPlugin).not.toHaveBeenCalled();+ expect(useToolStore.getState().createConnector).not.toHaveBeenCalled();});});@@ -1298,7 +1294,7 @@ describe('mcpStore actions', () => {});expect(installResult).toBeUndefined();- expect(pluginService.installPlugin).not.toHaveBeenCalled();+ expect(useToolStore.getState().createConnector).not.toHaveBeenCalled();});it('should return undefined if installation check fails', async () => {diff --git a/src/store/tool/slices/mcpStore/action.ts b/src/store/tool/slices/mcpStore/action.tsindex 53f578e161a..a1b627a3b75 100644--- a/src/store/tool/slices/mcpStore/action.ts+++ b/src/store/tool/slices/mcpStore/action.ts@@ -1,4 +1,4 @@-import { CURRENT_VERSION, isDesktop } from '@lobechat/const';+import { CURRENT_VERSION, hasCallableMcpEndpoint, isDesktop } from '@lobechat/const';import { type ToolManifest } from '@lobechat/types';import { type PluginItem } from '@lobehub/market-sdk';import { type TRPCClientError } from '@trpc/client';@@ -18,7 +18,6 @@ import {} from '@/libs/replica';import { discoverService } from '@/services/discover';import { mcpService } from '@/services/mcp';-import { pluginService } from '@/services/plugin';import { globalHelpers } from '@/store/global/helpers';import { mcpStoreSelectors } from '@/store/tool/selectors';import { type StoreSetter } from '@/store/types';@@ -36,8 +35,14 @@ import { sleep } from '@/utils/sleep';import { setNamespace } from '@/utils/storeDebug';import { type ToolStore } from '../../store';-import { pluginSelectors } from '../plugin/selectors';+import {+ type ConnectorSnapshot,+ restoreConnector,+ snapshotReplacedConnector,+} from '../connector/replaceConnector';+import { buildCloudMcpManifest } from './cloudManifest';import { type MCPPluginListData, type MCPStoreState } from './initialState';+import { installMarketplaceConnector } from './installMarketplaceConnector';import { installOAuthPlugin } from './installOAuthPlugin';import { MCP_PLUGIN_LIST_KEY, type MCPPluginListParams, mcpPluginListResource } from './projection';@@ -76,70 +81,6 @@ const toNonEmptyStringRecord = (input?: Record<string, any>) => {}, {});};-/**- * Build manifest for cloud MCP connection from market data- */-const buildCloudMcpManifest = (params: {- data: any;- plugin: { description?: string; icon?: string; identifier: string };-}): ToolManifest => {- const { data, plugin } = params;-- log('Using cloud connection, building manifest from market data');-- // Get tools (MCP format) or api (LobeChat format) from data- const mcpTools = data.tools;- const lobeChatApi = data.api;-- // If MCP format tools, need to convert to LobeChat api format- // MCP: { name, description, inputSchema }- // LobeChat: { name, description, parameters }- let apiArray: any[] = [];-- if (lobeChatApi) {- // Already in LobeChat format, use directly- apiArray = lobeChatApi;- log('[Cloud MCP] Using existing LobeChat API format');- } else if (mcpTools && Array.isArray(mcpTools)) {- // Convert MCP tools format to LobeChat api format- apiArray = mcpTools.map((tool: any) => ({- description: tool.description || '',- name: tool.name,- parameters: tool.inputSchema || {},- }));- log('[Cloud MCP] Converted %d MCP tools to LobeChat API format', apiArray.length);- } else {- console.warn('[Cloud MCP] No tools or api found in manifest data');- }-- // Build complete manifest- const manifest: ToolManifest = {- api: apiArray,- author: data.author?.name || data.author || '',- createAt: data.createdAt || new Date().toISOString(),- homepage: data.homepage || '',- identifier: plugin.identifier,- manifest: data.manifestUrl || '',- meta: {- avatar: data.icon || plugin.icon,- description: plugin.description || data.description,- tags: data.tags || [],- title: data.name || plugin.identifier,- },- name: data.name || plugin.identifier,- type: 'mcp',- version: data.version,- } as unknown as ToolManifest;-- log('[Cloud MCP] Final manifest built:', {- apiCount: manifest.api?.length,- identifier: manifest.identifier,- version: manifest.version,- });-- return manifest;-};-// Test connection result typeexport interface TestMcpConnectionResult {error?: string;@@ -277,7 +218,7 @@ export class PluginMCPStoreActionImpl {// Extract haveCloudEndpoint after plugin is loadedconst { haveCloudEndpoint } = plugin || {};- const { updateInstallLoadingState, refreshPlugins, updateMCPInstallProgress } = this.#get();+ const { updateInstallLoadingState, updateMCPInstallProgress } = this.#get();// Create AbortController for canceling installationconst abortController = new AbortController();@@ -560,11 +501,14 @@ export class PluginMCPStoreActionImpl {}let manifest: ToolManifest | undefined;+ // The marketplace row an OAuth install authorizes over, read before the+ // authorization rewrites it, so a cancel while finishing can restore it+ let oauthReplaced: ConnectorSnapshot | undefined;if (connection?.type === 'stdio') {manifest = await mcpService.getStdioMcpServerManifest({- // Config placeholders in args are filled here; the stored connection keeps them+ // Config placeholders in args are filled here and in the stored connectorargs: renderMcpArgs(connection.args, normalizedConfig),command: connection.command!,env: mergedStdioEnv,@@ -592,6 +536,8 @@ export class PluginMCPStoreActionImpl {progress: 70,step: MCPInstallStep.AUTHORIZING,});+ const replaced = await snapshotReplacedConnector(identifier, 'marketplace', this.#get);+ oauthReplaced = replaced;manifest = await installOAuthPlugin({connection: { ...connection, headers: mergedHttpHeaders },@@ -603,7 +549,17 @@ export class PluginMCPStoreActionImpl {signal: abortController.signal,},this.#get,- );+ ).catch(async (error: unknown) => {+ // The row was rewritten before the popup opened: an authorization+ // that is denied, dismissed, timed out or canceled puts back the one+ // it replaced. A row it created stays unmarked, so uncallable.+ if (replaced) {+ await restoreConnector(replaced, this.#get).catch((restoreError) => {+ log('restore of connector %s failed: %O', identifier, restoreError);+ });+ }+ throw error;+ });} else {manifest = await mcpService.getStreamableMcpServerManifest({@@ -674,6 +630,12 @@ export class PluginMCPStoreActionImpl {if (finalConnection.type === 'http' && mergedHttpHeaders && !isOAuth) {finalConnection.headers = mergedHttpHeaders;}+ // A connector has no plugin settings to fill `{{KEY}}` placeholders on+ // each call: it stores the URL and args this install connected with.+ if (finalConnection.type === 'http' && !isOAuth && httpUrl) finalConnection.url = httpUrl;+ if (finalConnection.type === 'stdio') {+ finalConnection.args = renderMcpArgs(connection.args, normalizedConfig);+ }if (finalConnection.type === 'stdio' && mergedStdioEnv) {finalConnection.env = mergedStdioEnv;}@@ -681,22 +643,27 @@ export class PluginMCPStoreActionImpl {finalConnection.headers = mergedCloudHeaders;}- await pluginService.installPlugin({- // For mcp, store connection info in customParams field first- customParams: { mcp: finalConnection },- identifier: plugin.identifier,- manifest,- settings: isOAuth ? undefined : normalizedConfig,- type: 'plugin',- });+ // The install lands in `user_connectors`; no `user_installed_plugins` row is written.+ await installMarketplaceConnector(+ {+ connection: finalConnection,+ description: plugin.description,+ icon: plugin.icon,+ identifier: plugin.identifier,+ isOAuth,+ oauthReplaced,+ manifest,+ name: manifest.meta?.title || data.name || plugin.identifier,+ signal: abortController.signal,+ },+ this.#get,+ );// Check if already cancelledif (abortController.signal.aborted) {return;}- await refreshPlugins();-// Step 7: Complete installationupdateMCPInstallProgress(identifier, {progress: 100,@@ -991,21 +958,22 @@ export class PluginMCPStoreActionImpl {};uninstallMCPPlugin = async (identifier: string): Promise<void> => {- // Persisted display projections omit OAuth configuration. Confirm them- // before deciding whether this installation owns server-held credentials.- if (pluginSelectors.isInstalledPluginsCacheOnly(this.#get())) {- await this.#get().refreshPlugins();- }- const connection = pluginSelectors.getInstalledPluginById(identifier)(this.#get())?.customParams- ?.mcp;- if (connection?.type === 'http' && connection.auth?.type === 'oauth2') {- await this.#get().fetchConnectors();- const connector = this.#get().connectors.find(- (item) =>- item.identifier === identifier && item.sourceType === 'marketplace' && item.mcpServerUrl,- );- if (connector) await this.#get().deleteConnector(connector.id);- }+ // The install's connector: every install since connectors, and the OAuth+ // credentials of older ones. Endpoint-less rows are only tool projections.+ // Best effort: with the list unavailable, match what the store already holds.+ await this.#get()+ .fetchConnectors()+ .catch(() => {});+ const connector = this.#get().connectors.find(+ (item) =>+ item.identifier === identifier &&+ item.sourceType === 'marketplace' &&+ hasCallableMcpEndpoint(item),+ );+ if (connector) await this.#get().deleteConnector(connector.id);++ // Installs made before connectors also keep a legacy plugin row; removing+ // a missing one is a no-op on the server.await this.#get().uninstallPlugin(identifier);discoverService.reportMcpEvent({diff --git a/src/store/tool/slices/mcpStore/action.urlTemplate.test.ts b/src/store/tool/slices/mcpStore/action.urlTemplate.test.tsindex b4e25946e66..d9da495123f 100644--- a/src/store/tool/slices/mcpStore/action.urlTemplate.test.ts+++ b/src/store/tool/slices/mcpStore/action.urlTemplate.test.ts@@ -3,10 +3,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type * as ReplicaModule from '@/libs/replica';import { discoverService } from '@/services/discover';import { mcpService } from '@/services/mcp';-import { pluginService } from '@/services/plugin';import type { ToolStore } from '@/store/tool/store';import { createMCPPluginStoreSlice } from './action';+import { installMarketplaceConnector } from './installMarketplaceConnector';vi.mock('@/libs/replica', async (original) => ({...(await original<typeof ReplicaModule>()),@@ -26,7 +26,7 @@ vi.mock('@/services/discover', () => ({},}));vi.mock('@/services/mcp', () => ({ mcpService: { getStreamableMcpServerManifest: vi.fn() } }));-vi.mock('@/services/plugin', () => ({ pluginService: { installPlugin: vi.fn() } }));+vi.mock('./installMarketplaceConnector', () => ({ installMarketplaceConnector: vi.fn() }));vi.mock('@/utils/sleep', () => ({ sleep: async () => {} }));const TEMPLATE_URL = 'https://quotes.example.com/mcp?apikey={{API_KEY}}';@@ -78,7 +78,7 @@ beforeEach(() => {identifier: 'quote-mcp',meta: { title: 'Quote MCP' },} as never);- vi.mocked(pluginService.installPlugin).mockResolvedValue(undefined);+ vi.mocked(installMarketplaceConnector).mockResolvedValue(undefined);});afterEach(() => vi.restoreAllMocks());@@ -98,23 +98,22 @@ describe('marketplace HTTP MCP with config placeholders in the URL', () => {);});- it('stores the template URL so the key stays in settings, not in the saved connection', async () => {+ // A connector has no plugin settings to fill the template on each call+ it('stores the URL the install connected with on the connector', async () => {await actions.installMCPPlugin('quote-mcp', {config: { API_KEY: 'k&1', X_REGION: 'eu' },resume: false,});- expect(pluginService.installPlugin).toHaveBeenCalledWith(+ expect(installMarketplaceConnector).toHaveBeenCalledWith(expect.objectContaining({- customParams: {- mcp: expect.objectContaining({- headers: { 'X-Client': 'lobehub', 'X_REGION': 'eu' },- type: 'http',- url: TEMPLATE_URL,- }),- },- settings: { API_KEY: 'k&1', X_REGION: 'eu' },+ connection: expect.objectContaining({+ headers: { 'X-Client': 'lobehub', 'X_REGION': 'eu' },+ type: 'http',+ url: 'https://quotes.example.com/mcp?apikey=k%261',+ }),}),+ expect.any(Function),);});});diff --git a/src/store/tool/slices/mcpStore/cloudManifest.ts b/src/store/tool/slices/mcpStore/cloudManifest.tsnew file mode 100644index 00000000000..c5183d1e9f6--- /dev/null+++ b/src/store/tool/slices/mcpStore/cloudManifest.ts@@ -0,0 +1,81 @@+import type { ToolManifest } from '@lobechat/types';+import debug from 'debug';++const log = debug('lobe-mcp:store:cloudManifest');++/**+ * Build manifest for cloud MCP connection from market data+ */+export const buildCloudMcpManifest = (params: {+ data: any;+ plugin: { description?: string; icon?: string; identifier: string };+}): ToolManifest => {+ const { data, plugin } = params;++ log('Using cloud connection, building manifest from market data');++ // Get tools (MCP format) or api (LobeChat format) from data+ const mcpTools = data.tools;+ const lobeChatApi = data.api;++ // If MCP format tools, need to convert to LobeChat api format+ // MCP: { name, description, inputSchema }+ // LobeChat: { name, description, parameters }+ let apiArray: any[] = [];++ if (lobeChatApi) {+ // Already in LobeChat format, use directly+ apiArray = lobeChatApi;+ log('[Cloud MCP] Using existing LobeChat API format');+ } else if (mcpTools && Array.isArray(mcpTools)) {+ // Convert MCP tools format to LobeChat api format+ apiArray = mcpTools.map((tool: any) => ({+ description: tool.description || '',+ name: tool.name,+ parameters: tool.inputSchema || {},+ }));+ log('[Cloud MCP] Converted %d MCP tools to LobeChat API format', apiArray.length);+ } else {+ console.warn('[Cloud MCP] No tools or api found in manifest data');+ }++ // Build complete manifest+ const manifest: ToolManifest = {+ api: apiArray,+ author: data.author?.name || data.author || '',+ createAt: data.createdAt || new Date().toISOString(),+ homepage: data.homepage || '',+ identifier: plugin.identifier,+ manifest: data.manifestUrl || '',+ meta: {+ avatar: data.icon || plugin.icon,+ description: plugin.description || data.description,+ tags: data.tags || [],+ title: data.name || plugin.identifier,+ },+ name: data.name || plugin.identifier,+ type: 'mcp',+ version: data.version,+ } as unknown as ToolManifest;++ log('[Cloud MCP] Final manifest built:', {+ apiCount: manifest.api?.length,+ identifier: manifest.identifier,+ version: manifest.version,+ });++ return manifest;+};++/**+ * A cloud server's tools as `connector.syncToolsFromClientById` stores them.+ * The manifest's `humanIntervention` carries over, so a tool the market marks+ * `required` / `always` is synced as needing approval.+ */+export const cloudManifestTools = (manifest: ToolManifest) =>+ (manifest.api ?? []).map((api) => ({+ description: api.description,+ humanIntervention: api.humanIntervention,+ inputSchema: api.parameters as Record<string, unknown>,+ toolName: api.name,+ }));diff --git a/src/store/tool/slices/mcpStore/installMarketplaceConnector.test.ts b/src/store/tool/slices/mcpStore/installMarketplaceConnector.test.tsnew file mode 100644index 00000000000..9c02aac8d6b--- /dev/null+++ b/src/store/tool/slices/mcpStore/installMarketplaceConnector.test.ts@@ -0,0 +1,514 @@+import type { ToolManifest } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { lambdaClient } from '@/libs/trpc/client';+import type { ToolStore } from '@/store/tool/store';++import { installMarketplaceConnector } from './installMarketplaceConnector';++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ connector: { syncToolsFromClientById: { mutate: vi.fn() } },+ },+}));++const manifest = {+ api: [{ description: 'Search', name: 'search', parameters: { type: 'object' } }],+ identifier: 'market-mcp',+} as unknown as ToolManifest;++let state: ToolStore;++const install = (connection: Record<string, any>, patch: { isOAuth?: boolean } = {}) =>+ installMarketplaceConnector(+ {+ connection,+ description: 'desc',+ icon: 'icon',+ identifier: 'market-mcp',+ isOAuth: patch.isOAuth ?? false,+ manifest,+ name: 'Market MCP',+ signal: new AbortController().signal,+ },+ () => state,+ );++beforeEach(() => {+ vi.clearAllMocks();+ state = {+ connectors: [],+ createConnector: vi.fn(async () => {+ state.connectors = [{ id: 'connector-1', metadata: { avatar: 'icon' } }] as never;+ return { id: 'connector-1', isNew: true };+ }),+ deleteConnector: vi.fn().mockResolvedValue(undefined),+ fetchConnectors: vi.fn().mockResolvedValue(undefined),+ getConnectorForEdit: vi.fn(),+ syncConnectorTools: vi.fn().mockResolvedValue(undefined),+ updateConnector: vi.fn().mockResolvedValue(undefined),+ } as unknown as ToolStore;+});++describe('installMarketplaceConnector', () => {+ it('creates an http connector, syncs its tools on the server and marks the install', async () => {+ await install({+ auth: { token: 'secret', type: 'bearer' },+ headers: { 'X-Key': 'k' },+ type: 'http',+ url: 'https://mcp.example.com',+ });++ expect(state.createConnector).toHaveBeenCalledWith({+ credentials: { token: 'secret', type: 'bearer' },+ identifier: 'market-mcp',+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://mcp.example.com',+ metadata: { avatar: 'icon', customHeaders: { 'X-Key': 'k' }, description: 'desc' },+ name: 'Market MCP',+ sourceType: 'marketplace',+ });+ expect(state.syncConnectorTools).toHaveBeenCalledWith('connector-1', {+ pruneMissingAutoTools: true,+ });+ expect(state.updateConnector).toHaveBeenCalledWith('connector-1', {+ metadata: { avatar: 'icon', marketplaceInstalled: true },+ });+ });++ // Each call reported to the Market names the version that was installed+ it('records the manifest version it installed', async () => {+ await installMarketplaceConnector(+ {+ connection: { type: 'http', url: 'https://mcp.example.com' },+ identifier: 'market-mcp',+ isOAuth: false,+ manifest: { ...manifest, version: '1.2.0' },+ name: 'Market MCP',+ signal: new AbortController().signal,+ },+ () => state,+ );++ expect(vi.mocked(state.createConnector).mock.calls[0][0].metadata).toMatchObject({+ version: '1.2.0',+ });+ });++ it('stores a stdio command on the connector', async () => {+ await install({ args: ['-y', 'pkg'], command: 'npx', env: { A: '1' }, type: 'stdio' });++ expect(state.createConnector).toHaveBeenCalledWith(+ expect.objectContaining({+ mcpConnectionType: 'stdio',+ mcpStdioConfig: { args: ['-y', 'pkg'], command: 'npx', env: { A: '1' } },+ }),+ );+ expect(state.syncConnectorTools).toHaveBeenCalledWith('connector-1', {+ pruneMissingAutoTools: true,+ });+ });++ it('syncs a cloud connector from the market manifest instead of connecting', async () => {+ await install({ cloudEndPoint: 'https://cloud.example', type: 'cloud' });++ expect(state.createConnector).toHaveBeenCalledWith(+ expect.objectContaining({+ mcpConnectionType: 'cloud',+ metadata: expect.objectContaining({ cloudEndPoint: 'https://cloud.example' }),+ }),+ );+ expect(state.syncConnectorTools).not.toHaveBeenCalled();+ // A reinstall's manifest replaces the stored tools: the ones it dropped go+ expect(lambdaClient.connector.syncToolsFromClientById.mutate).toHaveBeenCalledWith({+ id: 'connector-1',+ pruneMissingAutoTools: true,+ tools: [{ description: 'Search', inputSchema: { type: 'object' }, toolName: 'search' }],+ });+ });++ it("carries a cloud manifest's approval requirements into the synced tools", async () => {+ const api = [+ { description: 'Send', humanIntervention: 'required', name: 'send', parameters: {} },+ { description: 'Wipe', humanIntervention: 'always', name: 'wipe', parameters: {} },+ ];+ await installMarketplaceConnector(+ {+ connection: { cloudEndPoint: 'https://cloud.example', type: 'cloud' },+ identifier: 'market-mcp',+ isOAuth: false,+ manifest: { ...manifest, api } as unknown as ToolManifest,+ name: 'Market MCP',+ signal: new AbortController().signal,+ },+ () => state,+ );++ expect(lambdaClient.connector.syncToolsFromClientById.mutate).toHaveBeenCalledWith({+ id: 'connector-1',+ pruneMissingAutoTools: true,+ tools: [+ expect.objectContaining({ humanIntervention: 'required', toolName: 'send' }),+ expect.objectContaining({ humanIntervention: 'always', toolName: 'wipe' }),+ ],+ });+ });++ it('only marks the connector an OAuth install already authorized', async () => {+ state.connectors = [{ id: 'oauth-1', identifier: 'market-mcp', metadata: null }] as never;++ await install(+ { auth: { type: 'oauth2' }, type: 'http', url: 'https://mcp.example.com' },+ {+ isOAuth: true,+ },+ );++ expect(state.createConnector).not.toHaveBeenCalled();+ expect(state.syncConnectorTools).not.toHaveBeenCalled();+ expect(state.updateConnector).toHaveBeenCalledWith('oauth-1', {+ metadata: { marketplaceInstalled: true },+ });+ });++ // The authorization's own sync only adds to the tools of the row it reused+ it('lists the tools of an OAuth reinstall again, so the ones its server dropped go', async () => {+ state.connectors = [{ id: 'oauth-1', identifier: 'market-mcp', metadata: null }] as never;++ await installMarketplaceConnector(+ {+ connection: { auth: { type: 'oauth2' }, type: 'http', url: 'https://mcp.example.com' },+ identifier: 'market-mcp',+ isOAuth: true,+ manifest,+ name: 'Market MCP',+ oauthReplaced: { id: 'oauth-1', status: 'connected', tools: [] } as never,+ signal: new AbortController().signal,+ },+ () => state,+ );++ expect(state.createConnector).not.toHaveBeenCalled();+ expect(state.syncConnectorTools).toHaveBeenCalledWith('oauth-1', {+ pruneMissingAutoTools: true,+ });+ expect(vi.mocked(state.syncConnectorTools).mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(state.updateConnector).mock.invocationCallOrder[0],+ );+ });++ it('removes the connector it created and leaves no install mark when the sync fails', async () => {+ vi.mocked(state.syncConnectorTools).mockRejectedValue(new Error('unreachable'));++ await expect(install({ type: 'http', url: 'https://down.example' })).rejects.toThrow(+ 'unreachable',+ );+ expect(state.deleteConnector).toHaveBeenCalledWith('connector-1');+ expect(state.updateConnector).not.toHaveBeenCalled();+ });++ it('leaves the install mark off the replacement until its tools are synced', async () => {+ state.connectors = [+ {+ id: 'connector-1',+ identifier: 'market-mcp',+ metadata: { marketplaceInstalled: true },+ sourceType: 'marketplace',+ },+ ] as never;+ vi.mocked(state.getConnectorForEdit).mockResolvedValue({+ metadata: { marketplaceInstalled: true },+ } as never);+ vi.mocked(state.createConnector).mockImplementation(async () => {+ state.connectors = [{ id: 'connector-1', metadata: { avatar: 'icon' } }] as never;+ return { id: 'connector-1', isNew: false };+ });++ await install({ type: 'http', url: 'https://mcp.example.com' });++ expect(vi.mocked(state.createConnector).mock.calls[0][0].metadata).not.toHaveProperty(+ 'marketplaceInstalled',+ );+ expect(vi.mocked(state.syncConnectorTools).mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(state.updateConnector).mock.invocationCallOrder[0],+ );+ expect(state.updateConnector).toHaveBeenCalledWith('connector-1', {+ metadata: { avatar: 'icon', marketplaceInstalled: true },+ });+ });++ it('does not write the mark alone when the created row cannot be loaded', async () => {+ vi.mocked(state.createConnector).mockResolvedValue({ id: 'connector-1', isNew: true });++ await expect(install({ type: 'http', url: 'https://mcp.example.com' })).rejects.toThrow(+ 'could not be loaded',+ );+ expect(state.updateConnector).not.toHaveBeenCalled();+ expect(state.deleteConnector).toHaveBeenCalledWith('connector-1');+ });++ it('keeps a connector that existed before the install when the sync fails', async () => {+ vi.mocked(state.createConnector).mockResolvedValue({ id: 'connector-1', isNew: false });+ vi.mocked(state.syncConnectorTools).mockRejectedValue(new Error('unreachable'));++ await expect(install({ type: 'http', url: 'https://down.example' })).rejects.toThrow();+ expect(state.deleteConnector).not.toHaveBeenCalled();+ });++ it('rolls back and leaves no mark when the install is canceled after the connector is created', async () => {+ const controller = new AbortController();+ vi.mocked(state.syncConnectorTools).mockImplementation(async () => controller.abort());++ await expect(+ installMarketplaceConnector(+ {+ connection: { type: 'http', url: 'https://mcp.example.com' },+ identifier: 'market-mcp',+ isOAuth: false,+ manifest,+ name: 'Market MCP',+ signal: controller.signal,+ },+ () => state,+ ),+ ).rejects.toThrow();+ expect(state.deleteConnector).toHaveBeenCalledWith('connector-1');+ expect(state.updateConnector).not.toHaveBeenCalled();+ });++ it('refuses to replace a connector the user added from another source', async () => {+ state.connectors = [+ {+ id: 'custom-1',+ identifier: 'market-mcp',+ mcpServerUrl: 'https://mine.example.com',+ metadata: null,+ sourceType: 'custom',+ },+ ] as never;++ await expect(install({ type: 'http', url: 'https://mcp.example.com' })).rejects.toThrow(+ 'already exists',+ );+ expect(state.createConnector).not.toHaveBeenCalled();+ expect(state.deleteConnector).not.toHaveBeenCalled();+ });++ it('restores the connector it reinstalled over when the sync fails', async () => {+ state.connectors = [+ {+ id: 'connector-1',+ identifier: 'market-mcp',+ metadata: { marketplaceInstalled: true },+ sourceType: 'marketplace',+ },+ ] as never;+ vi.mocked(state.getConnectorForEdit).mockResolvedValue({+ credentials: { token: 'old-token', type: 'bearer' },+ id: 'connector-1',+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://old.example',+ mcpStdioConfig: null,+ metadata: { avatar: 'old', marketplaceInstalled: true },+ name: 'Old MCP',+ oidcConfig: null,+ status: 'connected',+ tools: [+ {+ description: 'Search',+ inputSchema: { type: 'object' },+ metadata: { visibility: ['model'] },+ toolName: 'search',+ },+ ],+ } as never);+ vi.mocked(state.createConnector).mockResolvedValue({ id: 'connector-1', isNew: false });+ vi.mocked(state.syncConnectorTools).mockRejectedValue(new Error('unreachable'));++ await expect(install({ type: 'http', url: 'https://new.example' })).rejects.toThrow(+ 'unreachable',+ );++ expect(state.deleteConnector).not.toHaveBeenCalled();+ expect(state.updateConnector).toHaveBeenCalledWith('connector-1', {+ credentials: { token: 'old-token', type: 'bearer' },+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://old.example',+ mcpStdioConfig: null,+ metadata: { avatar: 'old', marketplaceInstalled: true },+ name: 'Old MCP',+ oidcConfig: null,+ });+ expect(lambdaClient.connector.syncToolsFromClientById.mutate).toHaveBeenCalledWith({+ id: 'connector-1',+ pruneMissingAutoTools: true,+ tools: [+ {+ description: 'Search',+ inputSchema: { type: 'object' },+ toolName: 'search',+ visibility: ['model'],+ },+ ],+ });+ });++ // `createConnector` resolves once the row is written, even when its list+ // refresh fails: the install refreshes again where a failure rolls back+ it('restores the connector it reinstalled over when the list refresh after the create fails', async () => {+ state.connectors = [+ {+ id: 'connector-1',+ identifier: 'market-mcp',+ mcpConnectionType: 'cloud',+ metadata: { marketplaceInstalled: true },+ sourceType: 'marketplace',+ },+ ] as never;+ vi.mocked(state.getConnectorForEdit).mockResolvedValue({+ credentials: null,+ id: 'connector-1',+ isEnabled: true,+ mcpConnectionType: 'cloud',+ mcpServerUrl: null,+ mcpStdioConfig: null,+ metadata: { cloudEndPoint: 'https://cloud.example', marketplaceInstalled: true },+ name: 'Old MCP',+ oidcConfig: null,+ status: 'disconnected',+ tools: [],+ } as never);+ vi.mocked(state.createConnector).mockResolvedValue({ id: 'connector-1', isNew: false });+ // The snapshot's own read succeeds; the refresh after the create does not+ vi.mocked(state.fetchConnectors)+ .mockResolvedValueOnce(undefined)+ .mockRejectedValueOnce(new Error('network down'));++ await expect(install({ type: 'http', url: 'https://new.example' })).rejects.toThrow(+ 'network down',+ );++ expect(state.syncConnectorTools).not.toHaveBeenCalled();+ expect(state.updateConnector).toHaveBeenCalledTimes(1);+ expect(state.updateConnector).toHaveBeenCalledWith(+ 'connector-1',+ expect.objectContaining({+ mcpConnectionType: 'cloud',+ mcpServerUrl: null,+ metadata: { cloudEndPoint: 'https://cloud.example', marketplaceInstalled: true },+ }),+ );+ });++ it('puts a legacy tool projection back off the endpoint a failed reinstall wrote', async () => {+ state.connectors = [+ { id: 'connector-1', identifier: 'market-mcp', metadata: {}, sourceType: 'marketplace' },+ ] as never;+ vi.mocked(state.getConnectorForEdit).mockResolvedValue({+ credentials: null,+ id: 'connector-1',+ isEnabled: true,+ mcpConnectionType: null,+ mcpServerUrl: null,+ mcpStdioConfig: null,+ metadata: {},+ name: 'Legacy MCP',+ oidcConfig: null,+ status: 'connected',+ tools: [{ description: null, inputSchema: null, metadata: null, toolName: 'search' }],+ } as never);+ vi.mocked(state.createConnector).mockResolvedValue({ id: 'connector-1', isNew: false });+ vi.mocked(state.syncConnectorTools).mockRejectedValue(new Error('unreachable'));++ await expect(install({ type: 'http', url: 'https://new.example' })).rejects.toThrow(+ 'unreachable',+ );++ expect(state.updateConnector).toHaveBeenCalledWith(+ 'connector-1',+ expect.objectContaining({+ mcpConnectionType: null,+ mcpServerUrl: null,+ mcpStdioConfig: null,+ }),+ );+ });++ it('rolls back when the install is canceled while the mark is written', async () => {+ const controller = new AbortController();+ vi.mocked(state.updateConnector).mockImplementation(async () => controller.abort());++ await expect(+ installMarketplaceConnector(+ {+ connection: { type: 'http', url: 'https://mcp.example.com' },+ identifier: 'market-mcp',+ isOAuth: false,+ manifest,+ name: 'Market MCP',+ signal: controller.signal,+ },+ () => state,+ ),+ ).rejects.toThrow();+ expect(state.updateConnector).toHaveBeenCalled();+ expect(state.deleteConnector).toHaveBeenCalledWith('connector-1');+ });++ describe('an OAuth install canceled while the mark is written', () => {+ const cancelOAuth = (oauthReplaced?: unknown) => {+ const controller = new AbortController();+ state.connectors = [{ id: 'oauth-1', identifier: 'market-mcp', metadata: null }] as never;+ vi.mocked(state.updateConnector).mockImplementation(async () => controller.abort());++ return installMarketplaceConnector(+ {+ connection: { auth: { type: 'oauth2' }, type: 'http', url: 'https://mcp.example.com' },+ identifier: 'market-mcp',+ isOAuth: true,+ manifest,+ name: 'Market MCP',+ oauthReplaced: oauthReplaced as never,+ signal: controller.signal,+ },+ () => state,+ );+ };++ it('removes the connector its authorization created', async () => {+ await expect(cancelOAuth()).rejects.toThrow();++ expect(state.deleteConnector).toHaveBeenCalledWith('oauth-1');+ });++ it('restores the connector it authorized over, without the mark', async () => {+ const previous = {+ credentials: null,+ id: 'oauth-1',+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://old.example.com',+ mcpStdioConfig: null,+ metadata: { avatar: 'old' },+ name: 'Old MCP',+ oidcConfig: { scheme: 'dcr' },+ status: 'disconnected',+ tools: [],+ };++ await expect(cancelOAuth(previous)).rejects.toThrow();++ expect(state.deleteConnector).not.toHaveBeenCalled();+ // The mark write, then the restore of the previous row+ expect(state.updateConnector).toHaveBeenLastCalledWith(+ 'oauth-1',+ expect.objectContaining({+ metadata: { avatar: 'old' },+ mcpServerUrl: 'https://old.example.com',+ }),+ );+ });+ });+});diff --git a/src/store/tool/slices/mcpStore/installMarketplaceConnector.ts b/src/store/tool/slices/mcpStore/installMarketplaceConnector.tsnew file mode 100644index 00000000000..c038b322817--- /dev/null+++ b/src/store/tool/slices/mcpStore/installMarketplaceConnector.ts@@ -0,0 +1,177 @@+import { MARKETPLACE_INSTALL_COMPLETED_KEY } from '@lobechat/const';+import type { ToolManifest } from '@lobechat/types';+import debug from 'debug';++import { lambdaClient } from '@/libs/trpc/client';+import {+ type ConnectorSnapshot,+ restoreConnector,+ snapshotReplacedConnector,+} from '@/store/tool/slices/connector/replaceConnector';+import { connectorSelectors } from '@/store/tool/slices/connector/selectors';+import type { ToolStore } from '@/store/tool/store';++import { cloudManifestTools } from './cloudManifest';++const log = debug('lobe-mcp:store:installMarketplaceConnector');++type CreateConnectorPayload = Parameters<ToolStore['createConnector']>[0];++interface InstallMarketplaceConnectorParams {+ /** The resolved marketplace connection (`http` / `stdio` / `cloud`), config merged in. */+ connection: Record<string, any>;+ description?: string;+ icon?: string;+ identifier: string;+ /** An OAuth install already created and authorized its connector. */+ isOAuth: boolean;+ /** The manifest read during install; a `cloud` connector takes its tools from it. */+ manifest: ToolManifest;+ name: string;+ /**+ * OAuth only: the marketplace row the authorization overwrote, read before it+ * (`snapshotReplacedConnector`). None means the authorization created the row.+ */+ oauthReplaced?: ConnectorSnapshot;+ signal: AbortSignal;+}++/**+ * The replacement row never carries the install mark, even over a finished+ * install: until its tools are synced it must stay uncallable. The mark is+ * written last, and a failed reinstall restores the previous row with its mark.+ */+const buildCreatePayload = ({+ connection,+ description,+ icon,+ identifier,+ manifest,+ name,+}: InstallMarketplaceConnectorParams): CreateConnectorPayload => {+ // The version goes with each call the Market is told about+ const metadata: Record<string, unknown> = {+ avatar: icon,+ description,+ version: manifest.version,+ };+ if (connection.headers) metadata.customHeaders = connection.headers;+ const base = { identifier, metadata, name, sourceType: 'marketplace' as const };++ switch (connection.type) {+ case 'http': {+ const token = connection.auth?.type === 'bearer' ? connection.auth.token : undefined;+ return {+ ...base,+ credentials: token ? { token, type: 'bearer' } : undefined,+ mcpConnectionType: 'http',+ mcpServerUrl: connection.url,+ };+ }+ case 'stdio': {+ return {+ ...base,+ mcpConnectionType: 'stdio',+ mcpStdioConfig: {+ args: connection.args ?? [],+ command: connection.command,+ env: connection.env,+ },+ };+ }+ case 'cloud': {+ return {+ ...base,+ mcpConnectionType: 'cloud',+ metadata: { ...metadata, cloudEndPoint: connection.cloudEndPoint },+ };+ }+ default: {+ throw new Error(`Unsupported MCP connection type: ${connection.type}`);+ }+ }+};++/**+ * The install's tool list replaces the stored one, as a plugin install replaced+ * its manifest: a reinstall drops the tools the server no longer lists.+ */+const REPLACE_TOOLS = { pruneMissingAutoTools: true };++/** A cloud server runs in the market: its tool list is the manifest the market served. */+const syncCloudTools = async (connectorId: string, manifest: ToolManifest) => {+ await lambdaClient.connector.syncToolsFromClientById.mutate({+ id: connectorId,+ ...REPLACE_TOOLS,+ tools: cloudManifestTools(manifest),+ });+};++/**+ * Store a marketplace MCP install as a `user_connectors` row with its tools,+ * then mark the install finished. Only the mark lets the runtime call a+ * marketplace row (see `isMarketplaceInstallCompleted`). When a later step+ * fails or the install is canceled, a row this call created is removed and a+ * row it reinstalled over is restored.+ */+export const installMarketplaceConnector = async (+ params: InstallMarketplaceConnectorParams,+ get: () => ToolStore,+): Promise<void> => {+ const { identifier, isOAuth, manifest, signal } = params;++ let connectorId: string;+ let isNew = false;+ let snapshot: ConnectorSnapshot | undefined;++ if (isOAuth) {+ const connector = connectorSelectors.connectorByIdentifier(identifier)(get());+ if (!connector) throw new Error('The MCP connector did not finish authorization');+ connectorId = connector.id;+ // Authorization already wrote the row: a cancel while finishing removes the+ // row it created, or restores the one it authorized over+ snapshot = params.oauthReplaced;+ isNew = !params.oauthReplaced;+ } else {+ snapshot = await snapshotReplacedConnector(identifier, 'marketplace', get);+ ({ id: connectorId, isNew } = await get().createConnector(buildCreatePayload(params)));+ }++ try {+ // The create's own list refresh may have failed, leaving the replaced row in+ // the list the steps below read (its transport, its metadata)+ if (!isOAuth) await get().fetchConnectors();+ // An OAuth authorization synced a new row's tools already; over an existing+ // row it only added to them, so a reinstall lists them again to drop the rest+ if (!isOAuth || !isNew) {+ signal.throwIfAborted();+ if (params.connection.type === 'cloud') await syncCloudTools(connectorId, manifest);+ else await get().syncConnectorTools(connectorId, REPLACE_TOOLS);+ }++ signal.throwIfAborted();+ // `update` replaces the whole metadata column: merge onto the stored row,+ // never write the mark alone over headers / endpoint the row carries.+ const connector = connectorSelectors.connectorById(connectorId)(get());+ if (!connector) throw new Error('The installed MCP connector could not be loaded');+ await get().updateConnector(connectorId, {+ metadata: { ...connector.metadata, [MARKETPLACE_INSTALL_COMPLETED_KEY]: true },+ });+ // A cancel that arrived while the mark was written still undoes the install.+ signal.throwIfAborted();+ } catch (error) {+ // A failed rollback is only logged: an unmarked row stays uncallable.+ if (isNew) {+ await get()+ .deleteConnector(connectorId)+ .catch((rollbackError) => {+ log('rollback of connector %s (%s) failed: %O', connectorId, identifier, rollbackError);+ });+ } else if (snapshot) {+ await restoreConnector(snapshot, get).catch((rollbackError) => {+ log('restore of connector %s (%s) failed: %O', connectorId, identifier, rollbackError);+ });+ }+ throw error;+ }+};diff --git a/src/store/tool/slices/plugin/replica.test.ts b/src/store/tool/slices/plugin/replica.test.tsindex e948984493b..1f39718e332 100644--- a/src/store/tool/slices/plugin/replica.test.ts+++ b/src/store/tool/slices/plugin/replica.test.ts@@ -29,7 +29,6 @@ import { pluginSelectors } from './selectors';vi.mock('@/services/plugin', () => ({pluginService: {- createCustomPlugin: vi.fn(),getInstalledPlugins: vi.fn(),uninstallPlugin: vi.fn(),updatePlugin: vi.fn(),@@ -383,7 +382,7 @@ describe('installed plugins replica', () => {});describe('install / uninstall propagation', () => {- it('shows a newly installed plugin and persists it', async () => {+ it('shows a plugin the server now lists and persists it', async () => {await loadFromServer([plugin('p1')]);vi.mocked(pluginService.getInstalledPlugins).mockResolvedValue([plugin('p1'),@@ -391,12 +390,9 @@ describe('installed plugins replica', () => {]);await act(async () => {- await useToolStore- .getState()- .installCustomPlugin({ identifier: 'custom-1', type: 'customPlugin' } as any);+ await useToolStore.getState().refreshPlugins();});- expect(pluginService.createCustomPlugin).toHaveBeenCalled();expect(ids()).toEqual(['p1', 'custom-1']);await waitFor(async () =>expect((await readPersisted())?.map((p) => p.identifier)).toEqual(['p1', 'custom-1']),@@ -412,6 +408,8 @@ describe('installed plugins replica', () => {// The follow-up refresh has not caught up yet: the removal must still hold.vi.mocked(pluginService.getInstalledPlugins).mockImplementation(pending);+ // No marketplace connector backs these legacy rows.+ act(() => useToolStore.setState({ connectors: [], fetchConnectors: async () => {} }));void useToolStore.getState().uninstallMCPPlugin('p1');expect(ids()).toEqual(['p1', 'p2']);diff --git a/src/store/tool/slices/plugin/selectors.test.ts b/src/store/tool/slices/plugin/selectors.test.tsindex 972dda4c82a..81dc46e6bc3 100644--- a/src/store/tool/slices/plugin/selectors.test.ts+++ b/src/store/tool/slices/plugin/selectors.test.ts@@ -169,6 +169,25 @@ describe('pluginSelectors', () => {const result = pluginSelectors.isPluginInstalled('non-installed-plugin')(mockState);expect(result).toBe(false);});++ it('should count a marketplace MCP installed as a connector', () => {+ const connector = {+ identifier: 'market-mcp',+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://mcp.example.com',+ sourceType: 'marketplace',+ };+ const withConnector = (metadata: Record<string, unknown> | null) =>+ ({ ...mockState, connectors: [{ ...connector, metadata }] }) as ToolStoreState;++ expect(+ pluginSelectors.isPluginInstalled('market-mcp')(+ withConnector({ marketplaceInstalled: true }),+ ),+ ).toBe(true);+ // An unfinished install (no mark) is not installed+ expect(pluginSelectors.isPluginInstalled('market-mcp')(withConnector(null))).toBe(false);+ });});describe('getInstalledPluginById', () => {diff --git a/src/store/tool/slices/plugin/selectors.ts b/src/store/tool/slices/plugin/selectors.tsindex 11710a0a773..6419c548eef 100644--- a/src/store/tool/slices/plugin/selectors.ts+++ b/src/store/tool/slices/plugin/selectors.ts@@ -4,6 +4,7 @@ import { isInstalledPluginAvailableInCurrentEnv } from '@/helpers/toolAvailabiliimport { type InstallPluginMeta, type LobeToolCustomPlugin } from '@/types/tool/plugin';import { type ToolStoreState } from '../../initialState';+import { connectorSelectors } from '../connector/selectors';import { INSTALLED_PLUGINS_KEY } from './projection';const EMPTY_PLUGINS: LobeTool[] = [];@@ -36,8 +37,10 @@ const isInstalledPluginsServerConfirmed = (s: ToolStoreState) =>const confirmedInstalledPlugins = (s: ToolStoreState) =>isInstalledPluginsCacheOnly(s) ? EMPTY_PLUGINS : s.installedPlugins;+/** Installed as a legacy plugin row, or as a finished marketplace connector install. */const isPluginInstalled = (id: string) => (s: ToolStoreState) =>- installedPlugins(s).some((i) => i.identifier === id);+ installedPlugins(s).some((i) => i.identifier === id) ||+ connectorSelectors.isMarketplaceConnectorInstalled(id)(s);/** The full record of an installed plugin (see {@link confirmedInstalledPlugins}). */const getInstalledPluginById = (id?: string) => (s: ToolStoreState) => {