🤯 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
✨ feat(mcp): let HTTP MCP servers connect through the user's device (#23056)
Bryana8b501bf87ba
diff --git a/apps/cli/src/commands/connect/index.ts b/apps/cli/src/commands/connect/index.tsindex 53c237fbf78..dbd1a73bb11 100644--- a/apps/cli/src/commands/connect/index.ts+++ b/apps/cli/src/commands/connect/index.ts@@ -49,7 +49,7 @@ import {resolveCliDeviceGateway,} from '../../device/gatewayEndpoint';import { MANAGED_GATEWAY_ENV } from '../../device/managed';-import { disposeDeviceMcp } from '../../device/mcp';+import { disposeDeviceMcp, listDeviceMcpTools } from '../../device/mcp';import {mintWorkspaceConnectToken,registerDevice,@@ -606,6 +606,8 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {...params,env: { ...process.env, ...params.env },}),+ // A server that can't reach an MCP server itself lists its tools here+ listMcpTools: listDeviceMcpTools,restartCli: maintenance.restart,searchProjectFiles: defaultSearchProjectFiles,};diff --git a/apps/cli/src/device/mcp.test.ts b/apps/cli/src/device/mcp.test.tsindex 2bca50d89ec..4e49c10977d 100644--- a/apps/cli/src/device/mcp.test.ts+++ b/apps/cli/src/device/mcp.test.ts@@ -5,7 +5,7 @@ import { fileURLToPath } from 'node:url';import { afterEach, describe, expect, it, vi } from 'vitest';-import { disposeDeviceMcp, executeDeviceMcpCall } from './mcp';+import { disposeDeviceMcp, executeDeviceMcpCall, listDeviceMcpTools } from './mcp';const { resolveUserSpawnPath } = vi.hoisted(() => ({resolveUserSpawnPath: vi.fn(async () => process.env.PATH),@@ -92,3 +92,39 @@ describe('executeDeviceMcpCall', () => {expect(result.error).toBeTruthy();});});++describe('listDeviceMcpTools', () => {+ it(+ 'lists a stdio server on the pooled session its tunneled calls then reuse',+ { timeout: 20_000 },+ async () => {+ const dir = await mkdtemp(path.join(tmpdir(), 'cli-device-mcp-'));+ dirs.push(dir);+ const trace = path.join(dir, 'wire.txt');+ const { params } = stdioCall(trace);++ const tools = await listDeviceMcpTools({ params });+ const call = await executeDeviceMcpCall(stdioCall(trace), () => undefined);++ // As listed, for the server to map like its own listings+ expect(tools.map((tool) => tool.name)).toEqual(['echo']);+ expect(tools[0].inputSchema).toBeDefined();+ expect(call).toMatchObject({ success: true });+ const spawns = (await readFile(trace, 'utf8')).split('\n').filter((line) => line === 'spawn');+ expect(spawns).toHaveLength(1);+ },+ );++ it('fails with the reason when the server cannot start', async () => {+ await expect(+ listDeviceMcpTools({+ params: {+ args: [],+ command: 'lobehub-missing-mcp-server-binary',+ name: 'x',+ type: 'stdio',+ },+ }),+ ).rejects.toThrow();+ });+});diff --git a/apps/cli/src/device/mcp.ts b/apps/cli/src/device/mcp.tsindex 17f0f18c685..43cbf128625 100644--- a/apps/cli/src/device/mcp.ts+++ b/apps/cli/src/device/mcp.ts@@ -1,3 +1,4 @@+import type { ListedMcpServerTool, ListMcpToolsParams } from '@lobechat/device-control';import type { GatewayMcpParams } from '@lobechat/device-gateway-client';import type { DeviceMcpRuntime, MCPClientParams } from '@lobechat/device-mcp';import { resolveUserSpawnPath } from '@lobechat/heterogeneous-agents/resolveCliCommand';@@ -114,6 +115,20 @@ export async function executeDeviceMcpCall(}}+/**+ * List an MCP server's tools on this machine (the `listMcpTools` device RPC),+ * for a server the cloud must not connect to itself: an install, a tool+ * refresh or a connection test. Listed on the runtime the tunneled calls run+ * on, so a stdio server is listed on the session its calls then reuse.+ */+export async function listDeviceMcpTools({+ mcpApps,+ params,+}: ListMcpToolsParams): Promise<ListedMcpServerTool[]> {+ const mcp = await getRuntime();+ return mcp.listTools(await toClientParams(params), { mcpApps });+}+/*** Disconnect every pooled MCP session so no stdio server outlives the process.* Every disconnect starts synchronously, so an exit path that cannot awaitdiff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex 558261fc923..1a4aa487c9c 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -24,12 +24,8 @@ import {} from '@lobechat/heterogeneous-agents/scanHost';import { type ILocalSystemService, LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';import { managedProcessEnvironment, spawnManaged } from '@lobechat/utils/managedProcess';-import { app as electronApp } from 'electron';import { withEmbeddedCliEnv } from '@/modules/cliEmbedding';-import { getRemoteTerminalDeps } from '@/modules/terminal/remote';-import { updaterConfig } from '@/modules/updater/configs';-import { createRemoteAppUpdateDeps } from '@/modules/updater/remoteUpdate';import AuvService, { type AuvRunCommandParams } from '@/services/auvSrv';import { backfillDeviceArchitecture } from '@/services/deviceArchitectureBackfill';import GatewayConnectionService, {@@ -42,6 +38,7 @@ import { setDesktopUserAgentHeader } from '@/utils/user-agent';import BrowserControlCtr from './BrowserControlCtr';import { executeGatewayAgentRun, type PlatformTaskEntry } from './gatewayAgentRun';+import { createDesktopDeviceControlDeps } from './gatewayDeviceControlDeps';import HeterogeneousAgentCtr from './HeterogeneousAgentCtr';import { ControllerModule, createProtocolHandler, IpcMethod } from './index';import LocalFileCtr from './LocalFileCtr';@@ -404,40 +401,7 @@ export default class GatewayConnectionCtr extends ControllerModule {/** Desktop handlers for the shared `@lobechat/device-control` dispatcher. */private get deviceControlDeps(): DeviceControlDeps {- return {- approveProjectRoot: async (root) => {- try {- await this.app.localFileProtocolManager.approveIndexedProjectRoot(root);- } catch (error) {- logger.error(`Failed to approve project preview root ${root}:`, error);- }- },- // Workspace share (server-driven enroll/unenroll RPCs): the service owns- // the gateway connections, so both handlers route straight to it.- enrollWorkspace: (params) => this.service.enrollWorkspace(params),- getLocalFilePreview: (params) => this.localFileCtr.getLocalFilePreview(params),- readExternalAssetForPublish: (params) =>- this.localFileCtr.readExternalAssetForPublish(params),- copyAssetForPublish: (params) => this.localFileCtr.copyAssetForPublish(params),- getProjectFileIndex: (params) => this.localFileCtr.getProjectFileIndex(params),- listHeterogeneousAgentModels: (params) => this.heterogeneousAgentCtr.listModels(params),- searchProjectFiles: (params) => this.localFileCtr.searchProjectFiles(params),- // Remote "delete" goes to this machine's trash (`shell.trashItem`), same- // as the local Files tree, so it stays recoverable.- trashLocalFiles: (params) => this.localFileCtr.trashLocalFiles(params),- unenrollWorkspace: (params) => this.service.unenrollWorkspace(params),- // Skill-archive cache (`prepareSkillDirectory` RPC): reuse LocalFileCtr's- // deps so gateway-prepared skills share one cache with the renderer-IPC path.- ...this.localFileCtr.getSkillDirectoryDeps(),- // Remote app update from the web device page, over the same updater the- // local "Check for updates" menu drives.- ...createRemoteAppUpdateDeps({- currentVersion: electronApp.getVersion(),- enabled: updaterConfig.enableAppUpdate,- getUpdater: () => this.app.getUpdaterManager(),- }),- ...getRemoteTerminalDeps(),- };+ return createDesktopDeviceControlDeps(this.app);}/**diff --git a/apps/desktop/src/main/controllers/McpCtr.ts b/apps/desktop/src/main/controllers/McpCtr.tsindex f6b800b814f..704c26cf3b4 100644--- a/apps/desktop/src/main/controllers/McpCtr.ts+++ b/apps/desktop/src/main/controllers/McpCtr.ts@@ -6,6 +6,7 @@ import {partitionMcpToolsForViews,resolveMcpUiToolMeta,} from '@lobechat/const/mcpApp';+import type { ListMcpToolsParams } from '@lobechat/device-control';import {DeviceMcpRuntime,type McpCallOptions,@@ -383,6 +384,33 @@ export default class McpCtr extends ControllerModule {);}+ /**+ * The device-gateway `listMcpTools` RPC: the cloud server can't reach this+ * MCP server (stdio, an endpoint on this machine's network, or one the user+ * set to connect through this device), so it asks this machine for the tool+ * list and maps it as it maps its own listings. The tools go back as listed.+ * Listed by the same runtime the tunneled calls run on.+ */+ async listToolsForGateway({ mcpApps, params }: ListMcpToolsParams): Promise<McpTool[]> {+ const client: MCPClientParams =+ params.type === 'http'+ ? {+ auth: params.auth,+ headers: params.headers,+ name: params.name,+ type: 'http',+ url: params.url,+ }+ : {+ args: params.args ?? [],+ command: params.command,+ env: params.env,+ name: params.name,+ type: 'stdio',+ };+ return this.runtime.listTools(client, { mcpApps });+ }+@IpcMethod()async callTool(payload: SuperJSONSerialized<CallToolInput>) {const input = deserializePayload<CallToolInput>(payload);diff --git a/apps/desktop/src/main/controllers/__tests__/McpCtr.gatewayList.test.ts b/apps/desktop/src/main/controllers/__tests__/McpCtr.gatewayList.test.tsnew file mode 100644index 00000000000..092dc2fb014--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/McpCtr.gatewayList.test.ts@@ -0,0 +1,112 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import McpCtr from '../McpCtr';++// The device gateway's `listMcpTools`: the server asks this desktop for the+// tools of an MCP server only this machine reaches, listed on the runtime the+// tunneled calls run on.++const { clientParams, mcpClientMocks } = vi.hoisted(() => ({+ clientParams: [] as unknown[],+ mcpClientMocks: vi.fn(),+}));++// The shared device MCP runtime lazily imports its client module; mock it so+// no real server is contacted+vi.mock('@lobechat/device-mcp/client', () => ({+ MCPClient: class {+ constructor(params: unknown) {+ clientParams.push(params);+ return mcpClientMocks();+ }+ },+ MCPConnectionError: class extends Error {+ name = 'MCPConnectionError';+ stderrLogs: string[] = [];+ },+}));++const mockApp = { getService: vi.fn(() => null) } as unknown as App;++const tools = [+ { inputSchema: { type: 'object' }, name: 'list_files' },+ { _meta: { ui: { visibility: ['app'] } }, inputSchema: { type: 'object' }, name: 'refresh' },+];++const makeClient = () => ({+ disconnect: vi.fn().mockResolvedValue(undefined),+ initialize: vi.fn().mockResolvedValue(undefined),+ listTools: vi.fn().mockResolvedValue(tools),+});++describe('McpCtr.listToolsForGateway', () => {+ let ctr: McpCtr;++ beforeEach(() => {+ vi.clearAllMocks();+ clientParams.length = 0;+ ctr = new McpCtr(mockApp);+ });++ it('lists an HTTP server on a one-off session with its credentials, returning every tool', async () => {+ const client = makeClient();+ mcpClientMocks.mockReturnValue(client);++ const result = await ctr.listToolsForGateway({+ mcpApps: true,+ params: {+ auth: { token: 'secret', type: 'bearer' },+ headers: { 'x-team': 'a' },+ name: 'nas',+ type: 'http',+ url: 'https://nas.tail1234.ts.net/mcp',+ },+ });++ // Raw, as listed: the server maps them into its manifest itself+ expect(result).toEqual(tools);+ expect(clientParams[0]).toMatchObject({+ auth: { token: 'secret', type: 'bearer' },+ headers: { 'x-team': 'a' },+ name: 'nas',+ type: 'http',+ url: 'https://nas.tail1234.ts.net/mcp',+ });+ expect(client.disconnect).toHaveBeenCalledOnce();+ });++ it('disconnects the HTTP session when listing fails', async () => {+ const client = makeClient();+ client.listTools.mockRejectedValue(new Error('unreachable'));+ mcpClientMocks.mockReturnValue(client);++ await expect(+ ctr.listToolsForGateway({+ params: { name: 'nas', type: 'http', url: 'https://nas.tail1234.ts.net/mcp' },+ }),+ ).rejects.toThrow('unreachable');+ expect(client.disconnect).toHaveBeenCalledOnce();+ });++ it('lists a stdio server on the pooled session its calls reuse', async () => {+ const client = makeClient();+ mcpClientMocks.mockReturnValue(client);+ const params = {+ args: ['mcp.js'],+ command: 'node',+ env: { TOKEN: 't' },+ name: 'files',+ type: 'stdio' as const,+ };++ await expect(ctr.listToolsForGateway({ params })).resolves.toEqual(tools);+ await expect(ctr.listToolsForGateway({ params })).resolves.toEqual(tools);++ // One process serves both listings, and stays up for the calls that follow+ expect(mcpClientMocks).toHaveBeenCalledOnce();+ expect(clientParams[0]).toMatchObject(params);+ expect(client.disconnect).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/controllers/gatewayDeviceControlDeps.ts b/apps/desktop/src/main/controllers/gatewayDeviceControlDeps.tsnew file mode 100644index 00000000000..38144f2e904--- /dev/null+++ b/apps/desktop/src/main/controllers/gatewayDeviceControlDeps.ts@@ -0,0 +1,62 @@+import type { DeviceControlDeps } from '@lobechat/device-control';+import { app as electronApp } from 'electron';++import type { App } from '@/core/App';+import { getRemoteTerminalDeps } from '@/modules/terminal/remote';+import { updaterConfig } from '@/modules/updater/configs';+import { createRemoteAppUpdateDeps } from '@/modules/updater/remoteUpdate';+import GatewayConnectionService from '@/services/gatewayConnectionSrv';+import { createLogger } from '@/utils/logger';++import HeterogeneousAgentCtr from './HeterogeneousAgentCtr';+import LocalFileCtr from './LocalFileCtr';+import McpCtr from './McpCtr';++const logger = createLogger('controllers:GatewayConnectionCtr');++/**+ * Desktop handlers for the shared `@lobechat/device-control` dispatcher, the+ * device RPCs a server sends this machine through the device gateway. Each+ * handler looks its controller up when it runs.+ */+export const createDesktopDeviceControlDeps = (app: App): DeviceControlDeps => {+ const localFileCtr = () => app.getController(LocalFileCtr);+ const service = () => app.getService(GatewayConnectionService);++ return {+ approveProjectRoot: async (root) => {+ try {+ await app.localFileProtocolManager.approveIndexedProjectRoot(root);+ } catch (error) {+ logger.error(`Failed to approve project preview root ${root}:`, error);+ }+ },+ // Workspace share (server-driven enroll/unenroll RPCs): the service owns+ // the gateway connections, so both handlers route straight to it.+ enrollWorkspace: (params) => service().enrollWorkspace(params),+ getLocalFilePreview: (params) => localFileCtr().getLocalFilePreview(params),+ readExternalAssetForPublish: (params) => localFileCtr().readExternalAssetForPublish(params),+ copyAssetForPublish: (params) => localFileCtr().copyAssetForPublish(params),+ getProjectFileIndex: (params) => localFileCtr().getProjectFileIndex(params),+ listHeterogeneousAgentModels: (params) =>+ app.getController(HeterogeneousAgentCtr).listModels(params),+ // A server that can't reach an MCP server itself lists its tools here+ listMcpTools: (params) => app.getController(McpCtr).listToolsForGateway(params),+ searchProjectFiles: (params) => localFileCtr().searchProjectFiles(params),+ // Remote "delete" goes to this machine's trash (`shell.trashItem`), same+ // as the local Files tree, so it stays recoverable.+ trashLocalFiles: (params) => localFileCtr().trashLocalFiles(params),+ unenrollWorkspace: (params) => service().unenrollWorkspace(params),+ // Skill-archive cache (`prepareSkillDirectory` RPC): reuse LocalFileCtr's+ // deps so gateway-prepared skills share one cache with the renderer-IPC path.+ ...localFileCtr().getSkillDirectoryDeps(),+ // Remote app update from the web device page, over the same updater the+ // local "Check for updates" menu drives.+ ...createRemoteAppUpdateDeps({+ currentVersion: electronApp.getVersion(),+ enabled: updaterConfig.enableAppUpdate,+ getUpdater: () => app.getUpdaterManager(),+ }),+ ...getRemoteTerminalDeps(),+ };+};diff --git a/apps/server/src/routers/lambda/agentEval/connectors.ts b/apps/server/src/routers/lambda/agentEval/connectors.tsindex 29dbf478194..167310962d0 100644--- a/apps/server/src/routers/lambda/agentEval/connectors.ts+++ b/apps/server/src/routers/lambda/agentEval/connectors.ts@@ -143,7 +143,12 @@ export const evalConnectorRouter = router({if (!(await models.connectorModel.findPublicById(input.id)))throw new TRPCError({ code: 'NOT_FOUND', message: 'Dataset connection not found' });try {- return await syncConnectorToolsById(input.id, models, { pruneMissingAutoTools: true });+ // Eval connections never tunnel to a user's device+ return await syncConnectorToolsById(+ input.id,+ { ...models, serverDB: undefined },+ { pruneMissingAutoTools: true },+ );} catch {// Upstream MCP errors may echo credentials, request headers or private addresses.throw new TRPCError({diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.tsindex defa55503f8..2a3e7a127bd 100644--- a/apps/server/src/routers/lambda/connector.ts+++ b/apps/server/src/routers/lambda/connector.ts@@ -1,6 +1,6 @@import { getComposioAppByIdentifier, hasCallableMcpEndpoint } from '@lobechat/const';import { isFullAccessApiKey } from '@lobechat/const/apiKeyScope';-import { upsertPluginMode } from '@lobechat/types';+import { GetStreamableMcpServerManifestInputSchema, upsertPluginMode } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -35,6 +35,7 @@ import {ConnectorToolCallError,readConnectorUiResourceById,} from '@/server/services/connector/exec';+import { getConnectorLocalCallToken } from '@/server/services/connector/localCallToken';import {buildAuthorizationUrl,discoverConnectorOAuth,@@ -51,6 +52,7 @@ import {pruneMissingAutoConnectorTools,syncConnectorToolsById,} from '@/server/services/connector/sync';+import { getDeviceMcpManifest } from '@/server/services/mcp/deviceManifest';import {resolveConnectorAuthorizerId,resolveUserDisplayMap,@@ -302,6 +304,23 @@ export const connectorRouter = router({return { ...rest, credentials: safeCredentials, oidcConfig: safeOidcConfig, tools };}),+ /** The OAuth access token a device-routed connector's local desktop call sends. */+ getLocalCallToken: connectorWriteProcedure+ .input(z.object({ id: z.string().uuid() }))+ .mutation(({ ctx, input }) => getConnectorLocalCallToken(ctx, input.id)),++ /**+ * Test an HTTP MCP server the user set to connect through their device: its+ * manifest, read on their own desktop app. A mutation so the credentials+ * travel in the body, not the URL.+ */+ getDeviceMcpManifest: wsCompatProcedure+ .use(serverDatabase)+ .input(GetStreamableMcpServerManifestInputSchema)+ .mutation(({ ctx, input }) =>+ getDeviceMcpManifest({ connection: input, serverDB: ctx.serverDB, userId: ctx.userId }),+ ),+/*** The exact redirect URI the server will send to the OAuth/DCR endpoints.* The Add modal must display THIS value (not a client-derived origin) so thediff --git a/apps/server/src/services/agentEvalConnector/index.ts b/apps/server/src/services/agentEvalConnector/index.tsindex 288220715a3..a2c8bcd1f6f 100644--- a/apps/server/src/services/agentEvalConnector/index.ts+++ b/apps/server/src/services/agentEvalConnector/index.ts@@ -410,10 +410,8 @@ export class AgentEvalConnectorService {throw unavailable();await syncConnectorToolsById(binding.connectorId,- {- connectorModel,- connectorToolModel: this.toolModel,- },+ // Eval connections never tunnel to a user's device+ { connectorModel, connectorToolModel: this.toolModel, serverDB: undefined },{ pruneMissingAutoTools: true },);// The canonical LobeBench adapter authenticates /sessions/* before lookup.diff --git a/apps/server/src/services/connector/exec.ts b/apps/server/src/services/connector/exec.tsindex d9d1f596029..e3c930e7e32 100644--- a/apps/server/src/services/connector/exec.ts+++ b/apps/server/src/services/connector/exec.ts@@ -1,7 +1,7 @@import { hasCallableMcpEndpoint, isMarketplaceInstallRunnable } from '@lobechat/const';import { getMcpServerFingerprint, isSyncedMcpToolVisibleTo } from '@lobechat/const/mcpApp';import { getDisabledPluginIds } from '@lobechat/types';-import { isLocalOrPrivateUrl } from '@lobechat/utils';+import { connectorMcpEndpoint, shouldConnectViaDevice } from '@lobechat/utils/mcpEndpoint';import type { AgentModel } from '@/database/models/agent';import type { DecryptedConnector } from '@/database/models/connector';@@ -226,6 +226,7 @@ export const callConnectorToolById = async (id: connector.id,mcpConnectionType: connector.mcpConnectionType,mcpServerUrl: connector.mcpServerUrl,+ metadata: connector.metadata,},],buildLastSyncedAtMap(tools),@@ -235,19 +236,19 @@ export const callConnectorToolById = async (// Background tool-list refresh is best-effort — never fail the tool call.}- // Stdio runs on the user's own device, never in the server process. Private HTTP- // endpoints also require a device when a gateway is configured; self-hosted- // servers without a gateway can still connect to their own LAN over HTTP.- const requiresDevice =- connector.mcpConnectionType === ConnectorMcpConnectionType.stdio ||- (deviceGateway.isConfigured &&- !!connector.mcpServerUrl &&- isLocalOrPrivateUrl(connector.mcpServerUrl));- if (requiresDevice) {+ // Stdio runs on the user's own device, never in the server process. HTTP set+ // to connect through the device, or a private one, also requires a device+ // when a gateway is configured; self-hosted servers without a gateway keep+ // connecting in-process. Same rule as agent runs (`ToolExecutionService`).+ if (+ shouldConnectViaDevice(connectorMcpEndpoint(connector), {+ deviceGatewayConfigured: deviceGateway.isConfigured,+ })+ ) {throw new ConnectorToolCallError('BAD_REQUEST',- `Connector '${connector.name}' points at an MCP endpoint that only your machine can reach (stdio or local network). ` +- 'It runs only on your own device — the desktop app or `lh connect` — through a configured device gateway.',+ `Connector '${connector.name}' connects through your own device (stdio, a local-network address, or set to "Connect via device"), so the server can't call it directly. ` ++ 'Run these tools from a chat, with the desktop app or `lh connect` running on a computer that can reach this MCP server.',);}@@ -378,12 +379,13 @@ export const readConnectorUiResourceById = async (`Interactive views are not supported for ${connector.mcpConnectionType} connectors yet`,);}- // A cloud server can't reach a localhost / LAN endpoint, and resource reads- // aren't tunneled to the device yet; the chat falls back to the plain result.+ // A cloud server can't reach a device-routed endpoint (localhost / LAN, or+ // set to connect through the device), and resource reads aren't tunneled to+ // the device yet; the chat falls back to the plain result.if (- deviceGateway.isConfigured &&- !!connector.mcpServerUrl &&- isLocalOrPrivateUrl(connector.mcpServerUrl)+ shouldConnectViaDevice(connectorMcpEndpoint(connector), {+ deviceGatewayConfigured: deviceGateway.isConfigured,+ })) {throw new ConnectorToolCallError('BAD_REQUEST',diff --git a/apps/server/src/services/connector/localCallToken.test.ts b/apps/server/src/services/connector/localCallToken.test.tsnew file mode 100644index 00000000000..4967246a17a--- /dev/null+++ b/apps/server/src/services/connector/localCallToken.test.ts@@ -0,0 +1,72 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { getConnectorLocalCallToken } from './localCallToken';+import { ensureFreshConnectorToken } from './tokens';++vi.mock('./tokens', () => ({ ensureFreshConnectorToken: vi.fn(async (connector) => connector) }));++const oauthConnector = {+ credentials: {+ accessToken: 'access',+ clientSecret: 'never-leaves',+ refreshToken: 'never-leaves',+ type: 'oauth2',+ },+ id: 'c1',+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://nas.tail1234.ts.net/mcp',+ metadata: { connectVia: 'device' },+ userId: 'u1',+};++const call = (connector: Record<string, unknown> | undefined, userId = 'u1') => {+ const connectorModel = { findById: vi.fn().mockResolvedValue(connector) };+ return getConnectorLocalCallToken({ connectorModel: connectorModel as never, userId }, 'c1');+};++describe('getConnectorLocalCallToken', () => {+ beforeEach(() => vi.clearAllMocks());++ it("returns only a device-routed connector's access token, refreshed first when due", async () => {+ vi.mocked(ensureFreshConnectorToken).mockResolvedValueOnce({+ ...oauthConnector,+ credentials: { ...oauthConnector.credentials, accessToken: 'refreshed' },+ } as never);++ await expect(call(oauthConnector)).resolves.toEqual({+ accessToken: 'refreshed',+ type: 'oauth2',+ });+ expect(ensureFreshConnectorToken).toHaveBeenCalledOnce();+ });++ it('returns the token for a localhost / LAN endpoint on automatic routing', async () => {+ await expect(+ call({ ...oauthConnector, mcpServerUrl: 'http://192.168.1.5/mcp', metadata: {} }),+ ).resolves.toEqual({ accessToken: 'access', type: 'oauth2' });+ });++ // The server calls it itself: the token never needs to leave it+ it('returns nothing for a connector the server reaches itself', async () => {+ await expect(call({ ...oauthConnector, metadata: {} })).resolves.toBeNull();+ expect(ensureFreshConnectorToken).not.toHaveBeenCalled();+ });++ it('returns nothing for a connector without an OAuth token', async () => {+ await expect(+ call({ ...oauthConnector, credentials: { token: 't', type: 'bearer' } }),+ ).resolves.toBeNull();+ });++ // A workspace owner may manage the row, but not take another member's token+ it('refuses anyone but the member who connected it', async () => {+ await expect(call(oauthConnector, 'workspace-owner')).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect(ensureFreshConnectorToken).not.toHaveBeenCalled();+ });++ it('fails when the connector is gone', async () => {+ await expect(call(undefined)).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });+});diff --git a/apps/server/src/services/connector/localCallToken.ts b/apps/server/src/services/connector/localCallToken.tsnew file mode 100644index 00000000000..fc1d946e318--- /dev/null+++ b/apps/server/src/services/connector/localCallToken.ts@@ -0,0 +1,43 @@+import { connectorMcpEndpoint, isDeviceOnlyMcpEndpoint } from '@lobechat/utils/mcpEndpoint';+import { TRPCError } from '@trpc/server';++import type { ConnectorModel } from '@/database/models/connector';++import { ensureFreshConnectorToken } from './tokens';++/**+ * The current OAuth access token of an HTTP connector the creator's desktop app+ * calls itself: one only their machine reaches (localhost / LAN, or set to+ * connect through the device). The edit read (`getForEdit`) never returns OAuth+ * tokens, so without this such a call would reach the server unauthenticated.+ *+ * Narrow on purpose: the creator only (a workspace owner can manage the row+ * but must not take a token another member authorized), the access token only+ * (never the refresh token or client secret), refreshed first when due. This+ * is what the device gateway already forwards to the user's device for the+ * same call. `null` when the connector has no OAuth token or runs elsewhere.+ */+export const getConnectorLocalCallToken = async (+ ctx: { connectorModel: ConnectorModel; userId: string },+ id: string,+): Promise<{ accessToken: string; type: 'oauth2' } | null> => {+ const connector = await ctx.connectorModel.findById(id);+ if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });+ if (connector.userId !== ctx.userId) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Only the member who connected this connector can run it from their device.',+ });+ }++ const endpoint = connectorMcpEndpoint(connector);+ if (endpoint.type === 'stdio' || !connector.mcpServerUrl || !isDeviceOnlyMcpEndpoint(endpoint))+ return null;+ if (connector.credentials?.type !== 'oauth2') return null;++ const fresh = await ensureFreshConnectorToken(connector, ctx.connectorModel);+ const credentials = fresh.credentials;+ return credentials?.type === 'oauth2' && credentials.accessToken+ ? { accessToken: credentials.accessToken, type: 'oauth2' }+ : null;+};diff --git a/apps/server/src/services/connector/refresh.ts b/apps/server/src/services/connector/refresh.tsindex ca1f285e291..5c300523943 100644--- a/apps/server/src/services/connector/refresh.ts+++ b/apps/server/src/services/connector/refresh.ts@@ -1,4 +1,4 @@-import { isLocalOrPrivateUrl } from '@lobechat/utils';+import { connectorMcpEndpoint, shouldConnectViaDevice } from '@lobechat/utils/mcpEndpoint';import debug from 'debug';import { ConnectorMcpConnectionType } from '@/database/schemas';@@ -46,6 +46,8 @@ export interface StaleRefreshConnector {id: string;mcpConnectionType: ConnectorMcpConnectionType | string | null;mcpServerUrl: string | null;+ /** Read for `connectVia`: a connector set to connect through the device is skipped. */+ metadata?: { connectVia?: unknown } | null;}/**@@ -105,12 +107,18 @@ export const scheduleStaleConnectorToolsRefresh = (// machine); skip anything without an HTTP endpoint.if (connector.mcpConnectionType === ConnectorMcpConnectionType.stdio) continue;if (!connector.mcpServerUrl) continue;- // Localhost / private-network endpoints are unreachable from the CLOUD- // server — their tool list is synced by the desktop client instead- // (`syncToolsFromClientById`). Gate on the device gateway being- // configured: a self-hosted server may share a LAN with the endpoint- // and can legitimately refresh it.- if (deviceGateway.isConfigured && isLocalOrPrivateUrl(connector.mcpServerUrl)) continue;+ // Device-routed endpoints (localhost / private network, or set to connect+ // through the device) are unreachable from the CLOUD server — their tool+ // list is synced on the device instead, when the user installs or+ // refreshes it. Gated on the device gateway being configured+ // (`shouldConnectViaDevice`): a self-hosted server may share a LAN with+ // the endpoint and can legitimately refresh it.+ if (+ shouldConnectViaDevice(connectorMcpEndpoint(connector), {+ deviceGatewayConfigured: deviceGateway.isConfigured,+ })+ )+ continue;const { id } = connector;// Throttle on whichever is more recent: the DB tool marker or the last@@ -124,7 +132,8 @@ export const scheduleStaleConnectorToolsRefresh = (try {after(async () => {try {- const { toolCount } = await syncConnectorToolsById(id, ctx);+ // Device-routed connectors were skipped above: none tunnels here+ const { toolCount } = await syncConnectorToolsById(id, { ...ctx, serverDB: undefined });log('auto-refreshed connector %s: %d tools', id, toolCount);} catch (err) {// Remote unreachable / auth failure / etc. — best-effort backgrounddiff --git a/apps/server/src/services/connector/sync.ts b/apps/server/src/services/connector/sync.tsindex 321760997da..aada7017dde 100644--- a/apps/server/src/services/connector/sync.ts+++ b/apps/server/src/services/connector/sync.ts@@ -3,6 +3,12 @@ import {getMcpAppEntrypoints,resolveMcpUiToolMeta,} from '@lobechat/const/mcpApp';+import { type LobeChatDatabase } from '@lobechat/database';+import {+ connectorConnectVia,+ connectorMcpEndpoint,+ shouldConnectViaDevice,+} from '@lobechat/utils/mcpEndpoint';import type { ConnectorModel, DecryptedConnector } from '@/database/models/connector';import type { ConnectorToolModel } from '@/database/models/connectorTool';@@ -12,9 +18,11 @@ import {ConnectorStatus,ConnectorToolPermission,} from '@/database/schemas';-import type { AuthConfig } from '@/libs/mcp';+import type { AuthConfig, McpTool } from '@/libs/mcp';import { inferCrudType } from '@/libs/mcp/utils';+import { deviceGateway } from '@/server/services/deviceGateway';import { mcpService } from '@/server/services/mcp';+import { listMcpToolsOnPersonalDevice } from '@/server/services/mcp/deviceTunnel';import { isMcpAppsEnabled } from '@/server/services/mcp/featureGate';import { ensureFreshConnectorToken } from './tokens';@@ -55,6 +63,8 @@ export const buildConnectorMcpParams = (const mergedHeaders = headers || customHeaders ? { ...headers, ...customHeaders } : undefined;return {auth,+ // Only set when chosen, as `buildConnectorManifests` does+ ...(connectorConnectVia(connector.metadata) === 'device' && { connectVia: 'device' as const }),headers: mergedHeaders,name: connector.identifier,type: 'http',@@ -121,6 +131,45 @@ export const pruneMissingAutoConnectorTools = async (await connectorToolModel.deleteToolsNotIn(connectorId, [...listedToolNames, ...tombstones]);};+/**+ * A connector this server must not connect to itself (stdio, local network, or+ * set to connect through the device) is listed on the user's desktop through+ * the device gateway; `undefined` for any other, which the server lists itself.+ * Without a gateway (self-hosted) every connector keeps the in-process listing,+ * as agent runs keep the in-process call.+ *+ * Only the caller's own connector is tunneled to the caller's device: a+ * workspace connector another member set up carries that member's credentials,+ * which must not reach a machine they never approved.+ */+const listOnDevice = async (+ connector: DecryptedConnector,+ mcpParams: ReturnType<typeof buildConnectorMcpParams>,+ ctx: { serverDB?: LobeChatDatabase; userId?: string | null },+ mcpApps: boolean,+): Promise<McpTool[] | undefined> => {+ if (!deviceGateway.isConfigured) return undefined;+ if (+ !shouldConnectViaDevice(connectorMcpEndpoint(connector), {+ deviceGatewayConfigured: true,+ })+ )+ return undefined;++ if (connector.userId !== ctx.userId) {+ throw new Error(+ `Connector '${connector.name}' connects through a device, and only the member who set it up can refresh its tools from their desktop app.`,+ );+ }++ return listMcpToolsOnPersonalDevice({+ mcpApps,+ params: mcpParams,+ serverDB: ctx.serverDB,+ userId: ctx.userId,+ });+};+/*** 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@@ -131,8 +180,16 @@ export const pruneMissingAutoConnectorTools = async (*/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 },+ /**+ * `userId` decides the `mcp_apps` flag: with it on, view-only tools are listed+ * too. `serverDB` finds the user's device for a connector the server can't+ * reach itself (`shouldConnectViaDevice`). Required, so each caller decides:+ * `undefined` fails such a sync instead of tunneling it to a device.+ */+ ctx: ConnectorToolSyncContext & {+ serverDB: LobeChatDatabase | undefined;+ userId?: string | null;+ },options: ConnectorToolSyncOptions = {},): Promise<{ toolCount: number }> => {let connector = await ctx.connectorModel.findById(connectorId);@@ -152,9 +209,11 @@ export const syncConnectorToolsById = async (try {// A server may list the tools only its views call just to a client// announcing MCP Apps; they are synced, and kept from the model, all the same- rawTools = await mcpService.listRawTools(mcpParams, {- mcpApps,- });+ rawTools =+ (await listOnDevice(connector, mcpParams, ctx, mcpApps)) ??+ (await mcpService.listRawTools(mcpParams, {+ mcpApps,+ }));} catch (err) {await ctx.connectorModel.updateStatus(connectorId, ConnectorStatus.error);throw err;diff --git a/apps/server/src/services/deviceGateway/agents.ts b/apps/server/src/services/deviceGateway/agents.tsindex b7ec2e4a0b2..aff6304247a 100644--- a/apps/server/src/services/deviceGateway/agents.ts+++ b/apps/server/src/services/deviceGateway/agents.ts@@ -25,6 +25,8 @@ import type {} from '@lobechat/types';import debug from 'debug';+import type { McpTool } from '@/libs/mcp/types';+import { invokeDeviceRead } from './deviceRead';import type { DeviceClientGetter } from './types';@@ -296,6 +298,71 @@ export async function executeMcpCall(}}+/**+ * List an MCP server's tools on a connected device, for servers only the device+ * can reach (stdio, its network, or set to connect through it): the cloud can't+ * connect to them to install or refresh the tool list. The tools come back as+ * the server's `tools/list` returned them.+ *+ * Throws with a reason the user can act on: no gateway, a client too old to+ * list MCP tools, or the device's own error.+ */+export async function listMcpTools(+ getClient: DeviceClientGetter,+ params: {+ /** Which of the device's clients lists them (see `resolveMcpClientKinds`). */+ clientKinds?: DeviceClient[];+ deviceId: string;+ mcpApps?: boolean;+ params: GatewayMcpParams;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<McpTool[]> {+ const {+ clientKinds,+ deviceId,+ mcpApps,+ params: connection,+ timeout = 30_000,+ userId,+ workspaceId,+ } = params;+ const client = getClient();+ if (!client) throw new Error('Device gateway is not configured');++ log('listMcpTools: userId=%s, deviceId=%s, mcp=%s', userId, deviceId, connection.name);++ let result: Awaited<ReturnType<typeof client.invokeRpc<McpTool[]>>>;+ try {+ result = await client.invokeRpc<McpTool[]>(+ { clientKinds, deviceId, timeout, userId, workspaceId },+ { method: 'listMcpTools', params: { mcpApps, params: connection } },+ );+ } catch (error) {+ log('listMcpTools: transport error for deviceId=%s — %O', deviceId, error);+ const reason = error instanceof Error ? error.message : String(error);+ throw new Error(+ `Couldn't reach your device to list this MCP server's tools (${reason}). Make sure the desktop app or \`lh connect\` is running and connected, then try again.`,+ { cause: error },+ );+ }++ if (!result.success || !Array.isArray(result.data)) {+ const message = result.error || 'The device did not return a tool list';+ log('listMcpTools: failed for deviceId=%s — %s', deviceId, message);+ if (message.includes('Unknown device RPC method')) {+ throw new Error(+ 'The app on this device is too old to list MCP tools. Update the desktop app or the `lh` CLI, then try again.',+ );+ }+ throw new Error(message);+ }++ return result.data;+}+export async function executeMessageApi(getClient: DeviceClientGetter,params: { deviceId: string; userId: string; workspaceId?: string },diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex 5621385fcd2..772db8165fa 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -467,6 +467,10 @@ export class DeviceGateway {return agents.executeMcpCall(this.clientGetter, ...args);}+ listMcpTools(...args: DeviceRpcArgs<typeof agents.listMcpTools>) {+ return agents.listMcpTools(this.clientGetter, ...args);+ }+executeMessageApi(...args: DeviceRpcArgs<typeof agents.executeMessageApi>) {return agents.executeMessageApi(this.clientGetter, ...args);}diff --git a/apps/server/src/services/mcp/deviceManifest.test.ts b/apps/server/src/services/mcp/deviceManifest.test.tsnew file mode 100644index 00000000000..16d83c6f3ef--- /dev/null+++ b/apps/server/src/services/mcp/deviceManifest.test.ts@@ -0,0 +1,108 @@+import { TRPCError } from '@trpc/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { getDeviceMcpManifest } from './deviceManifest';+import { listMcpToolsOnPersonalDevice, McpDeviceUnavailableError } from './deviceTunnel';++const gateway = vi.hoisted(() => ({ isConfigured: true }));++vi.mock('@/server/services/deviceGateway', () => ({ deviceGateway: gateway }));+vi.mock('@/server/services/mcp/featureGate', () => ({+ isMcpAppsEnabled: vi.fn().mockResolvedValue(true),+}));+vi.mock('@/server/services/mcp', () => ({+ mcpService: {+ buildStreamableMcpManifest: vi.fn((identifier: string, _p, tools: unknown[]) => ({+ api: tools,+ identifier,+ })),+ listRawTools: vi.fn(),+ },+}));+vi.mock('./deviceTunnel', async (importOriginal) => ({+ ...((await importOriginal()) as Record<string, unknown>),+ listMcpToolsOnPersonalDevice: vi.fn(),+}));++const serverDB = {} as never;+const connection = {+ auth: { token: 'secret', type: 'bearer' as const },+ identifier: 'nas',+ url: 'https://nas.tail1234.ts.net/mcp',+};+const tools = [{ inputSchema: { type: 'object' }, name: 'list_files' }];++describe('getDeviceMcpManifest', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ gateway.isConfigured = true;+ });++ it("lists the tools on the user's desktop app and maps them into a manifest", async () => {+ const { mcpService } = await import('@/server/services/mcp');+ vi.mocked(listMcpToolsOnPersonalDevice).mockResolvedValue(tools as never);++ await expect(getDeviceMcpManifest({ connection, serverDB, userId: 'u1' })).resolves.toEqual({+ api: tools,+ identifier: 'nas',+ });++ expect(listMcpToolsOnPersonalDevice).toHaveBeenCalledWith({+ mcpApps: true,+ params: {+ auth: connection.auth,+ connectVia: 'device',+ name: 'nas',+ type: 'http',+ url: connection.url,+ },+ serverDB,+ userId: 'u1',+ });+ // Never connected from the server+ expect(mcpService.listRawTools).not.toHaveBeenCalled();+ });++ it('connects from the server itself when it has no device gateway (self-hosted)', async () => {+ const { mcpService } = await import('@/server/services/mcp');+ gateway.isConfigured = false;+ vi.mocked(mcpService.listRawTools).mockResolvedValue(tools as never);++ await getDeviceMcpManifest({ connection, serverDB, userId: 'u1' });++ expect(mcpService.listRawTools).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'nas', url: connection.url }),+ { mcpApps: true },+ );+ expect(listMcpToolsOnPersonalDevice).not.toHaveBeenCalled();+ });++ it('fails as a precondition, with what to do, when no desktop app is online', async () => {+ vi.mocked(listMcpToolsOnPersonalDevice).mockRejectedValue(new McpDeviceUnavailableError('nas'));++ const error = await getDeviceMcpManifest({ connection, serverDB, userId: 'u1' }).catch(+ (e) => e,+ );++ expect(error).toBeInstanceOf(TRPCError);+ expect(error.code).toBe('PRECONDITION_FAILED');+ expect(error.message).toContain('desktop app');+ });++ it("passes a connection's own TRPC error through with its data", async () => {+ const authError = new TRPCError({ code: 'UNAUTHORIZED', message: 'Reconnect this MCP' });+ vi.mocked(listMcpToolsOnPersonalDevice).mockRejectedValue(authError);++ await expect(getDeviceMcpManifest({ connection, serverDB, userId: 'u1' })).rejects.toBe(+ authError,+ );+ });++ it('reports a failed listing on the device as a bad request', async () => {+ vi.mocked(listMcpToolsOnPersonalDevice).mockRejectedValue(new Error('ECONNREFUSED'));++ await expect(+ getDeviceMcpManifest({ connection, serverDB, userId: 'u1' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST', message: 'ECONNREFUSED' });+ });+});diff --git a/apps/server/src/services/mcp/deviceManifest.ts b/apps/server/src/services/mcp/deviceManifest.tsnew file mode 100644index 00000000000..5c0401e1bf4--- /dev/null+++ b/apps/server/src/services/mcp/deviceManifest.ts@@ -0,0 +1,63 @@+import { type LobeChatDatabase } from '@lobechat/database';+import { type GetStreamableMcpServerManifestInputSchema } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import type { z } from 'zod';++import { deviceGateway } from '@/server/services/deviceGateway';+import { mcpService } from '@/server/services/mcp';+import {+ listMcpToolsOnPersonalDevice,+ McpDeviceUnavailableError,+} from '@/server/services/mcp/deviceTunnel';+import { isMcpAppsEnabled } from '@/server/services/mcp/featureGate';++/**+ * The manifest of an HTTP MCP server the user set to connect through their+ * device: its tools are listed on the user's own desktop app, then mapped the+ * way the server relay's `getStreamableMcpServerManifest` maps a listing it ran+ * itself. Without a device gateway (self-hosted) the server connects itself.+ *+ * Fails with `PRECONDITION_FAILED` when no desktop app of the user's is online,+ * and with the connection's own error when the listing fails.+ */+export const getDeviceMcpManifest = async ({+ connection,+ serverDB,+ userId,+}: {+ connection: z.infer<typeof GetStreamableMcpServerManifestInputSchema>;+ serverDB: LobeChatDatabase;+ userId: string;+}) => {+ const mcpApps = await isMcpAppsEnabled(userId);+ const params = {+ ...(connection.auth && { auth: connection.auth }),+ connectVia: 'device' as const,+ ...(connection.headers && { headers: connection.headers }),+ name: connection.identifier,+ type: 'http' as const,+ url: connection.url,+ };++ try {+ const rawTools = deviceGateway.isConfigured+ ? await listMcpToolsOnPersonalDevice({ mcpApps, params, serverDB, userId })+ : await mcpService.listRawTools(params, { mcpApps });++ return mcpService.buildStreamableMcpManifest(+ connection.identifier,+ params,+ rawTools,+ connection.metadata,+ { mcpApps },+ );+ } catch (error) {+ // The connection's own TRPC errors (authorization, ...) keep their data+ if (error instanceof TRPCError) throw error;+ throw new TRPCError({+ cause: error,+ code: error instanceof McpDeviceUnavailableError ? 'PRECONDITION_FAILED' : 'BAD_REQUEST',+ message: error instanceof Error ? error.message : String(error),+ });+ }+};diff --git a/apps/server/src/services/mcp/deviceTunnel.test.ts b/apps/server/src/services/mcp/deviceTunnel.test.tsnew file mode 100644index 00000000000..c8a6797fbca--- /dev/null+++ b/apps/server/src/services/mcp/deviceTunnel.test.ts@@ -0,0 +1,100 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { deviceGateway } from '@/server/services/deviceGateway';+import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';++import { listMcpToolsOnPersonalDevice, McpDeviceUnavailableError } from './deviceTunnel';++vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: {+ isConfigured: true,+ listMcpTools: vi.fn(),+ queryDeviceList: vi.fn().mockResolvedValue([]),+ readDeviceSystemInfo: vi.fn(),+ },+}));+vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({+ getScopedOnlineDevices: vi.fn(),+}));++const serverDB = {} as never;+const params = {+ auth: { refreshToken: 'never-leaves', token: 'secret', type: 'bearer' as const },+ name: 'nas',+ type: 'http' as const,+ url: 'https://nas.tail1234.ts.net/mcp',+};+const tools = [{ inputSchema: { type: 'object' }, name: 'list_files' }];+const device = (deviceId: string, channels: string[], online = true) =>+ ({ channels: channels.map((channel) => ({ channel })), deviceId, online }) as never;++describe('listMcpToolsOnPersonalDevice', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(deviceGateway.listMcpTools).mockResolvedValue(tools as never);+ });++ it("lists on the newest online desktop app, pinned to it, with only the auth's token fields", async () => {+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([+ device('offline', ['desktop'], false),+ device('laptop', ['desktop', 'cli']),+ ]);++ await expect(+ listMcpToolsOnPersonalDevice({ mcpApps: true, params, serverDB, userId: 'u1' }),+ ).resolves.toEqual(tools);++ expect(deviceGateway.listMcpTools).toHaveBeenCalledWith({+ clientKinds: ['desktop'],+ deviceId: 'laptop',+ mcpApps: true,+ params: {+ auth: { accessToken: undefined, token: 'secret', type: 'bearer' },+ headers: undefined,+ name: 'nas',+ type: 'http',+ url: params.url,+ },+ userId: 'u1',+ });+ });++ // The same device and client a tunneled call of this server runs on+ it('lists on a device with only an MCP-capable `lh connect`', async () => {+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([device('devbox', ['cli'])]);+ vi.mocked(deviceGateway.readDeviceSystemInfo).mockResolvedValue({+ ok: true,+ systemInfo: { supportedToolCallTypes: ['mcp'] },+ } as never);++ await listMcpToolsOnPersonalDevice({ params, serverDB, userId: 'u1' });++ expect(deviceGateway.listMcpTools).toHaveBeenCalledWith(+ expect.objectContaining({ clientKinds: ['cli'], deviceId: 'devbox' }),+ );+ });++ it('skips an older CLI and a device whose clients are unlabelled', async () => {+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([+ device('old-cli', ['cli']),+ device('unlabelled', []),+ ]);+ vi.mocked(deviceGateway.readDeviceSystemInfo).mockResolvedValue({+ ok: true,+ systemInfo: {},+ } as never);++ await expect(+ listMcpToolsOnPersonalDevice({ params, serverDB, userId: 'u1' }),+ ).rejects.toBeInstanceOf(McpDeviceUnavailableError);+ expect(deviceGateway.listMcpTools).not.toHaveBeenCalled();+ });++ it('tells the user to open the desktop app or run `lh connect` when no device can list it', async () => {+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([]);++ await expect(listMcpToolsOnPersonalDevice({ params, serverDB, userId: 'u1' })).rejects.toThrow(+ /desktop app or run `lh connect`/,+ );+ });+});diff --git a/apps/server/src/services/mcp/deviceTunnel.ts b/apps/server/src/services/mcp/deviceTunnel.tsnew file mode 100644index 00000000000..d68b8cbae73--- /dev/null+++ b/apps/server/src/services/mcp/deviceTunnel.ts@@ -0,0 +1,145 @@+import { BRANDING_NAME } from '@lobechat/business-const';+import { type LobeChatDatabase } from '@lobechat/database';+import type { GatewayMcpParams } from '@lobechat/device-gateway-client';+import type { DeviceClient } from '@lobechat/types';+import debug from 'debug';++import type { HttpMCPClientParams, McpTool, StdioMCPParams } from '@/libs/mcp/types';+import { deviceGateway } from '@/server/services/deviceGateway';+import {+ clientKindFromChannels,+ resolveMcpClientKinds,+} from '@/server/services/deviceGateway/deviceChannels';+import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';++const log = debug('lobe-server:mcp:device-tunnel');++/** Code of the error a device-routed MCP fails with when no device can run it. */+export const MCP_DEVICE_UNAVAILABLE = 'MCP_DEVICE_UNAVAILABLE';++/**+ * What a user reads when an MCP server that must run on their device finds no+ * device to run it: why it needs one, and what to do.+ */+export const mcpDeviceUnavailableMessage = (identifier: string) =>+ `MCP server '${identifier}' connects through your own device (it uses stdio, a local-network address, or is set to "Connect via device"), and no online device can run it. Open the ${BRANDING_NAME} desktop app or run \`lh connect\` (update the CLI if it is older) on a computer that can reach this MCP server, then try again.`;++export class McpDeviceUnavailableError extends Error {+ readonly code = MCP_DEVICE_UNAVAILABLE;++ constructor(identifier: string) {+ super(mcpDeviceUnavailableMessage(identifier));+ this.name = 'McpDeviceUnavailableError';+ }+}++/**+ * The connection params a device needs to reach an MCP server. Credentials for+ * HTTP are narrowed to the token fields: the full `AuthConfig` also carries+ * OAuth client secrets and refresh tokens, which never leave the server.+ */+export const toGatewayMcpParams = (+ params: StdioMCPParams | HttpMCPClientParams,+): GatewayMcpParams =>+ params.type === 'stdio'+ ? {+ args: params.args ?? [],+ command: params.command,+ env: params.env,+ name: params.name,+ type: 'stdio',+ }+ : {+ auth: params.auth+ ? {+ accessToken: params.auth.accessToken,+ token: params.auth.token,+ type: params.auth.type,+ }+ : undefined,+ headers: params.headers,+ name: params.name,+ type: 'http',+ url: params.url,+ };++/** A device an MCP connection is tunneled to, and which of its clients runs it. */+export interface McpDeviceTarget {+ clientKinds: DeviceClient[];+ deviceId: string;+}++/**+ * The user's most recently active online PERSONAL device that can run an MCP+ * connection: the one a call, a tool listing or a connection test is tunneled+ * to when nothing routed it to a device.+ *+ * Its client is the one `resolveMcpClientKinds` picks: the desktop app, or an+ * `lh connect` that reports MCP support. A device whose clients are unlabelled+ * is skipped: it could be an older CLI that would mis-dispatch the call.+ * Personal scope only: a workspace device may belong to another member, and+ * the connection carries this user's credentials. The scoped helper (not the+ * raw gateway pool) applies device visibility and merges DB state.+ */+export const findPersonalMcpDevice = async (+ serverDB: LobeChatDatabase,+ userId: string,+): Promise<McpDeviceTarget | undefined> => {+ try {+ const devices = await getScopedOnlineDevices(serverDB, userId, undefined);+ // Already sorted online-first / most-recently-active: the newest online+ // device that can run the call wins.+ for (const device of devices) {+ if (!device.online) continue;+ const clientKind = clientKindFromChannels(device.channels);+ if (clientKind === 'unknown') continue;+ const clientKinds = await resolveMcpClientKinds(+ userId,+ device.deviceId,+ undefined,+ clientKind,+ );+ if (clientKinds) return { clientKinds, deviceId: device.deviceId };+ }+ return undefined;+ } catch (error) {+ log('findPersonalMcpDevice: lookup failed for user %s — %O', userId, error);+ return undefined;+ }+};++/**+ * List an MCP server's tools on the user's own device, for a server this+ * deployment must not connect to itself (`shouldConnectViaDevice`): an+ * install, a tool refresh or a connection test the user started. It runs on+ * the device and client a tool call would, so both reach the server alike.+ *+ * Throws {@link McpDeviceUnavailableError} when no device of theirs can run+ * it, and the device's own reason when the listing fails there.+ */+export const listMcpToolsOnPersonalDevice = async ({+ mcpApps,+ params,+ serverDB,+ userId,+}: {+ mcpApps?: boolean;+ params: StdioMCPParams | HttpMCPClientParams;+ serverDB?: LobeChatDatabase;+ userId?: string | null;+}): Promise<McpTool[]> => {+ if (!serverDB || !userId) throw new McpDeviceUnavailableError(params.name);++ const device = await findPersonalMcpDevice(serverDB, userId);+ if (!device) throw new McpDeviceUnavailableError(params.name);++ log('listing tools of %s (%s) on device %s', params.name, params.type, device.deviceId);++ return deviceGateway.listMcpTools({+ clientKinds: device.clientKinds,+ deviceId: device.deviceId,+ mcpApps,+ params: toGatewayMcpParams(params),+ userId,+ });+};diff --git a/apps/server/src/services/mcp/index.ts b/apps/server/src/services/mcp/index.tsindex 88eeb28e8ae..afad212f0f7 100644--- a/apps/server/src/services/mcp/index.ts+++ b/apps/server/src/services/mcp/index.ts@@ -24,6 +24,7 @@ import retry from 'async-retry';import debug from 'debug';import {+ type HttpMCPClientParams,type McpAppToolState,type MCPClientParams,type McpPrompt,@@ -523,6 +524,22 @@ export class MCPService {}const rawTools = await this.listRawTools(mcpParams, { mcpApps });++ return this.buildStreamableMcpManifest(identifier, mcpParams, rawTools, metadata, { mcpApps });+ }++ /**+ * An HTTP MCP server's manifest from a tool list read elsewhere: on the+ * user's device, for a server this deployment can't reach itself. Built the+ * way {@link getStreamableMcpServerManifest} builds the listing it ran.+ */+ buildStreamableMcpManifest(+ identifier: string,+ mcpParams: HttpMCPClientParams,+ rawTools: McpTool[],+ metadata?: CustomPluginMetadata,+ { mcpApps = false }: { mcpApps?: boolean } = {},+ ): ToolManifest {const tools = this.transformMCPToolToLobeAPI(rawTools, mcpApps);return {diff --git a/apps/server/src/services/toolExecution/__tests__/index.test.ts b/apps/server/src/services/toolExecution/__tests__/index.test.tsindex 80bca7617e7..8fb256620d4 100644--- a/apps/server/src/services/toolExecution/__tests__/index.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/index.test.ts@@ -819,6 +819,79 @@ describe('ToolExecutionService', () => {expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();});+ it.each([+ 'https://mcp.example.com/mcp',+ 'http://nas.tail1234.ts.net:8080/mcp',+ 'http://printer.local/mcp',+ ])('tunnels an HTTP MCP set to connect via device to the device (URL: %s)', async (url) => {+ const callTool = vi.fn();+ const service = makeService({ callTool });++ const result = await service.executeTool(+ mcpPayload,+ contextWith(+ { connectVia: 'device', headers: { 'X-Team': 'a' }, name: 'my-mcp', type: 'http', url },+ { activeDeviceId: 'device-1' },+ ),+ );++ expect(result.success).toBe(true);+ expect(callTool).not.toHaveBeenCalled();+ expect(deviceGateway.executeMcpCall).toHaveBeenCalledWith(+ expect.objectContaining({+ deviceId: 'device-1',+ // The routing choice stays on the server: the device just connects+ params: {+ auth: undefined,+ headers: { 'X-Team': 'a' },+ name: 'my-mcp',+ type: 'http',+ url,+ },+ }),+ undefined,+ );+ });++ it('fails a connect-via-device HTTP MCP with an actionable error when no desktop is online', async () => {+ const callTool = vi.fn();+ const service = makeService({ callTool });++ const result = await service.executeTool(+ mcpPayload,+ contextWith({+ connectVia: 'device',+ name: 'my-mcp',+ type: 'http',+ url: 'https://nas.tail1234.ts.net/mcp',+ }),+ );++ expect(callTool).not.toHaveBeenCalled();+ expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();+ expect(result.success).toBe(false);+ expect((result.error as any)?.code).toBe('MCP_DEVICE_UNAVAILABLE');+ expect(result.content).toContain('Connect via device');+ expect(result.content).toContain('desktop app');+ });++ it('keeps a connect-via-device HTTP MCP in-process without a gateway (self-hosted)', async () => {+ (deviceGateway as any).isConfigured = false;+ const callTool = vi.fn().mockResolvedValue({ ok: true });+ const service = makeService({ callTool });++ await service.executeTool(+ mcpPayload,+ contextWith(+ { connectVia: 'device', name: 'my-mcp', type: 'http', url: 'https://nas.internal/mcp' },+ { activeDeviceId: 'device-1' },+ ),+ );++ expect(callTool).toHaveBeenCalledTimes(1);+ expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();+ });+it.each([true, false])("passes the run owner's mcp_apps flag (%s) to the server MCP call",async (enabled) => {@@ -940,6 +1013,10 @@ describe('ToolExecutionService', () => {it.each([['stdio', { args: [], command: 'npx', name: 'my-mcp', type: 'stdio' }],['local-network HTTP', { name: 'my-mcp', type: 'http', url: 'http://10.0.0.5:8000/mcp' }],+ [+ 'connect-via-device HTTP',+ { connectVia: 'device', name: 'my-mcp', type: 'http', url: 'https://mcp.example.com' },+ ],])('refuses a %s MCP call instead of tunneling to the creator device',async (_, mcpParams) => {diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.tsindex 693f6a18e6b..e2cd874419c 100644--- a/apps/server/src/services/toolExecution/index.ts+++ b/apps/server/src/services/toolExecution/index.ts@@ -1,7 +1,7 @@import { BRANDING_NAME } from '@lobechat/business-const';import { DEFAULT_TOOL_RESULT_MAX_LENGTH, truncateToolResult } from '@lobechat/prompts/toolResult';import { type ChatToolPayload, type DeviceClient } from '@lobechat/types';-import { isDeviceOnlyMcpEndpoint } from '@lobechat/utils/mcpEndpoint';+import { isDeviceOnlyMcpEndpoint, shouldConnectViaDevice } from '@lobechat/utils/mcpEndpoint';import debug from 'debug';import { ConnectorToolPermission } from '@/database/schemas';@@ -12,16 +12,18 @@ import {} from '@/libs/mcp/connectorPermissionCheck';import { isMCPSSRFBlockedError } from '@/libs/mcp/ssrf';import { deviceGateway } from '@/server/services/deviceGateway';-import {- clientKindFromChannels,- resolveMcpClientKinds,-} from '@/server/services/deviceGateway/deviceChannels';+import { resolveMcpClientKinds } from '@/server/services/deviceGateway/deviceChannels';import { resolveDeviceDispatchAuthorizationFailure } from '@/server/services/deviceGateway/dispatchAuthorization';-import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';import { isMcpAppsEnabled } from '@/server/services/mcp/featureGate';import { type MCPService } from '../mcp';import { callCloudMcpTool, runtimeCloudMcpCaller } from '../mcp/cloudTool';+import {+ findPersonalMcpDevice,+ MCP_DEVICE_UNAVAILABLE,+ mcpDeviceUnavailableMessage,+ toGatewayMcpParams,+} from '../mcp/deviceTunnel';import { type BuiltinToolsExecutor } from './builtin';import { classifyToolError, getToolAccessDeniedError } from './errorClassification';import { buildMcpAuthorizationErrorContent, isMcpAuthorizationError } from './mcpAuthError';@@ -332,9 +334,12 @@ export class ToolExecutionService {// Stdio must run on the user's own device. Without a configured gateway or a// reachable device, fail instead of executing the command on the server.- // Private HTTP also uses the device when a gateway is configured, while- // self-hosted servers without one can still access their LAN over HTTP.- if (mcpParams.type === 'stdio' || (isDeviceOnlyMcp && deviceGateway.isConfigured)) {+ // HTTP the user set to connect through their device, or a private one,+ // also uses the device when a gateway is configured, while self-hosted+ // servers without one keep connecting in-process.+ if (+ shouldConnectViaDevice(mcpParams, { deviceGatewayConfigured: deviceGateway.isConfigured })+ ) {if (!deviceGateway.isConfigured) {const message = `MCP server '${identifier}' uses stdio and must run on your own device, not in the cloud, but this server's device gateway is not configured. Configure a device gateway on the server, then open the ${BRANDING_NAME} desktop app or run \`lh connect\` on the machine that hosts this MCP server, and retry.`;return {@@ -349,10 +354,10 @@ export class ToolExecutionService {: undefined;if (!tunnelTarget) {log('Device-only MCP %s:%s has no reachable device — failing fast', identifier, apiName);- const message = `MCP server '${identifier}' only your own machine can reach (stdio or local network), and no online device can run it. Open the ${BRANDING_NAME} desktop app or run \`lh connect\` (update the CLI if it is older) on the machine that hosts this MCP server, then retry.`;+ const message = mcpDeviceUnavailableMessage(identifier);return {content: message,- error: { code: 'MCP_DEVICE_UNAVAILABLE', message },+ error: { code: MCP_DEVICE_UNAVAILABLE, message },success: false,};}@@ -454,32 +459,14 @@ export class ToolExecutionService {// no plan-routed device and no connector→device ownership tie, fail closed// (caller surfaces MCP_DEVICE_UNAVAILABLE).if (workspaceId) return undefined;- // The scoped helper (not the raw gateway pool) is mandatory here: it+ // The scoped device lookup (not the raw gateway pool) is mandatory here: it// applies device visibility and merges DB state. No serverDB → can't// apply visibility → fail closed.if (!context.userId || !context.serverDB) return undefined;- try {- const devices = await getScopedOnlineDevices(context.serverDB, context.userId, undefined);- // Already sorted online-first / most-recently-active: the newest online- // device that can run the call wins.- for (const device of devices) {- if (!device.online) continue;- // A device whose clients are unlabelled is not picked implicitly: it- // could be an older CLI that would mis-dispatch the call.- const clientKind = clientKindFromChannels(device.channels);- if (clientKind === 'unknown') continue;- const clientKinds = await resolveMcpClientKinds(- context.userId,- device.deviceId,- undefined,- clientKind,- );- if (clientKinds) return { clientKinds, deviceId: device.deviceId, workspaceId: undefined };- }- return undefined;- } catch {- return undefined;- }+ const device = await findPersonalMcpDevice(context.serverDB, context.userId);+ return device+ ? { clientKinds: device.clientKinds, deviceId: device.deviceId, workspaceId: undefined }+ : undefined;}/**@@ -530,30 +517,8 @@ export class ToolExecutionService {arguments: args,deviceId: target.deviceId,identifier,- params:- mcpParams.type === 'stdio'- ? {- args: mcpParams.args ?? [],- command: mcpParams.command,- env: mcpParams.env,- name: mcpParams.name,- type: 'stdio',- }- : {- // AuthConfig also carries OAuth client secrets / refresh tokens —- // forward only what the device's MCP client needs to authenticate.- auth: mcpParams.auth- ? {- accessToken: mcpParams.auth.accessToken,- token: mcpParams.auth.token,- type: mcpParams.auth.type,- }- : undefined,- headers: mcpParams.headers,- name: mcpParams.name,- type: 'http',- url: mcpParams.url,- },+ // Only the token fields of the auth travel to the device+ params: toGatewayMcpParams(mcpParams),// Pin the client resolved for this device, so the call never lands on// one of its clients that cannot run it.clientKinds: target.clientKinds,diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex 1e97ca54017..3def57cac06 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -771,6 +771,11 @@"dev.mcp.command.label": "Command","dev.mcp.command.placeholder": "e.g. npx / uv / docker","dev.mcp.command.required": "Enter command",+ "dev.mcp.connectVia.auto": "Auto",+ "dev.mcp.connectVia.autoDesc": "Decided by the address: localhost and LAN IPs connect from your device, every other address connects from the server.",+ "dev.mcp.connectVia.device": "Connect via device",+ "dev.mcp.connectVia.deviceDesc": "Connects from your own device. Use it for addresses only your computer can reach, such as intranet, Tailscale, or LAN hostnames. Keep the LobeHub desktop app open and online on a computer that can reach this server.",+ "dev.mcp.connectVia.label": "Connection","dev.mcp.desc.desc": "Add Skill description","dev.mcp.desc.label": "Description","dev.mcp.desc.placeholder": "Usage instructions and scenarios",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex 04652fd3917..7cccc870a2b 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -771,6 +771,11 @@"dev.mcp.command.label": "命令","dev.mcp.command.placeholder": "例如:npx / uv / docker 等","dev.mcp.command.required": "请输入启动命令",+ "dev.mcp.connectVia.auto": "自动",+ "dev.mcp.connectVia.autoDesc": "按地址自动判断:localhost 和局域网 IP 在你的设备上连接,其他地址由服务端直接连接。",+ "dev.mcp.connectVia.device": "通过设备连接",+ "dev.mcp.connectVia.deviceDesc": "在你的设备上连接,适合内网、Tailscale、局域网域名等只有你的电脑能访问的地址。需要在能访问该服务器的电脑上打开 LobeHub 桌面端并保持在线。",+ "dev.mcp.connectVia.label": "连接方式","dev.mcp.desc.desc": "添加技能的描述说明","dev.mcp.desc.label": "技能描述","dev.mcp.desc.placeholder": "补充该技能的使用说明和场景等信息",diff --git a/packages/database/src/schemas/connector.ts b/packages/database/src/schemas/connector.tsindex 78157c3a418..eac0d1fb798 100644--- a/packages/database/src/schemas/connector.ts+++ b/packages/database/src/schemas/connector.ts@@ -143,6 +143,13 @@ export interface ConnectorMetadata {[key: string]: unknown;avatar?: string;composio?: ComposioConnectorMetadata;+ /**+ * HTTP only: `device` reaches the MCP server from the user's device through+ * the device gateway, whatever its address looks like (Tailscale MagicDNS,+ * `.local`, intranet DNS). Absent means `auto`: decided by the address+ * (`shouldConnectViaDevice` in `@lobechat/utils/mcpEndpoint`).+ */+ connectVia?: 'device';customHeaders?: Record<string, string>;description?: string;/**diff --git a/packages/device-control/src/__tests__/dispatch.test.ts b/packages/device-control/src/__tests__/dispatch.test.tsindex 6675e545d40..593644dd3f8 100644--- a/packages/device-control/src/__tests__/dispatch.test.ts+++ b/packages/device-control/src/__tests__/dispatch.test.ts@@ -21,6 +21,7 @@ import {DEVICE_RPC_METHODS,deviceRpcClients,executeDeviceRpc,+ MCP_UNSUPPORTED_MESSAGE,TERMINAL_UNSUPPORTED_MESSAGE,TRASH_UNSUPPORTED_MESSAGE,} from '../dispatch';@@ -307,6 +308,34 @@ describe('executeDeviceRpc', () => {).rejects.toThrow('does not support heterogeneous agent model discovery');});+ it('routes MCP tool listing to the host MCP client', async () => {+ const deps = makeDeps();+ const tools = [{ inputSchema: { type: 'object' }, name: 'search' }];+ deps.listMcpTools = vi.fn(async () => tools);+ const params = {+ mcpApps: true,+ params: {+ headers: { 'X-Team': 'a' },+ name: 'nas',+ type: 'http' as const,+ url: 'https://nas.tail1234.ts.net/mcp',+ },+ };++ await expect(executeDeviceRpc('listMcpTools', params, deps)).resolves.toEqual(tools);+ expect(deps.listMcpTools).toHaveBeenCalledWith(params);+ });++ it('rejects MCP tool listing on a client that runs no MCP servers', async () => {+ await expect(+ executeDeviceRpc(+ 'listMcpTools',+ { params: { name: 'x', type: 'http', url: 'http://x' } },+ makeDeps(),+ ),+ ).rejects.toThrow(MCP_UNSUPPORTED_MESSAGE);+ });+it('delegates project file and preview methods to injected deps', async () => {const deps = makeDeps();await executeDeviceRpc('getProjectFileIndex', { scope: root }, deps);@@ -754,6 +783,11 @@ describe('deviceRpcClients', () => {expect(deviceRpcClients(method)).toEqual(['cli']);});+ // Both clients run MCP servers; the server pins the one it picked per device+ it('leaves MCP tool listing to the client the server pins', () => {+ expect(deviceRpcClients('listMcpTools')).toBeUndefined();+ });+it('lets any client serve the other methods', () => {const shared = DEVICE_RPC_METHODS.filter((method) => !desktopOnly.includes(method) && !cliOnly.includes(method),diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.tsindex 9298a40e3ca..bd94542d8c4 100644--- a/packages/device-control/src/dispatch.ts+++ b/packages/device-control/src/dispatch.ts@@ -59,6 +59,7 @@ import type {InitWorkspaceParams,ListClaudeCodeMemoryParams,ListHeterogeneousAgentModelsParams,+ ListMcpToolsParams,ListProjectSkillsParams,LocalFilePreviewUrlParams,PrepareSkillDirectoryParams,@@ -85,6 +86,7 @@ export const DEVICE_RPC_METHODS = ['unenrollWorkspace','initWorkspace','listHeterogeneousAgentModels',+ 'listMcpTools','getAntigravityQuota','getClaudeCodeQuota','getCodexQuota',@@ -155,6 +157,9 @@ export const APP_UPDATE_UNSUPPORTED_MESSAGE = 'This device client does not suppoexport const CLI_UPDATE_UNSUPPORTED_MESSAGE ='This device client does not support remote CLI updates';+/** Why a client that runs no MCP servers rejects `listMcpTools`. */+export const MCP_UNSUPPORTED_MESSAGE = 'This device client does not support MCP servers';+/** Why a client without a recoverable trash (the CLI daemon) rejects `trashLocalFiles`. */export const TRASH_UNSUPPORTED_MESSAGE = 'This device does not support moving files to the trash';@@ -230,6 +235,11 @@ export const executeDeviceRpc = async (return deps.listHeterogeneousAgentModels(params as ListHeterogeneousAgentModelsParams);}+ case 'listMcpTools': {+ if (!deps.listMcpTools) throw new Error(MCP_UNSUPPORTED_MESSAGE);+ return deps.listMcpTools(params as ListMcpToolsParams);+ }+case 'getClaudeCodeQuota': {return getClaudeCodeQuota(params as GetClaudeCodeQuotaParams);}diff --git a/packages/device-control/src/rpcClients.ts b/packages/device-control/src/rpcClients.tsindex 7248339503e..b76d2b34aad 100644--- a/packages/device-control/src/rpcClients.ts+++ b/packages/device-control/src/rpcClients.ts@@ -11,6 +11,9 @@ import type { DeviceRpcMethod } from './dispatch';* RPC methods only the desktop app implements: the CLI daemon passes no* handler for them (no recoverable trash, no self-update), so a call that lands* on `lh connect` is rejected.+ *+ * `listMcpTools` is not listed: both clients run MCP servers, and the server+ * passes the client `resolveMcpClientKinds` picked for the device.*/const DESKTOP_ONLY_RPC_METHODS: ReadonlySet<string> = new Set<DeviceRpcMethod>(['trashLocalFiles',diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.tsindex ccd5955a829..c220a8c26b9 100644--- a/packages/device-control/src/types.ts+++ b/packages/device-control/src/types.ts@@ -399,6 +399,13 @@ export interface DeviceControlDeps extends SkillDirectoryDeps, WorkspaceScanDepslistHeterogeneousAgentModels?: (params: ListHeterogeneousAgentModelsParams,) => Promise<HeterogeneousAgentModelCatalog>;+ /**+ * List the tools of an MCP server only this machine reaches (stdio, or an+ * HTTP endpoint on its network), for a server that must not connect to it+ * itself. Optional: a client that runs no MCP servers omits it, and the+ * dispatcher fails the RPC with {@link MCP_UNSUPPORTED_MESSAGE}.+ */+ listMcpTools?: (params: ListMcpToolsParams) => Promise<ListedMcpServerTool[]>;/** Read raw bytes after the user explicitly approved an external publish closure. */readExternalAssetForPublish?: (params: ExternalAssetForPublishParams,@@ -430,6 +437,44 @@ export interface DeviceControlDeps extends SkillDirectoryDeps, WorkspaceScanDeps* Structural mirrors of the canonical `@lobechat/types` catalog contracts.* Kept local so device-control remains a leaf package with no app/type-layer dependency.*/+/**+ * An MCP server's connection, as the server forwards it for `listMcpTools`+ * (the shape tunneled MCP tool calls forward). Credentials travel decrypted and+ * narrowed to the token fields; the device stores nothing.+ */+export type ListMcpToolsConnection =+ | {+ auth?: { accessToken?: string; token?: string; type: 'none' | 'bearer' | 'oauth2' };+ headers?: Record<string, string>;+ name: string;+ type: 'http';+ url: string;+ }+ | {+ args: string[];+ command: string;+ env?: Record<string, string>;+ name: string;+ type: 'stdio';+ };++export interface ListMcpToolsParams {+ /** List on a session that announces MCP Apps, so view-only tools are listed too. */+ mcpApps?: boolean;+ params: ListMcpToolsConnection;+}++/**+ * A tool as the MCP server's `tools/list` returns it. Returned as listed, so+ * the server maps it exactly as it maps a listing it ran itself.+ */+export interface ListedMcpServerTool {+ _meta?: Record<string, unknown>;+ description?: string;+ inputSchema: object;+ name: string;+}+export interface ListHeterogeneousAgentModelsParams {args?: string[];command?: string;diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.tsindex 1bd01f9446c..3aaf617f9fa 100644--- a/packages/locales/src/default/plugin.ts+++ b/packages/locales/src/default/plugin.ts@@ -800,6 +800,13 @@ export default {'dev.mcp.command.label': 'Command','dev.mcp.command.placeholder': 'e.g. npx / uv / docker','dev.mcp.command.required': 'Enter command',+ 'dev.mcp.connectVia.auto': 'Auto',+ 'dev.mcp.connectVia.autoDesc':+ 'Decided by the address: localhost and LAN IPs connect from your device, every other address connects from the server.',+ 'dev.mcp.connectVia.device': 'Connect via device',+ 'dev.mcp.connectVia.deviceDesc':+ 'Connects from your own device. Use it for addresses only your computer can reach, such as intranet, Tailscale, or LAN hostnames. Keep the LobeHub desktop app open and online on a computer that can reach this server.',+ 'dev.mcp.connectVia.label': 'Connection','dev.mcp.desc.desc': 'Add Skill description','dev.mcp.desc.label': 'Description','dev.mcp.desc.placeholder': 'Usage instructions and scenarios',diff --git a/packages/openapi/src/services/mcp-server.service.ts b/packages/openapi/src/services/mcp-server.service.tsindex 9f050103829..29069ee49e6 100644--- a/packages/openapi/src/services/mcp-server.service.ts+++ b/packages/openapi/src/services/mcp-server.service.ts@@ -167,6 +167,8 @@ export class McpServerService extends BaseService {const { toolCount } = await syncConnectorToolsById(id, {connectorModel: model,connectorToolModel: this.connectorToolModel,+ // A connector set to connect through the device lists on the user's device+ serverDB: this.db,userId: this.userId,});return { id, status: ConnectorStatus.connected, toolCount };diff --git a/packages/types/src/plugins/mcp.ts b/packages/types/src/plugins/mcp.tsindex ee5568514fd..67867008635 100644--- a/packages/types/src/plugins/mcp.ts+++ b/packages/types/src/plugins/mcp.ts@@ -2,7 +2,7 @@ import type { PluginQueryParams, SystemDependency } from '@lobehub/market-sdk';import { z } from 'zod';import type { McpConnectionType } from '../discover/mcp';-import type { CustomPluginMetadata } from '../tool/plugin';+import type { CustomPluginMetadata, McpConnectVia } from '../tool/plugin';/*** MCP client error categories. Owned here so shared packages don't reach into@@ -220,6 +220,8 @@ export interface McpConnection {};// STDIO connection parameterscommand?: string;+ /** HTTP only: `device` reaches the server from the user's device (`McpConnectVia`). */+ connectVia?: McpConnectVia;env?: Record<string, string>;headers?: Record<string, string>;type: 'http' | 'stdio';diff --git a/packages/types/src/tool/plugin.ts b/packages/types/src/tool/plugin.tsindex ba7e9cbd005..dc5624ad530 100644--- a/packages/types/src/tool/plugin.ts+++ b/packages/types/src/tool/plugin.ts@@ -10,6 +10,15 @@ export interface CustomPluginMetadata {name?: string;}+/**+ * How an HTTP MCP server is reached: `auto` decides by its address (a+ * localhost / private-network URL from the user's device, any other from+ * wherever the call runs); `device` always connects from the user's device, for+ * addresses only their machine reaches (Tailscale, `.local`, intranet DNS).+ * Mirrors `McpConnectVia` in `@lobechat/utils/mcpEndpoint`, the routing rule.+ */+export type McpConnectVia = 'auto' | 'device';+export interface CustomPluginParams {apiMode?: 'openapi' | 'simple';avatar?: string;@@ -60,6 +69,8 @@ export interface CustomPluginParams {};// Added headers configuration supportheaders?: Record<string, string>;+ /** HTTP only: where the server is reached from. Absent means `auto`. */+ connectVia?: McpConnectVia;};useProxy?: boolean;}diff --git a/packages/utils/src/mcpEndpoint.test.ts b/packages/utils/src/mcpEndpoint.test.tsindex 40e363a5b52..b999c809a28 100644--- a/packages/utils/src/mcpEndpoint.test.ts+++ b/packages/utils/src/mcpEndpoint.test.ts@@ -1,6 +1,11 @@import { describe, expect, it } from 'vitest';-import { isDeviceOnlyMcpEndpoint } from './mcpEndpoint';+import {+ connectorConnectVia,+ connectorMcpEndpoint,+ isDeviceOnlyMcpEndpoint,+ shouldConnectViaDevice,+} from './mcpEndpoint';describe('isDeviceOnlyMcpEndpoint', () => {it('treats stdio as device-only', () => {@@ -18,4 +23,103 @@ describe('isDeviceOnlyMcpEndpoint', () => {expect(isDeviceOnlyMcpEndpoint({ type: 'cloud', url: 'http://localhost:3000' })).toBe(false);expect(isDeviceOnlyMcpEndpoint({})).toBe(false);});++ it('treats an HTTP endpoint set to connect through the device as device-only', () => {+ expect(+ isDeviceOnlyMcpEndpoint({+ connectVia: 'device',+ type: 'http',+ url: 'https://nas.tail1234.ts.net/mcp',+ }),+ ).toBe(true);+ // The choice is the user's even when the address can't be read+ expect(isDeviceOnlyMcpEndpoint({ connectVia: 'device', type: 'http' })).toBe(true);+ // A market-hosted server has no device side to connect from+ expect(+ isDeviceOnlyMcpEndpoint({ connectVia: 'device', type: 'cloud', url: 'https://x.dev' }),+ ).toBe(false);+ });+});++describe('shouldConnectViaDevice', () => {+ const urls = {+ domain: 'https://mcp.example.com/mcp',+ lan: 'http://192.168.1.8:8080/mcp',+ localhost: 'http://localhost:3000/mcp',+ magicDns: 'http://nas.tail1234.ts.net:8080/mcp',+ mdns: 'http://printer.local/mcp',+ tailscaleIp: 'http://100.101.102.103/mcp',+ };++ describe('with a device gateway', () => {+ const gateway = { deviceGatewayConfigured: true };++ it.each([+ ['domain', false],+ ['lan', true],+ ['localhost', true],+ ['magicDns', false],+ ['mdns', false],+ ['tailscaleIp', false],+ ] as const)('auto: %s → device=%s (decided by the address)', (key, expected) => {+ expect(shouldConnectViaDevice({ type: 'http', url: urls[key] }, gateway)).toBe(expected);+ expect(+ shouldConnectViaDevice({ connectVia: 'auto', type: 'http', url: urls[key] }, gateway),+ ).toBe(expected);+ });++ it.each(Object.keys(urls) as (keyof typeof urls)[])(+ 'device: %s always connects through the device',+ (key) => {+ expect(+ shouldConnectViaDevice({ connectVia: 'device', type: 'http', url: urls[key] }, gateway),+ ).toBe(true);+ },+ );++ it('runs stdio on the device and never a cloud server', () => {+ expect(shouldConnectViaDevice({ type: 'stdio' }, gateway)).toBe(true);+ expect(shouldConnectViaDevice({ connectVia: 'device', type: 'stdio' }, gateway)).toBe(true);+ expect(+ shouldConnectViaDevice({ connectVia: 'device', type: 'cloud', url: urls.domain }, gateway),+ ).toBe(false);+ });+ });++ describe('without a device gateway (self-hosted)', () => {+ const noGateway = { deviceGatewayConfigured: false };++ it('keeps every HTTP endpoint in-process, whatever the choice', () => {+ for (const url of Object.values(urls)) {+ expect(shouldConnectViaDevice({ type: 'http', url }, noGateway)).toBe(false);+ expect(shouldConnectViaDevice({ connectVia: 'device', type: 'http', url }, noGateway)).toBe(+ false,+ );+ }+ });++ it('still sends stdio to a device, so the caller fails instead of spawning it', () => {+ expect(shouldConnectViaDevice({ type: 'stdio' }, noGateway)).toBe(true);+ });+ });+});++describe('connectorMcpEndpoint', () => {+ it('reads the connection choice from the connector metadata', () => {+ expect(+ connectorMcpEndpoint({+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://mcp.example.com',+ metadata: { connectVia: 'device' },+ }),+ ).toEqual({ connectVia: 'device', type: 'http', url: 'https://mcp.example.com' });+ });++ it('reads anything but `device` as auto', () => {+ expect(connectorConnectVia(undefined)).toBe('auto');+ expect(connectorConnectVia(null)).toBe('auto');+ expect(connectorConnectVia({})).toBe('auto');+ expect(connectorConnectVia({ connectVia: 'cloud' })).toBe('auto');+ expect(connectorConnectVia({ connectVia: 'device' })).toBe('device');+ });});diff --git a/packages/utils/src/mcpEndpoint.ts b/packages/utils/src/mcpEndpoint.tsindex 577ecbd0798..955a78af3e8 100644--- a/packages/utils/src/mcpEndpoint.ts+++ b/packages/utils/src/mcpEndpoint.ts@@ -1,6 +1,20 @@import { isLocalOrPrivateUrl } from './url';+/**+ * How an HTTP MCP server is reached, as the user configured it:+ * - `auto` (the default): by address — a localhost / private-network URL is+ * reached from the user's device, any other from wherever the call runs;+ * - `device`: always from the user's device, for addresses only their machine+ * resolves or reaches although they look public (Tailscale MagicDNS, `.local`,+ * intranet DNS, a VPN).+ *+ * Stdio has no choice: it always runs on the user's device.+ */+export type McpConnectVia = 'auto' | 'device';+export interface McpEndpointShape {+ /** `device`: the user chose to reach this HTTP server from their device (`McpConnectVia`). */+ connectVia?: string | null;/** MCP transport: `stdio`, `http`, `cloud`, ... (`mcpConnectionType` on connector rows). */type?: string | null;/** HTTP endpoint (`mcpServerUrl` on connector rows). */@@ -9,10 +23,48 @@ export interface McpEndpointShape {/*** Whether an MCP endpoint is reachable only from the user's own machine: a- * stdio server (a local binary) or an HTTP endpoint on localhost / a private- * network. A cloud server can only call such an endpoint by tunneling to the- * user's device, so anything that must never touch that device (for example an- * Agent Share visitor run) has to refuse it.+ * stdio server (a local binary), an HTTP server set to connect through the+ * device, or an HTTP endpoint on localhost / a private network. A cloud server+ * can only call such an endpoint by tunneling to the user's device, so anything+ * that must never touch that device (for example an Agent Share visitor run)+ * has to refuse it.+ */+export const isDeviceOnlyMcpEndpoint = ({ connectVia, type, url }: McpEndpointShape): boolean =>+ type === 'stdio' ||+ (type !== 'cloud' && (connectVia === 'device' || (!!url && isLocalOrPrivateUrl(url))));++/**+ * Whether a server must run this MCP endpoint on the user's device instead of+ * connecting to it itself. The single routing rule for every server path (agent+ * tool calls, connector calls, tool-list syncs):+ *+ * - stdio always runs on a device, never in the server process; without a+ * device gateway the caller fails rather than spawning it;+ * - a device-only HTTP endpoint ({@link isDeviceOnlyMcpEndpoint}) goes through+ * the device gateway when one is configured. A self-hosted server without a+ * gateway keeps connecting in-process, since it may share the endpoint's LAN.+ */+export const shouldConnectViaDevice = (+ endpoint: McpEndpointShape,+ { deviceGatewayConfigured }: { deviceGatewayConfigured: boolean },+): boolean =>+ endpoint.type === 'stdio' || (deviceGatewayConfigured && isDeviceOnlyMcpEndpoint(endpoint));++/** The connection a connector row's MCP endpoint is configured with. */+export const connectorMcpEndpoint = (connector: {+ mcpConnectionType?: string | null;+ mcpServerUrl?: string | null;+ metadata?: { connectVia?: unknown } | null;+}): McpEndpointShape => ({+ connectVia: connectorConnectVia(connector.metadata),+ type: connector.mcpConnectionType,+ url: connector.mcpServerUrl,+});++/**+ * A connector's connection choice (`metadata.connectVia`). Only `device` is+ * stored; anything else reads as `auto`.*/-export const isDeviceOnlyMcpEndpoint = ({ type, url }: McpEndpointShape): boolean =>- type === 'stdio' || (type !== 'cloud' && !!url && isLocalOrPrivateUrl(url));+export const connectorConnectVia = (+ metadata: { connectVia?: unknown } | null | undefined,+): McpConnectVia => (metadata?.connectVia === 'device' ? 'device' : 'auto');diff --git a/src/app/(backend)/oauth/connector/callback/route.test.ts b/src/app/(backend)/oauth/connector/callback/route.test.tsindex 6d28a4476d2..80b707bf444 100644--- a/src/app/(backend)/oauth/connector/callback/route.test.ts+++ b/src/app/(backend)/oauth/connector/callback/route.test.ts@@ -125,6 +125,20 @@ describe('connector OAuth callback', () => {expect(body).toContain('"synced":true');});+ // A connector set to connect through the device lists its tools on the+ // user's device, which the sync can only find with the database+ it('syncs with the database, so a device-routed connector can list on the device', async () => {+ mockSync.mockResolvedValue({ toolCount: 5 });+ const { serverDB } = await import('@/database/server');++ await GET(makeReq());++ expect(mockSync).toHaveBeenCalledWith(+ 'c1',+ expect.objectContaining({ serverDB, userId: 'u1' }),+ );+ });+it('looks the connector up in the workspace it was started from', async () => {mockSync.mockResolvedValue({ toolCount: 5 });mockConsume.mockResolvedValue({diff --git a/src/app/(backend)/oauth/connector/callback/route.ts b/src/app/(backend)/oauth/connector/callback/route.tsindex 40ba2e3d8ea..54b05d047f4 100644--- a/src/app/(backend)/oauth/connector/callback/route.ts+++ b/src/app/(backend)/oauth/connector/callback/route.ts@@ -174,6 +174,8 @@ export const GET = async (req: NextRequest) => {const { toolCount } = await syncConnectorToolsById(payload.connectorId, {connectorModel,connectorToolModel,+ // A connector set to connect through the device lists on the user's device+ serverDB,userId: payload.lobeUserId,});synced = true;diff --git a/src/features/Connectors/CustomConnectorModal/index.tsx b/src/features/Connectors/CustomConnectorModal/index.tsxindex f0f2f8a98b2..d00ebb1ba97 100644--- a/src/features/Connectors/CustomConnectorModal/index.tsx+++ b/src/features/Connectors/CustomConnectorModal/index.tsx@@ -1,4 +1,5 @@-import { type LobeToolCustomPlugin } from '@lobechat/types';+import { type LobeToolCustomPlugin, type McpConnectVia } from '@lobechat/types';+import { connectorConnectVia } from '@lobechat/utils/mcpEndpoint';import { memo, useEffect, useMemo, useRef, useState } from 'react';import type { ConnectorCredentials, OIDCConfig } from '@/database/schemas';@@ -189,6 +190,7 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(type: authType === 'header' ? 'none' : authType,},command: mcpStdioConfig?.command,+ connectVia: connectorConnectVia(metadata),env: mcpStdioConfig?.env,headers: customHeaders,type: (connector.mcpConnectionType ?? 'http') as 'http' | 'stdio',@@ -249,12 +251,15 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(args?: string[];auth?: { clientId?: string; clientSecret?: string; token?: string; type?: string };command?: string;+ connectVia?: McpConnectVia;env?: Record<string, string>;headers?: Record<string, string>;type?: 'http' | 'stdio';url?: string;};const identifier = value.identifier;+ // Only `device` is stored; stdio always runs on the device anyway+ const connectViaDevice = mcp.type !== 'stdio' && mcp.connectVia === 'device';const isHttp = mcp.type !== 'stdio';const authType = mcp.auth?.type;@@ -292,6 +297,8 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(const nextMetadata: Record<string, unknown> = { ...connector.metadata };if (headers) nextMetadata.customHeaders = headers;else delete nextMetadata.customHeaders;+ if (connectViaDevice) nextMetadata.connectVia = 'device';+ else delete nextMetadata.connectVia;patch.metadata = nextMetadata;}@@ -345,6 +352,8 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(command: (mcp.command ?? '').trim(),env: cleanRecord(mcp.env),},+ // The OAuth create keeps the choice too; the other path rebuilds metadata below+ ...(connectViaDevice && { metadata: { connectVia: 'device' as const } }),name: identifier,sourceType: ConnectorSourceType.custom,};@@ -404,10 +413,14 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(// `fetchConnectors` completes it reports "absent" for a connector the// server already has, and the rollback below must never delete a// connector the user already had.+ const metadata = {+ ...(headers && { customHeaders: headers }),+ ...(connectViaDevice && { connectVia: 'device' as const }),+ };const { id: newConnectorId, isNew } = await createConnector({...base,credentials,- metadata: headers ? { customHeaders: headers } : undefined,+ metadata: Object.keys(metadata).length > 0 ? metadata : undefined,});try {await syncConnectorTools(newConnectorId);diff --git a/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.ts b/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.tsindex 34324b0ff82..1959520f67f 100644--- a/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.ts+++ b/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.ts@@ -115,6 +115,9 @@ export const buildConnectorPayloadFromLegacy = (legacy: LobeToolCustomPlugin): Mcredentials = { headers: extraHeaders, type: 'header' };}+ // The choice to connect through the device carries over (HTTP only)+ if (normalizedType === 'http' && mcp.connectVia === 'device') metadata.connectVia = 'device';+return {ok: true,payload: {diff --git a/src/features/MCPApp/entrypoints.test.ts b/src/features/MCPApp/entrypoints.test.tsindex 0c222f8054b..d4756fc0113 100644--- a/src/features/MCPApp/entrypoints.test.ts+++ b/src/features/MCPApp/entrypoints.test.ts@@ -4,15 +4,19 @@ import type { ToolStore } from '@/store/tool/store';import { mcpEntryTabKey, parseMcpEntryTab, selectMcpAppEntrypoints } from './entrypoints';-const env = vi.hoisted(() => ({ desktop: false }));+const env = vi.hoisted(() => ({ desktop: false, gateway: true }));vi.mock('@lobechat/const', async (importOriginal) => ({...(await importOriginal<object>()),get isDesktop() {return env.desktop;},}));+vi.mock('@/store/serverConfig/store', () => ({+ getServerConfigStoreState: () => ({ serverConfig: { deviceGatewayConfigured: env.gateway } }),+}));afterEach(() => {env.desktop = false;+ env.gateway = true;});const entry = { title: 'Notes', toolName: 'open' };@@ -89,4 +93,50 @@ describe('sidebar app entries', () => {'local-connector',]);});++ // The server tunnels their tool calls to the user's device, but not an app+ // view's calls: opening one on the web would always fail+ it('offers apps of servers that connect through the device on the desktop alone', () => {+ const open = { title: 'NAS', toolName: 'open' };+ const httpConnector = (identifier: string, mcpServerUrl: string, metadata?: object) => ({+ id: identifier,+ identifier,+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl,+ metadata,+ tools: [{ metadata: { threadEntry: open }, permission: 'auto', toolName: 'open' }],+ });+ const deviceRouted = {+ ...state,+ agentConnectors: {},+ connectors: [+ httpConnector('tailnet', 'https://nas.tail1234.ts.net/mcp', { connectVia: 'device' }),+ httpConnector('lan', 'http://192.168.1.5/mcp'),+ httpConnector('public', 'https://mcp.example.com/mcp'),+ ],+ installedPlugins: [+ ...(state.installedPlugins as object[]),+ {+ customParams: {+ mcp: { connectVia: 'device', type: 'http', url: 'https://nas.tail1234.ts.net/mcp' },+ },+ identifier: 'tailnet-plugin',+ manifest: { mcpAppEntrypoints: [open] },+ },+ ],+ } as unknown as ToolStore;+ const offered = () =>+ selectMcpAppEntrypoints(deviceRouted, true).map((item) => item.identifier);++ expect(offered()).toEqual(['notes', 'public']);++ // Self-hosted without a gateway, the server connects to them itself+ env.gateway = false;+ expect(offered()).toEqual(['notes', 'tailnet-plugin', 'tailnet', 'lan', 'public']);++ env.gateway = true;+ env.desktop = true;+ expect(offered()).toEqual(['notes', 'tailnet-plugin', 'tailnet', 'lan', 'public']);+ });});diff --git a/src/features/MCPApp/entrypoints.ts b/src/features/MCPApp/entrypoints.tsindex 14ba5586fc8..8e9e27b9317 100644--- a/src/features/MCPApp/entrypoints.ts+++ b/src/features/MCPApp/entrypoints.ts@@ -1,7 +1,13 @@import { isDesktop } from '@lobechat/const';import type { McpAppThreadEntry } from '@lobechat/const/mcpApp';+import {+ connectorMcpEndpoint,+ type McpEndpointShape,+ shouldConnectViaDevice,+} from '@lobechat/utils/mcpEndpoint';import { isInstalledPluginAvailableInCurrentEnv } from '@/helpers/toolAvailability';+import { getServerConfigStoreState } from '@/store/serverConfig/store';import { connectorSelectors } from '@/store/tool/slices/connector/selectors';import type { ToolStore } from '@/store/tool/store';@@ -23,6 +29,18 @@ export const parseMcpEntryTab = (tab: string) => {}};+/**+ * Whether an app's MCP server opens only in the desktop app: elsewhere the+ * server must run it on the user's device (stdio, a localhost / LAN address,+ * or set to connect through the device — `shouldConnectViaDevice`), and an+ * app view's calls are not tunneled there, so opening it always fails.+ */+const opensOnlyOnDesktop = (endpoint: McpEndpointShape) =>+ !isDesktop &&+ shouldConnectViaDevice(endpoint, {+ deviceGatewayConfigured: !!getServerConfigStoreState()?.serverConfig.deviceGatewayConfigured,+ });+export const selectMcpAppEntrypoints = (state: ToolStore,enabled: boolean,@@ -41,11 +59,13 @@ export const selectMcpAppEntrypoints = (if (connector && !connector.isEnabled) return [];const isMcp = connector && (connector.mcpServerUrl || connector.mcpConnectionType === 'stdio');const plugin = state.installedPlugins.find((item) => item.identifier === identifier);- // An app only a desktop can run (stdio) is offered there alone: elsewhere opening it always fails+ // An app only a desktop can open is offered there alone: elsewhere opening it always failsif (isMcp- ? connector.mcpConnectionType === 'stdio' && !isDesktop- : plugin && !isInstalledPluginAvailableInCurrentEnv(plugin)+ ? opensOnlyOnDesktop(connectorMcpEndpoint(connector))+ : plugin &&+ (!isInstalledPluginAvailableInCurrentEnv(plugin) ||+ (!!plugin.customParams?.mcp && opensOnlyOnDesktop(plugin.customParams.mcp))))return [];const entries = isMcpdiff --git a/src/features/PluginDevModal/MCPManifestForm/index.tsx b/src/features/PluginDevModal/MCPManifestForm/index.tsxindex 473b8911ac0..eeea272ca8b 100644--- a/src/features/PluginDevModal/MCPManifestForm/index.tsx+++ b/src/features/PluginDevModal/MCPManifestForm/index.tsx@@ -1,4 +1,4 @@-import { type LobeToolCustomPlugin } from '@lobechat/types';+import { type LobeToolCustomPlugin, type McpConnectVia } from '@lobechat/types';import { Alert, Button, Divider, Flexbox, Input, InputPassword, RadioGroup } from '@lobehub/ui';import { type FieldPath, Form, type FormInstance, useWatch } from '@lobehub/ui/form';import isEqual from 'fast-deep-equal';@@ -36,6 +36,7 @@ interface MCPManifestFormProps {}const HTTP_URL_KEY = 'customParams.mcp.url';+const CONNECT_VIA = 'customParams.mcp.connectVia';const STDIO_COMMAND = 'customParams.mcp.command';const STDIO_ARGS = 'customParams.mcp.args';const STDIO_ENV = 'customParams.mcp.env';@@ -49,6 +50,24 @@ const AUTH_CLIENT_SECRET = 'customParams.mcp.auth.clientSecret';// Headers-related constantsconst HEADERS = 'customParams.mcp.headers';+/** Unset reads as `auto`, the behavior a server without the choice always had. */+const ConnectViaRadio = ({+ onChange,+ options,+ value,+}: {+ onChange?: (value: McpConnectVia) => void;+ options: { label: string; value: McpConnectVia }[];+ value?: McpConnectVia;+}) => (+ <RadioGroup+ options={options}+ style={{ width: '100%' }}+ value={value ?? 'auto'}+ onChange={(next) => onChange?.(next as McpConnectVia)}+ />+);+const MCPManifestForm = ({form,isEditMode,@@ -58,6 +77,7 @@ const MCPManifestForm = ({const { t } = useTranslation('plugin');const mcpType = useWatch(form, MCP_TYPE);const authType = useWatch(form, AUTH_TYPE);+ const connectVia = useWatch(form, CONNECT_VIA);// For OAuth servers there is no token to test with — "testing" the connection// means running the authorize flow instead.const isOAuth = enableOAuth && mcpType === 'http' && authType === 'oauth2';@@ -218,6 +238,22 @@ const MCPManifestForm = ({><Input placeholder="https://mcp.higress.ai/mcp-github/xxxxx" /></Form.Field>+ <Form.Field+ label={t('dev.mcp.connectVia.label')}+ name={CONNECT_VIA}+ desc={+ connectVia === 'device'+ ? t('dev.mcp.connectVia.deviceDesc')+ : t('dev.mcp.connectVia.autoDesc')+ }+ >+ <ConnectViaRadio+ options={[+ { label: t('dev.mcp.connectVia.auto'), value: 'auto' },+ { label: t('dev.mcp.connectVia.device'), value: 'device' },+ ]}+ />+ </Form.Field><Form.Fielddesc={t('dev.mcp.auth.desc')}label={t('dev.mcp.auth.label')}diff --git a/src/features/PluginDevModal/pruneHiddenFields.test.ts b/src/features/PluginDevModal/pruneHiddenFields.test.tsindex 57d8e75dddd..7695f06ffa4 100644--- a/src/features/PluginDevModal/pruneHiddenFields.test.ts+++ b/src/features/PluginDevModal/pruneHiddenFields.test.ts@@ -21,6 +21,16 @@ const stale = {};describe('pruneHiddenFields', () => {+ it('keeps the HTTP connection choice and drops it after switching to stdio', () => {+ const http = pruneHiddenFields(plugin({ ...stale, connectVia: 'device', type: 'http' }))+ .customParams!.mcp!;+ expect(http.connectVia).toBe('device');++ const stdio = pruneHiddenFields(plugin({ ...stale, connectVia: 'device', type: 'stdio' }))+ .customParams!.mcp!;+ expect(stdio).not.toHaveProperty('connectVia');+ });+it('drops http fields after switching to stdio', () => {const mcp = pruneHiddenFields(plugin({ ...stale, type: 'stdio' })).customParams!.mcp!;diff --git a/src/features/PluginDevModal/pruneHiddenFields.ts b/src/features/PluginDevModal/pruneHiddenFields.tsindex 36dbc6327c2..af18d8ed884 100644--- a/src/features/PluginDevModal/pruneHiddenFields.ts+++ b/src/features/PluginDevModal/pruneHiddenFields.ts@@ -6,10 +6,11 @@ export const pruneHiddenFields = (values: LobeToolCustomPlugin): LobeToolCustomPconst mcp = values.customParams?.mcp;if (!mcp || (mcp.type !== 'http' && mcp.type !== 'stdio')) return values;- const { args, auth, command, env, headers, url, ...rest } = mcp;+ const { args, auth, command, connectVia, env, headers, url, ...rest } = mcp;let nextMcp: typeof mcp;if (mcp.type === 'stdio') {+ // Stdio always runs on the device: there is no connection to choosenextMcp = { ...rest, args, command, env };} else {let nextAuth = auth;@@ -21,7 +22,7 @@ export const pruneHiddenFields = (values: LobeToolCustomPlugin): LobeToolCustomP...(auth.type === 'oauth2' && { accessToken, clientId, clientSecret }),};}- nextMcp = { ...rest, auth: nextAuth, headers, url };+ nextMcp = { ...rest, auth: nextAuth, connectVia, headers, url };}return { ...values, customParams: { ...values.customParams, mcp: nextMcp } };diff --git a/src/libs/mcp/buildConnectorManifests.ts b/src/libs/mcp/buildConnectorManifests.tsindex aca4d272e17..ac90a602e08 100644--- a/src/libs/mcp/buildConnectorManifests.ts+++ b/src/libs/mcp/buildConnectorManifests.ts@@ -1,5 +1,6 @@import { buildConnectorManifest } from '@lobechat/mecha';import type { ToolManifest } from '@lobechat/types';+import { connectorConnectVia } from '@lobechat/utils/mcpEndpoint';import type { DecryptedConnector } from '@/database/models/connector';import type { UserConnectorToolItem } from '@/database/schemas';@@ -85,6 +86,9 @@ function buildMcpParams(connector: DecryptedConnector) {return {auth,+ // Only set when chosen, so `auto` keeps the params (and the MCP session+ // cached by them) it always had. Must match `buildConnectorMcpParams`.+ ...(connectorConnectVia(connector.metadata) === 'device' && { connectVia: 'device' as const }),headers: mergedHeaders,name: connector.identifier,type: 'http' as const,diff --git a/src/libs/mcp/localConnector.ts b/src/libs/mcp/localConnector.tsindex 9bc47fcf01c..7eebadec17d 100644--- a/src/libs/mcp/localConnector.ts+++ b/src/libs/mcp/localConnector.ts@@ -32,3 +32,25 @@ export const localConnectorHttpParams = (connector: {url: connector.mcpServerUrl,};};++/**+ * The HTTP params a call this desktop runs itself sends, with an OAuth+ * connector's access token: the edit read leaves OAuth tokens out, so it is+ * fetched (`connector.getLocalCallToken`, refreshed when due) when the+ * connector has an OAuth flow configured and no user-set credential.+ */+export const resolveLocalConnectorHttpParams = async (+ connector: Parameters<typeof localConnectorHttpParams>[0] & {+ id: string;+ oidcConfig?: unknown;+ },+ getLocalCallToken: (id: string) => Promise<{ accessToken: string; type: 'oauth2' } | null>,+) => {+ const http = localConnectorHttpParams(connector);+ if (http.auth || !connector.oidcConfig) return http;++ const oauth = await getLocalCallToken(connector.id);+ return oauth+ ? { ...http, auth: { accessToken: oauth.accessToken, type: 'oauth2' as const } }+ : http;+};diff --git a/src/libs/mcp/types.ts b/src/libs/mcp/types.tsindex 57f469eb6c9..753b6efb034 100644--- a/src/libs/mcp/types.ts+++ b/src/libs/mcp/types.ts@@ -135,6 +135,12 @@ export interface AuthConfig {export interface HttpMCPClientParams {auth?: AuthConfig;+ /**+ * `device`: the user chose to reach this server from their device; a server+ * with a device gateway tunnels it there (`shouldConnectViaDevice`). Never+ * read by the MCP client itself. Absent means `auto`.+ */+ connectVia?: 'device';headers?: Record<string, string>;name: string;type: 'http';diff --git a/src/services/mcp.deviceRoute.test.ts b/src/services/mcp.deviceRoute.test.tsnew file mode 100644index 00000000000..b6109e6ea5c--- /dev/null+++ b/src/services/mcp.deviceRoute.test.ts@@ -0,0 +1,323 @@+import { type ChatToolPayload } from '@lobechat/types';+import superjson from 'superjson';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { mcpService } from './mcp';++// Where an HTTP MCP server is reached from: a server only the user's machine+// reaches (a localhost / LAN address, or one set to connect through the device)+// is read and called over Desktop IPC, and on the web through the device+// gateway; any other through the server relay.++const mockElectronIpc = {+ mcp: {+ callTool: vi.fn(),+ getStreamableMcpServerManifest: vi.fn(),+ },+};++const environment = vi.hoisted(() => ({ isDesktop: false }));++vi.mock('@/store/serverConfig/store', () => ({+ getServerConfigStoreState: () => ({+ featureFlags: { enableMcpApps: false },+ serverConfig: { deviceGatewayConfigured: true },+ }),+}));++vi.mock('@lobechat/const', async (importOriginal) => ({+ ...((await importOriginal()) as Record<string, unknown>),+ CURRENT_VERSION: '1.0.0',+ get isDesktop() {+ return environment.isDesktop;+ },+}));++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ connector: {+ callTool: { mutate: vi.fn() },+ getDeviceMcpManifest: { mutate: vi.fn() },+ getForEdit: { query: vi.fn() },+ getLocalCallToken: { mutate: vi.fn() },+ },+ },+ toolsClient: {+ mcp: {+ callTool: { mutate: vi.fn() },+ getStreamableMcpServerManifest: { query: vi.fn() },+ },+ },+}));++vi.mock('@/utils/electron/ipc', () => ({+ ensureElectronIpc: () => mockElectronIpc,+}));++vi.mock('./discover', () => ({+ discoverService: {+ reportPluginCall: vi.fn().mockResolvedValue(undefined),+ safeInjectMPToken: vi.fn().mockResolvedValue(undefined),+ },+}));++const mockGetToolStoreState = vi.fn();+const mockPluginSelectors = {+ getCustomPluginById: vi.fn(),+ getInstalledPluginById: vi.fn(),+};++vi.mock('@/store/tool/store', () => ({+ getToolStoreState: () => mockGetToolStoreState(),+}));++vi.mock('@/store/tool/selectors', () => ({+ pluginSelectors: mockPluginSelectors,+}));++const TAILNET_URL = 'https://nas.tail1234.ts.net/mcp';+const manifest = {+ api: [],+ identifier: 'nas',+ mcpParams: { name: 'nas', type: 'http', url: TAILNET_URL },+ meta: { title: 'NAS' },+ version: '1',+};++beforeEach(() => {+ vi.clearAllMocks();+ environment.isDesktop = false;+ mockGetToolStoreState.mockReturnValue({});+ mockPluginSelectors.getInstalledPluginById.mockReturnValue(() => undefined);+ mockPluginSelectors.getCustomPluginById.mockReturnValue(() => undefined);+ mockElectronIpc.mcp.getStreamableMcpServerManifest.mockResolvedValue(+ superjson.serialize(manifest),+ );+ mockElectronIpc.mcp.callTool.mockResolvedValue(+ superjson.serialize({ content: 'ok', success: true }),+ );+});++describe('getStreamableMcpServerManifest routing', () => {+ const ipcPayload = () =>+ superjson.deserialize(+ mockElectronIpc.mcp.getStreamableMcpServerManifest.mock.calls[0][0],+ ) as Record<string, unknown>;++ it('reads a public-looking server set to connect through the device over IPC on desktop', async () => {+ const { lambdaClient, toolsClient } = await import('@/libs/trpc/client');+ environment.isDesktop = true;++ const result = await mcpService.getStreamableMcpServerManifest({+ auth: { type: 'none' },+ connectVia: 'device',+ identifier: 'nas',+ url: TAILNET_URL,+ });++ // Server-side agent runs route by the persisted `mcpParams`: the choice stays+ expect(result).toEqual({+ ...manifest,+ mcpParams: { ...manifest.mcpParams, connectVia: 'device' },+ });+ expect(ipcPayload()).toMatchObject({ identifier: 'nas', url: TAILNET_URL });+ // The routing choice is not a connection parameter+ expect(ipcPayload()).not.toHaveProperty('connectVia');+ expect(toolsClient.mcp.getStreamableMcpServerManifest.query).not.toHaveBeenCalled();+ expect(lambdaClient.connector.getDeviceMcpManifest.mutate).not.toHaveBeenCalled();+ });++ it('reads a localhost server over IPC on desktop without any setting', async () => {+ const { toolsClient } = await import('@/libs/trpc/client');+ environment.isDesktop = true;++ await mcpService.getStreamableMcpServerManifest({+ identifier: 'local',+ url: 'http://127.0.0.1:3000/mcp',+ });++ expect(mockElectronIpc.mcp.getStreamableMcpServerManifest).toHaveBeenCalledOnce();+ expect(toolsClient.mcp.getStreamableMcpServerManifest.query).not.toHaveBeenCalled();+ });++ it('keeps a public server on automatic routing on the server relay on desktop', async () => {+ const { toolsClient } = await import('@/libs/trpc/client');+ environment.isDesktop = true;++ await mcpService.getStreamableMcpServerManifest({+ connectVia: 'auto',+ identifier: 'nas',+ url: TAILNET_URL,+ });++ expect(mockElectronIpc.mcp.getStreamableMcpServerManifest).not.toHaveBeenCalled();+ expect(toolsClient.mcp.getStreamableMcpServerManifest.query).toHaveBeenCalledWith(+ { identifier: 'nas', url: TAILNET_URL },+ { signal: undefined },+ );+ });++ it('reads a server set to connect through the device via the device gateway on the web', async () => {+ const { lambdaClient, toolsClient } = await import('@/libs/trpc/client');+ vi.mocked(lambdaClient.connector.getDeviceMcpManifest.mutate).mockResolvedValue(+ manifest as never,+ );+ const signal = new AbortController().signal;++ const result = await mcpService.getStreamableMcpServerManifest(+ {+ auth: { token: 'secret', type: 'bearer' },+ connectVia: 'device',+ identifier: 'nas',+ url: TAILNET_URL,+ },+ signal,+ );++ expect(result).toEqual(manifest);+ expect(lambdaClient.connector.getDeviceMcpManifest.mutate).toHaveBeenCalledWith(+ { auth: { token: 'secret', type: 'bearer' }, identifier: 'nas', url: TAILNET_URL },+ { signal },+ );+ expect(toolsClient.mcp.getStreamableMcpServerManifest.query).not.toHaveBeenCalled();+ expect(mockElectronIpc.mcp.getStreamableMcpServerManifest).not.toHaveBeenCalled();+ });+});++describe('invokeMcpToolCall routing for HTTP servers', () => {+ const payload = { apiName: 'list_files', arguments: '{"dir":"/"}', identifier: 'nas' };++ describe('a plugin', () => {+ const usePlugin = (mcp: Record<string, unknown>) =>+ mockPluginSelectors.getCustomPluginById.mockReturnValue(() => ({+ customParams: { mcp: { type: 'http', url: TAILNET_URL, ...mcp } },+ identifier: 'nas',+ manifest: { meta: { title: 'NAS' }, version: '1' },+ }));++ it('calls a server set to connect through the device over IPC on desktop', async () => {+ const { toolsClient } = await import('@/libs/trpc/client');+ environment.isDesktop = true;+ usePlugin({ connectVia: 'device' });++ await mcpService.invokeMcpToolCall(payload as ChatToolPayload, {});++ const sent = superjson.deserialize(mockElectronIpc.mcp.callTool.mock.calls[0][0]);+ expect(sent).toMatchObject({+ args: { dir: '/' },+ http: { name: 'nas', url: TAILNET_URL },+ toolName: 'list_files',+ });+ expect(toolsClient.mcp.callTool.mutate).not.toHaveBeenCalled();+ });++ it('calls the same server on automatic routing through the server relay', async () => {+ const { toolsClient } = await import('@/libs/trpc/client');+ environment.isDesktop = true;+ usePlugin({});+ vi.mocked(toolsClient.mcp.callTool.mutate).mockResolvedValue({ content: 'ok' } as never);++ await mcpService.invokeMcpToolCall(payload as ChatToolPayload, {});++ expect(mockElectronIpc.mcp.callTool).not.toHaveBeenCalled();+ expect(toolsClient.mcp.callTool.mutate).toHaveBeenCalledOnce();+ });+ });++ describe('a connector', () => {+ const connector = {+ id: 'nas-id',+ identifier: 'nas',+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: TAILNET_URL,+ };+ const useConnector = (metadata: Record<string, unknown>) => {+ mockGetToolStoreState.mockReturnValue({ connectors: [{ ...connector, metadata }] });+ };++ it('calls one set to connect through the device over IPC on desktop with fresh config', async () => {+ const { lambdaClient } = await import('@/libs/trpc/client');+ environment.isDesktop = true;+ useConnector({ connectVia: 'device' });+ vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue({+ ...connector,+ metadata: { connectVia: 'device' },+ tools: [{ permission: 'auto', toolName: 'list_files' }],+ } as never);++ await mcpService.invokeMcpToolCall(payload as ChatToolPayload, {});++ expect(lambdaClient.connector.getForEdit.query).toHaveBeenCalledWith({ id: 'nas-id' });+ const sent = superjson.deserialize(mockElectronIpc.mcp.callTool.mock.calls[0][0]);+ expect(sent).toMatchObject({+ args: { dir: '/' },+ http: { url: TAILNET_URL },+ toolName: 'list_files',+ });+ expect(lambdaClient.connector.callTool.mutate).not.toHaveBeenCalled();+ });++ // `getForEdit` leaves OAuth tokens out; the call fetches the current one+ it("sends an OAuth connector's access token with a call it runs over IPC", async () => {+ const { lambdaClient } = await import('@/libs/trpc/client');+ environment.isDesktop = true;+ useConnector({ connectVia: 'device' });+ vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue({+ ...connector,+ credentials: null,+ metadata: { connectVia: 'device' },+ oidcConfig: { clientId: 'cid', issuer: 'https://auth.example.com' },+ tools: [{ permission: 'auto', toolName: 'list_files' }],+ } as never);+ vi.mocked(lambdaClient.connector.getLocalCallToken.mutate).mockResolvedValue({+ accessToken: 'fresh-access',+ type: 'oauth2',+ } as never);++ await mcpService.invokeMcpToolCall(payload as ChatToolPayload, {});++ expect(lambdaClient.connector.getLocalCallToken.mutate).toHaveBeenCalledWith({+ id: 'nas-id',+ });+ const sent = superjson.deserialize(mockElectronIpc.mcp.callTool.mock.calls[0][0]);+ expect(sent).toMatchObject({+ http: { auth: { accessToken: 'fresh-access', type: 'oauth2' }, url: TAILNET_URL },+ });+ });++ it('leaves one set to connect through the device to the server on the web', async () => {+ const { lambdaClient } = await import('@/libs/trpc/client');+ useConnector({ connectVia: 'device' });+ vi.mocked(lambdaClient.connector.callTool.mutate).mockResolvedValue({+ content: 'ok',+ success: true,+ } as never);++ await mcpService.invokeMcpToolCall(payload as ChatToolPayload, {});++ // The server tunnels it to the user's desktop through the device gateway+ expect(lambdaClient.connector.callTool.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ identifier: 'nas', toolName: 'list_files' }),+ expect.anything(),+ );+ expect(mockElectronIpc.mcp.callTool).not.toHaveBeenCalled();+ });++ it('leaves one on automatic routing to the server on desktop', async () => {+ const { lambdaClient } = await import('@/libs/trpc/client');+ environment.isDesktop = true;+ useConnector({});+ vi.mocked(lambdaClient.connector.callTool.mutate).mockResolvedValue({+ content: 'ok',+ success: true,+ } as never);++ await mcpService.invokeMcpToolCall(payload as ChatToolPayload, {});++ expect(lambdaClient.connector.callTool.mutate).toHaveBeenCalledOnce();+ expect(lambdaClient.connector.getForEdit.query).not.toHaveBeenCalled();+ expect(mockElectronIpc.mcp.callTool).not.toHaveBeenCalled();+ });+ });+});diff --git a/src/services/mcp.mcpApp.test.ts b/src/services/mcp.mcpApp.test.tsindex d3d332edc08..25f36b7efbd 100644--- a/src/services/mcp.mcpApp.test.ts+++ b/src/services/mcp.mcpApp.test.ts@@ -653,17 +653,16 @@ describe('mcpService.invokeMcpToolCall on desktop', () => {expect(result?.state).toEqual({ content: [] });});- it('keeps conversation calls to localhost / LAN http servers on their existing route', async () => {+ // Its tool list was read here over IPC; the server relay connects from the+ // server, which can't reach this machine's localhost / LAN+ it('runs conversation calls to localhost / LAN http servers here, where their tools were listed', async () => {plugins.set('local', httpPlugin('http://127.0.0.1:3000/mcp'));- relayCall.mockResolvedValue({ content: 'ok', success: true });+ ipcCall.mockResolvedValueOnce(serializeMcpIpcPayload({ content: 'ok', success: true }));await mcpService.invokeMcpToolCall(refresh, {});- expect(ipcCall).not.toHaveBeenCalled();- expect(relayCall).toHaveBeenCalledWith(- expect.objectContaining({ toolName: 'refresh' }),- expect.anything(),- );+ expect(relayCall).not.toHaveBeenCalled();+ expect(ipcCall).toHaveBeenCalledOnce();});});diff --git a/src/services/mcp.ts b/src/services/mcp.tsindex 61a8360ae60..fd71cc07be4 100644--- a/src/services/mcp.ts+++ b/src/services/mcp.ts@@ -15,7 +15,12 @@ import {type CheckMcpInstallResult,type CustomPluginMetadata,} from '@lobechat/types';-import { isLocalOrPrivateUrl, safeParseJSON } from '@lobechat/utils';+import { safeParseJSON } from '@lobechat/utils';+import {+ connectorMcpEndpoint,+ isDeviceOnlyMcpEndpoint,+ type McpConnectVia,+} from '@lobechat/utils/mcpEndpoint';import { deserializeMcpIpcPayload, serializeMcpIpcPayload } from '@lobechat/utils/mcpIpcPayload';import { toRecord } from '@lobechat/utils/object';import { type PluginManifest } from '@lobehub/market-sdk';@@ -24,7 +29,7 @@ import { type ReadResourceResult } from '@modelcontextprotocol/client';import { omit } from 'es-toolkit/compat';import { type MCPToolCallResult } from '@/libs/mcp';-import { localConnectorHttpParams } from '@/libs/mcp/localConnector';+import { resolveLocalConnectorHttpParams } from '@/libs/mcp/localConnector';import { renderMcpArgs, renderMcpUrlTemplate } from '@/libs/mcp/urlTemplate';import { getMCPConnectionErrorType } from '@/libs/mcp/utils';import { toolsClient } from '@/libs/trpc/client';@@ -295,6 +300,14 @@ class MCPService {: !!agentId && !plugin;if (isConnector) {const { lambdaClient } = await import('@/libs/trpc/client');+ // An HTTP server only this machine reaches (localhost / LAN, or set to+ // connect through the device) runs here over IPC, as its tool list was+ // read here: the server would have to tunnel it back to this device. A+ // view's call still runs where its result was produced.+ const isDeviceHttp =+ connector?.mcpConnectionType !== 'stdio' &&+ !!connector?.mcpServerUrl &&+ isDeviceOnlyMcpEndpoint(connectorMcpEndpoint(connector));const runsHere =connector &&isDesktop &&@@ -304,10 +317,7 @@ class MCPService {// These stdio servers ran on this desktop as plugins, gateway or notkeepsDesktopStdioExecution(connector) ||getServerConfigStoreState()?.serverConfig.deviceGatewayConfigured === false)) ||- (mcpApps &&- !!connector.mcpServerUrl &&- isLocalOrPrivateUrl(connector.mcpServerUrl) &&- (fromEntrypoint || (fromMcpApp && onThisDevice))));+ (isDeviceHttp && (fromMcpApp ? !!onThisDevice : true)));// A view's calls run where its result was producedif (fromMcpApp && !!runsHere !== !!onThisDevice) throw new Error(VIEW_SITE_MISMATCH);if (runsHere) {@@ -322,8 +332,10 @@ class MCPService {if (!fromEntrypoint && !fromMcpApp && !isSyncedMcpToolVisibleTo(tool, 'model', mcpApps)) {throw new Error(`Tool '${apiName}' can only be called from its interactive view`);}- if (detail.mcpConnectionType !== 'stdio' && mcpApps) {- const http = localConnectorHttpParams(detail);+ if (detail.mcpConnectionType !== 'stdio') {+ const http = await resolveLocalConnectorHttpParams(detail, (id) =>+ lambdaClient.connector.getLocalCallToken.mutate({ id }),+ );if (fromMcpApp && !(await isViewServer(server, { ...http, type: 'http' })))throw new Error(VIEW_SERVER_MOVED);throwIfAborted(signal);@@ -445,13 +457,20 @@ class MCPService {params = await pickViewServerParams(server, plugin, configured.params);if (!params) throw new Error(VIEW_SERVER_MOVED);}- // A view's call to an http server runs where its result was produced: over- // IPC when this desktop's process produced it (a localhost / LAN endpoint- // only it reaches), else on the server, which may reach its own LAN+ // An http server only this machine reaches (localhost / LAN, or set to+ // connect through the device) runs here over IPC, the route its manifest+ // was read on. A view's call runs where its result was produced: here when+ // this desktop's process produced it, else on the server.const isLocalHttp =isDesktop &&plugin?.customParams?.mcp?.type === 'http' &&- ((!!fromMcpApp && !!onThisDevice) || (!!fromEntrypoint && isLocalOrPrivateUrl(params.url)));+ (fromMcpApp+ ? !!onThisDevice+ : isDeviceOnlyMcpEndpoint({+ connectVia: params.connectVia,+ type: 'http',+ url: params.url,+ }));const isCustomPlugin = !!customPlugin;// Build meta for server-side reporting@@ -681,7 +700,9 @@ class MCPService {const { lambdaClient } = await import('@/libs/trpc/client');const detail = await lambdaClient.connector.getForEdit.query({ id: connector.id });if (!detail.isEnabled) return;- const http = localConnectorHttpParams(detail);+ const http = await resolveLocalConnectorHttpParams(detail, (id) =>+ lambdaClient.connector.getLocalCallToken.mutate({ id }),+ );if (!(await reaches({ ...http, type: 'http' }))) return;return deserializeMcpIpcPayload(await ensureElectronIpc().mcp.readUiResource(serializeMcpIpcPayload({ http, uri })),@@ -757,6 +778,7 @@ class MCPService {if (params.type === 'http' && params.url) {return this.getStreamableMcpServerManifest({auth: params.auth,+ connectVia: params.connectVia,headers: params.headers,identifier: plugin.identifier,url: params.url,@@ -772,6 +794,8 @@ class MCPService {token?: string;type: 'none' | 'bearer' | 'oauth2';};+ /** `device`: reach the server from the user's device, whatever its address. */+ connectVia?: McpConnectVia;headers?: Record<string, string>;identifier: string;metadata?: CustomPluginMetadata;@@ -779,20 +803,37 @@ class MCPService {},signal?: AbortSignal,) {- // If in Desktop mode and URL is local address, use IPC (main process)- // This avoids accessing user local services through remote server in production- if (isDesktop && isLocalOrPrivateUrl(params.url)) {+ const { connectVia, ...connection } = params;++ // A server only this machine reaches (a localhost / LAN address, or one set+ // to connect through the device) is read from the desktop over IPC (main+ // process), never through the remote server.+ if (isDesktop && isDeviceOnlyMcpEndpoint({ connectVia, type: 'http', url: params.url })) {// Note: IPC doesn't support AbortSignal yet// With MCP Apps on, the tools only views call are listed and kept too- const serialized = serializeMcpIpcPayload({ ...params, mcpApps: isMcpAppsOn() });+ const serialized = serializeMcpIpcPayload({ ...connection, mcpApps: isMcpAppsOn() });const serializedResult = await ensureElectronIpc().mcp.getStreamableMcpServerManifest(serialized as any,);- return deserializeMcpIpcPayload(serializedResult) as any;+ const manifest = deserializeMcpIpcPayload(serializedResult) as any;+ // The desktop builds `mcpParams` from the connection alone. Server-side+ // agent runs route by the persisted `mcpParams`, so the choice must stay+ // in it, as the device-gateway manifest below keeps it.+ return connectVia === 'device' && manifest?.mcpParams+ ? { ...manifest, mcpParams: { ...manifest.mcpParams, connectVia } }+ : manifest;+ }++ // On the web, a server set to connect through the device is read on the+ // user's desktop app through the device gateway (the server connects itself+ // when it has no gateway).+ if (connectVia === 'device') {+ const { lambdaClient } = await import('@/libs/trpc/client');+ return lambdaClient.connector.getDeviceMcpManifest.mutate(connection, { signal }) as any;}// Otherwise use toolsClient (via server relay)- return toolsClient.mcp.getStreamableMcpServerManifest.query(params, { signal });+ return toolsClient.mcp.getStreamableMcpServerManifest.query(connection, { signal });}/**diff --git a/src/store/tool/slices/connector/action.localSync.test.ts b/src/store/tool/slices/connector/action.localSync.test.tsindex b9711972180..3165d84ee67 100644--- a/src/store/tool/slices/connector/action.localSync.test.ts+++ b/src/store/tool/slices/connector/action.localSync.test.ts@@ -17,6 +17,7 @@ vi.mock('@/libs/trpc/client', () => ({lambdaClient: {connector: {getForEdit: { query: vi.fn() },+ getLocalCallToken: { mutate: vi.fn() },list: { query: vi.fn().mockResolvedValue([]) },syncTools: { mutate: vi.fn() },syncToolsFromClientById: { mutate: vi.fn() },@@ -85,4 +86,34 @@ describe('syncConnectorTools on desktop', () => {expect(lambdaClient.connector.syncTools.mutate).not.toHaveBeenCalled();},);++ // `getForEdit` leaves OAuth tokens out: listing without one would fail+ it('lists an OAuth connector set to connect through the device with its access token', async () => {+ vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue({+ credentials: null,+ id: 'c1',+ identifier: 'dash',+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://nas.tail1234.ts.net/mcp',+ metadata: { connectVia: 'device' },+ oidcConfig: { clientId: 'cid', issuer: 'https://auth.example.com' },+ } as any);+ vi.mocked(lambdaClient.connector.getLocalCallToken.mutate).mockResolvedValue({+ accessToken: 'fresh-access',+ type: 'oauth2',+ });++ const { result } = renderHook(() => useToolStore());+ await act(async () => {+ await result.current.syncConnectorTools('c1');+ });++ expect(lambdaClient.connector.getLocalCallToken.mutate).toHaveBeenCalledWith({ id: 'c1' });+ expect(mcpService.listLocalMcpTools).toHaveBeenCalledWith({+ http: expect.objectContaining({+ auth: { accessToken: 'fresh-access', type: 'oauth2' },+ url: 'https://nas.tail1234.ts.net/mcp',+ }),+ });+ });});diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.tsindex 05b6a238e7c..7d50f9e8699 100644--- a/src/store/tool/slices/connector/action.ts+++ b/src/store/tool/slices/connector/action.ts@@ -1,8 +1,9 @@import { isDesktop } from '@lobechat/const';-import { isLocalOrPrivateUrl } from '@lobechat/utils';+import { connectorMcpEndpoint, isDeviceOnlyMcpEndpoint } from '@lobechat/utils/mcpEndpoint';import type { SWRResponse } from 'swr';import type { ConnectorToolPermission } from '@/database/schemas';+import { resolveLocalConnectorHttpParams } from '@/libs/mcp/localConnector';import {cacheScope,createReplicaSlice,@@ -516,8 +517,8 @@ export class ConnectorActionImpl {/*** Desktop-only install/refresh path for connectors the cloud server cannot- * reach itself: stdio MCP (must spawn on this machine) and local/private- * network HTTP endpoints. The server-side `syncTools` would try to connect+ * reach itself: stdio MCP (must spawn on this machine), local/private+ * network HTTP endpoints, and HTTP set to connect through the device. The server-side `syncTools` would try to connect* FROM the cloud and fail with "Failed to start MCP service process" /* "fetch failed" (#16533), so the client lists the tools locally (via the* Electron main process, same path Test Connection uses) and reports them@@ -533,12 +534,13 @@ export class ConnectorActionImpl {if (!isDesktop) return false;// `getForEdit` returns the decrypted user-set credentials (bearer/apikey/- // header) needed to connect locally. OAuth2 tokens are machine-managed and- // never leave the server — but OAuth against a localhost endpoint would be- // server-unreachable anyway, so that combination stays on the server path.+ // header) needed to connect locally; an OAuth connector's access token is+ // fetched on its own (`resolveLocalConnectorHttpParams`).const detail = await lambdaClient.connector.getForEdit.query({ id });const isStdio = detail.mcpConnectionType === 'stdio';- const isLocalHttp = !!detail.mcpServerUrl && isLocalOrPrivateUrl(detail.mcpServerUrl);+ // A localhost / LAN address, or one the user set to connect through the device+ const isLocalHttp =+ !!detail.mcpServerUrl && isDeviceOnlyMcpEndpoint(connectorMcpEndpoint(detail));if (!isStdio && !isLocalHttp) return false;// The full tool list, not a manifest: a manifest leaves out view-only@@ -555,23 +557,11 @@ export class ConnectorActionImpl {},});} else {- const credentials = detail.credentials;- const auth =- credentials?.type === 'bearer'- ? { token: credentials.token, type: 'bearer' as const }- : credentials?.type === 'apikey'- ? { token: credentials.apiKey, type: 'bearer' as const }- : undefined;- // Custom headers live in metadata.customHeaders; legacy rows stored them- // as a 'header' credential — merge both, mirroring the server-side- // buildConnectorMcpParams.- const headerCreds = credentials?.type === 'header' ? credentials.headers : undefined;- const customHeaders = detail.metadata?.customHeaders as Record<string, string> | undefined;- const headers =- headerCreds || customHeaders ? { ...headerCreds, ...customHeaders } : undefined;- tools = await mcpService.listLocalMcpTools({- http: { auth, headers, name: detail.identifier, url: detail.mcpServerUrl! },- });+ // The same credentials and headers its tool calls send+ const http = await resolveLocalConnectorHttpParams(detail, (connectorId) =>+ lambdaClient.connector.getLocalCallToken.mutate({ id: connectorId }),+ );+ tools = await mcpService.listLocalMcpTools({ http });}await lambdaClient.connector.syncToolsFromClientById.mutate({diff --git a/src/store/tool/slices/customPlugin/action.ts b/src/store/tool/slices/customPlugin/action.tsindex c8042dcbe49..a95284076ff 100644--- a/src/store/tool/slices/customPlugin/action.ts+++ b/src/store/tool/slices/customPlugin/action.ts@@ -132,6 +132,7 @@ export class CustomPluginActionImpl {updateInstallLoadingState(id, true);const manifest = await mcpService.getStreamableMcpServerManifest({auth: plugin.customParams.mcp.auth,+ connectVia: plugin.customParams.mcp.connectVia,headers: plugin.customParams.mcp.headers,identifier: plugin.identifier,metadata: {diff --git a/src/store/tool/slices/mcpStore/action.ts b/src/store/tool/slices/mcpStore/action.tsindex a1b627a3b75..2f30f9e998c 100644--- a/src/store/tool/slices/mcpStore/action.ts+++ b/src/store/tool/slices/mcpStore/action.ts@@ -882,6 +882,8 @@ export class PluginMCPStoreActionImpl {manifest = await mcpService.getStreamableMcpServerManifest({auth: connection.auth,+ // Tested from where its calls will run: the device, when chosen+ connectVia: connection.connectVia,headers: connection.headers,identifier,metadata,