Skip to content

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

✨ feat(mcp): run stdio and local MCP connectors on lh connect devices (#23047)

Bryan45d3034f3b4f
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 6f6582637f5..0a443264b63 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -45,7 +45,7 @@ jobs:
runs-on: ubuntu-latest
name: Test Packages
env:
- PACKAGES: '@lobechat/file-loaders @lobechat/prompts @lobechat/model-runtime @lobechat/web-crawler @lobechat/electron-server-ipc @lobechat/utils @lobechat/context-engine @lobechat/agent-runtime @lobechat/conversation-flow @lobechat/editor-runtime @lobechat/ssrf-safe-fetch @lobechat/memory-user-memory @lobechat/types @lobechat/trpc @lobechat/app-config @lobechat/locales @lobechat/env @lobechat/builtin-tool-lobe-agent @lobechat/builtin-tool-message model-bank @lobechat/agent-gateway-client @lobechat/agent-manager-runtime @lobechat/device-gateway-client @lobechat/device-identity @lobechat/eval-dataset-parser @lobechat/eval-rubric @lobechat/fetch-sse @lobechat/heterogeneous-agents @lobechat/openapi'
+ PACKAGES: '@lobechat/file-loaders @lobechat/prompts @lobechat/model-runtime @lobechat/web-crawler @lobechat/electron-server-ipc @lobechat/utils @lobechat/context-engine @lobechat/agent-runtime @lobechat/conversation-flow @lobechat/editor-runtime @lobechat/ssrf-safe-fetch @lobechat/memory-user-memory @lobechat/types @lobechat/trpc @lobechat/app-config @lobechat/locales @lobechat/env @lobechat/builtin-tool-lobe-agent @lobechat/builtin-tool-message model-bank @lobechat/agent-gateway-client @lobechat/agent-manager-runtime @lobechat/device-gateway-client @lobechat/device-identity @lobechat/device-mcp @lobechat/eval-dataset-parser @lobechat/eval-rubric @lobechat/fetch-sse @lobechat/heterogeneous-agents @lobechat/openapi'
steps:
- name: Checkout
diff --git a/apps/cli/package.json b/apps/cli/package.json
index b0e10cea982..d9f97f338e3 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -44,6 +44,7 @@
"@lobechat/device-control": "workspace:*",
"@lobechat/device-gateway-client": "workspace:*",
"@lobechat/device-identity": "workspace:*",
+ "@lobechat/device-mcp": "workspace:*",
"@lobechat/eval-rubric": "workspace:*",
"@lobechat/heterogeneous-agents": "workspace:*",
"@lobechat/html-artifact": "workspace:*",
diff --git a/apps/cli/pnpm-workspace.yaml b/apps/cli/pnpm-workspace.yaml
index 03bb2caeef7..75b93c090c2 100644
--- a/apps/cli/pnpm-workspace.yaml
+++ b/apps/cli/pnpm-workspace.yaml
@@ -4,6 +4,7 @@ packages:
- '../../packages/device-control'
- '../../packages/device-sandbox'
- '../../packages/device-gateway-client'
+ - '../../packages/device-mcp'
- '../../packages/device-identity'
- '../../packages/heterogeneous-agents'
- '../../packages/html-artifact'
diff --git a/apps/cli/src/commands/connect/handlers.test.ts b/apps/cli/src/commands/connect/handlers.test.ts
new file mode 100644
index 00000000000..4758be8f6b0
--- /dev/null
+++ b/apps/cli/src/commands/connect/handlers.test.ts
@@ -0,0 +1,120 @@
+import type { GatewayClient, ToolCallRequestMessage } from '@lobechat/device-gateway-client';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { executeDeviceMcpCall } from '../../device/mcp';
+import { executeToolCall } from '../../tools';
+import { bindGatewayClientHandlers, type GatewayHandlerContext } from './handlers';
+
+vi.mock('../../tools', () => ({
+ executeToolCall: vi.fn().mockResolvedValue({ content: 'local tool ran', success: true }),
+}));
+
+vi.mock('../../daemon/manager', () => ({ appendLog: vi.fn() }));
+
+vi.mock('../../device/mcp', () => ({
+ executeDeviceMcpCall: vi.fn().mockResolvedValue({ content: 'mcp tool ran', success: true }),
+}));
+
+const createClient = () => {
+ const handlers: Record<string, (...args: any[]) => Promise<void>> = {};
+ const client = {
+ on: vi.fn((event: string, handler: (...args: any[]) => Promise<void>) => {
+ handlers[event] = handler;
+ }),
+ sendToolCallResponse: vi.fn(),
+ };
+ return { client, handlers };
+};
+
+const createContext = (): GatewayHandlerContext =>
+ ({
+ deps: {},
+ error: vi.fn(),
+ getAuth: () => ({ serverUrl: 'https://app.test', token: 'token' }),
+ getToolAuth: () => ({ serverUrl: 'https://app.test', token: 'token' }),
+ info: vi.fn(),
+ isDaemonChild: true,
+ maintenance: { afterResponse: vi.fn(), run: (fn: () => unknown) => fn() },
+ nativeRuntimes: { get: vi.fn().mockResolvedValue([]) },
+ recordRequest: vi.fn(),
+ }) as unknown as GatewayHandlerContext;
+
+const toolCallRequest = (
+ toolCall: Partial<ToolCallRequestMessage['toolCall']>,
+): ToolCallRequestMessage => ({
+ requestId: 'req-1',
+ toolCall: { apiName: 'runCommand', arguments: '{"command":"id"}', identifier: 'x', ...toolCall },
+ type: 'tool_call_request',
+});
+
+describe('bindGatewayClientHandlers tool_call_request routing', () => {
+ let client: ReturnType<typeof createClient>['client'];
+ let handlers: ReturnType<typeof createClient>['handlers'];
+
+ beforeEach(() => {
+ vi.mocked(executeToolCall).mockClear();
+ vi.mocked(executeDeviceMcpCall).mockClear();
+ ({ client, handlers } = createClient());
+ bindGatewayClientHandlers(client as unknown as GatewayClient, createContext());
+ });
+
+ it('runs a plain tool call, and one from an older server without a type, locally', async () => {
+ await handlers.tool_call_request(toolCallRequest({ type: 'tool' }));
+ await handlers.tool_call_request(toolCallRequest({}));
+
+ expect(executeToolCall).toHaveBeenCalledTimes(2);
+ });
+
+ it('runs a tunneled MCP call on the MCP runtime, not the same-named local tool', async () => {
+ const params = {
+ args: ['--stdio'],
+ command: 'mcp-server',
+ name: 'some-mcp-server',
+ type: 'stdio' as const,
+ };
+ await handlers.tool_call_request({
+ ...toolCallRequest({ identifier: 'some-mcp-server', params, type: 'mcp' }),
+ timeout: 30_000,
+ });
+
+ expect(executeToolCall).not.toHaveBeenCalled();
+ expect(executeDeviceMcpCall).toHaveBeenCalledWith(
+ { apiName: 'runCommand', arguments: '{"command":"id"}', params, timeout: 30_000 },
+ expect.any(Function),
+ );
+ expect(client.sendToolCallResponse).toHaveBeenCalledWith({
+ requestId: 'req-1',
+ result: expect.objectContaining({ content: 'mcp tool ran', success: true }),
+ });
+ });
+
+ it('fails an MCP call that carries no connection params', async () => {
+ await handlers.tool_call_request(toolCallRequest({ type: 'mcp' }));
+
+ expect(executeDeviceMcpCall).not.toHaveBeenCalled();
+ expect(executeToolCall).not.toHaveBeenCalled();
+ expect(client.sendToolCallResponse).toHaveBeenCalledWith({
+ requestId: 'req-1',
+ result: expect.objectContaining({ success: false }),
+ });
+ });
+
+ it('never runs a same-named local tool for a call kind it does not support', async () => {
+ await handlers.tool_call_request(
+ toolCallRequest({
+ identifier: 'some-mcp-server',
+ params: { args: [], command: 'mcp-server', name: 'some-mcp-server', type: 'stdio' },
+ type: 'skill' as any,
+ }),
+ );
+
+ expect(executeToolCall).not.toHaveBeenCalled();
+ expect(client.sendToolCallResponse).toHaveBeenCalledWith({
+ requestId: 'req-1',
+ result: expect.objectContaining({
+ error: expect.stringContaining('does not support "skill" tool calls'),
+ success: false,
+ }),
+ });
+ });
+});
diff --git a/apps/cli/src/commands/connect/handlers.ts b/apps/cli/src/commands/connect/handlers.ts
index 3491d305fee..fa4bae96cdb 100644
--- a/apps/cli/src/commands/connect/handlers.ts
+++ b/apps/cli/src/commands/connect/handlers.ts
@@ -16,6 +16,7 @@ import type { CliMaintenance } from '../../daemon/maintenance';
import { appendLog } from '../../daemon/manager';
import type { ActivityReporter } from '../../device/activityHook';
import { spawnHeteroAgentRun } from '../../device/agentRun';
+import { executeDeviceMcpCall } from '../../device/mcp';
import { collectSystemInfo } from '../../device/systemInfo';
import { executeToolCall } from '../../tools';
import { executeBrowserCall, type resolveBrowserDevice } from '../../tools/browser';
@@ -96,16 +97,42 @@ export function bindGatewayClientHandlers(
// round trip, so reporting this back is what separates a slow tool from
// slow transport.
const startedAt = performance.now();
+ const dispatch = async () => {
+ const type = toolCall.type ?? 'tool';
+ // Route on the explicit discriminator, never on the apiName alone: a
+ // call of a kind this client does not run (e.g. an MCP server's
+ // `runCommand`) must fail instead of reaching a same-named local tool.
+ if (type === 'mcp') {
+ // A tunneled MCP call for a server only this machine reaches: a stdio
+ // binary, or a localhost / LAN HTTP endpoint.
+ if (!toolCall.params) {
+ const message = 'MCP tool call is missing its connection params.';
+ return { content: message, error: message, state: undefined, success: false };
+ }
+ return executeDeviceMcpCall(
+ {
+ apiName: toolCall.apiName,
+ arguments: toolCall.arguments,
+ params: toolCall.params,
+ timeout,
+ },
+ getToolAuth,
+ );
+ }
+ if (type !== 'tool') {
+ const message = `This device's lh connect does not support "${type}" tool calls. Update the LobeHub CLI and retry.`;
+ return { content: message, error: message, state: undefined, success: false };
+ }
+ // Computer Use's `runCommand` shares its apiName with the shell tool, and
+ // the browser's apis (`click`, `screenshot`, …) are routed by identifier too.
+ return toolCall.identifier === COMPUTER_USE_IDENTIFIER
+ ? executeComputerUseCall(computerUse, toolCall.apiName, toolCall.arguments, timeout)
+ : toolCall.identifier === BROWSER_IDENTIFIER
+ ? executeBrowserCall(browser, toolCall.apiName, toolCall.arguments, timeout)
+ : executeToolCall(toolCall.apiName, toolCall.arguments, timeout, getToolAuth());
+ };
const result = await executeDeviceOperation({ apiName: toolCall.apiName, operationId }, () =>
- maintenance.run(() =>
- // Computer Use's `runCommand` shares its apiName with the shell tool, and
- // the browser's apis (`click`, `screenshot`, …) are routed by identifier too.
- toolCall.identifier === COMPUTER_USE_IDENTIFIER
- ? executeComputerUseCall(computerUse, toolCall.apiName, toolCall.arguments, timeout)
- : toolCall.identifier === BROWSER_IDENTIFIER
- ? executeBrowserCall(browser, toolCall.apiName, toolCall.arguments, timeout)
- : executeToolCall(toolCall.apiName, toolCall.arguments, timeout, getToolAuth()),
- ),
+ maintenance.run(dispatch),
).catch((err: Error) => ({
content: '',
error: err.message,
diff --git a/apps/cli/src/commands/connect/index.ts b/apps/cli/src/commands/connect/index.ts
index 2a6fc64898c..53c237fbf78 100644
--- a/apps/cli/src/commands/connect/index.ts
+++ b/apps/cli/src/commands/connect/index.ts
@@ -49,6 +49,7 @@ import {
resolveCliDeviceGateway,
} from '../../device/gatewayEndpoint';
import { MANAGED_GATEWAY_ENV } from '../../device/managed';
+import { disposeDeviceMcp } from '../../device/mcp';
import {
mintWorkspaceConnectToken,
registerDevice,
@@ -1024,6 +1025,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
managed?.session.stop();
activity?.stop();
cleanupAllProcesses();
+ void disposeDeviceMcp();
// Kill every remote-terminal shell this daemon started, so a stopping
// `lh connect` does not leave orphaned PTYs behind on the machine.
terminals.dispose();
@@ -1045,6 +1047,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
await Promise.all([
metricsSampler?.stop({ flushTimeoutMs: SHUTDOWN_METRICS_FLUSH_MS }),
closeBrowserSessions(browser),
+ disposeDeviceMcp(),
]);
cleanup();
process.exit(exitCode);
diff --git a/apps/cli/src/device/mcp.test.ts b/apps/cli/src/device/mcp.test.ts
new file mode 100644
index 00000000000..2bca50d89ec
--- /dev/null
+++ b/apps/cli/src/device/mcp.test.ts
@@ -0,0 +1,94 @@
+import { mkdtemp, readFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { disposeDeviceMcp, executeDeviceMcpCall } from './mcp';
+
+const { resolveUserSpawnPath } = vi.hoisted(() => ({
+ resolveUserSpawnPath: vi.fn(async () => process.env.PATH),
+}));
+
+// The login-shell probe spawns the user's shell; the inherited PATH is enough here.
+vi.mock('@lobechat/heterogeneous-agents/resolveCliCommand', () => ({ resolveUserSpawnPath }));
+
+/** A real stdio MCP server exposing one `echo` tool; argv[2] records every spawn. */
+const fixture = fileURLToPath(
+ new URL('../../../../src/libs/mcp/__tests__/fixtures/legacyStdio.mjs', import.meta.url),
+);
+
+const stdioCall = (trace: string, env?: Record<string, string>) => ({
+ apiName: 'echo',
+ arguments: '{}',
+ params: {
+ args: [fixture, trace],
+ command: process.execPath,
+ env,
+ name: 'echo-fixture',
+ type: 'stdio' as const,
+ },
+});
+
+const dirs: string[] = [];
+
+afterEach(async () => {
+ await disposeDeviceMcp();
+ await Promise.all(dirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));
+ resolveUserSpawnPath.mockClear();
+});
+
+describe('executeDeviceMcpCall', () => {
+ it(
+ 'runs a tunneled stdio MCP tool on this machine and keeps its session across calls',
+ { 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 first = await executeDeviceMcpCall(stdioCall(trace), () => undefined);
+ const second = await executeDeviceMcpCall(stdioCall(trace), () => undefined);
+
+ expect(first).toMatchObject({ content: 'Stdio MCP tool succeeded', success: true });
+ expect(second).toMatchObject({ content: 'Stdio MCP tool succeeded', success: true });
+ // One process served both calls: a stateful server keeps its state.
+ const spawns = (await readFile(trace, 'utf8')).split('\n').filter((line) => line === 'spawn');
+ expect(spawns).toHaveLength(1);
+ },
+ );
+
+ it('spawns with the login-shell PATH unless the connector set its own', async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'cli-device-mcp-'));
+ dirs.push(dir);
+
+ await executeDeviceMcpCall(stdioCall(path.join(dir, 'a.txt')), () => undefined);
+ expect(resolveUserSpawnPath).toHaveBeenCalledTimes(1);
+
+ await executeDeviceMcpCall(
+ stdioCall(path.join(dir, 'b.txt'), { PATH: process.env.PATH ?? '' }),
+ () => undefined,
+ );
+ expect(resolveUserSpawnPath).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports a server that cannot start as a failed call instead of throwing', async () => {
+ const result = await executeDeviceMcpCall(
+ {
+ apiName: 'echo',
+ arguments: '{}',
+ params: {
+ args: [],
+ command: 'lobehub-missing-mcp-server-binary',
+ name: 'missing',
+ type: 'stdio',
+ },
+ },
+ () => undefined,
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBeTruthy();
+ });
+});
diff --git a/apps/cli/src/device/mcp.ts b/apps/cli/src/device/mcp.ts
new file mode 100644
index 00000000000..17f0f18c685
--- /dev/null
+++ b/apps/cli/src/device/mcp.ts
@@ -0,0 +1,130 @@
+import type { GatewayMcpParams } from '@lobechat/device-gateway-client';
+import type { DeviceMcpRuntime, MCPClientParams } from '@lobechat/device-mcp';
+import { resolveUserSpawnPath } from '@lobechat/heterogeneous-agents/resolveCliCommand';
+
+import { createLambdaClient } from '../api/client';
+import { log } from '../utils/logger';
+import { uploadFileBuffer } from '../utils/uploadLocalFile';
+
+type ToolAuth = Parameters<typeof createLambdaClient>[0];
+
+export interface DeviceMcpCall {
+ apiName: string;
+ arguments: string;
+ params: GatewayMcpParams;
+ timeout?: number;
+}
+
+export interface DeviceMcpCallResult {
+ content: string;
+ error?: string;
+ state?: unknown;
+ success: boolean;
+}
+
+let runtime: Promise<DeviceMcpRuntime> | undefined;
+/** The resolved runtime, so a synchronous exit path can still tear it down. */
+let runtimeInstance: DeviceMcpRuntime | undefined;
+/** Read per upload: the device's credentials may be refreshed mid-session. */
+let currentToolAuth: () => ToolAuth | undefined = () => undefined;
+
+const getRuntime = () => {
+ // Lazy: the MCP SDK and the runtime load only once a device runs an MCP call.
+ runtime ??= import('@lobechat/device-mcp').then(({ DeviceMcpRuntime }) => {
+ runtimeInstance = new DeviceMcpRuntime({
+ clientName: 'lobehub-cli-mcp-client',
+ // An uploaded block's key is already the file's URL.
+ getMediaUrl: async (url) => url,
+ logger: { error: (message) => log.debug(message), warn: (message) => log.debug(message) },
+ uploadMedia: async ({ buffer, filename, mimeType }) => {
+ const auth = currentToolAuth();
+ // A managed device's token authenticates with the gateway only.
+ if (!auth) return undefined;
+ const file = await uploadFileBuffer(createLambdaClient(auth), {
+ buffer,
+ fileName: filename,
+ fileType: mimeType,
+ });
+ return (file as { url?: string })?.url;
+ },
+ });
+ return runtimeInstance;
+ });
+ return runtime;
+};
+
+/**
+ * A service manager (launchd / systemd) starts the daemon with a minimal PATH,
+ * where `npx` / `uvx` / nvm binaries are missing. Spawn stdio servers with the
+ * user's login-shell PATH, as the desktop app does, unless the connector set
+ * its own PATH.
+ */
+const toClientParams = async (params: GatewayMcpParams): Promise<MCPClientParams> => {
+ if (params.type === 'http') {
+ return {
+ auth: params.auth,
+ headers: params.headers,
+ name: params.name,
+ type: 'http',
+ url: params.url,
+ };
+ }
+
+ const env = params.env ?? {};
+ const spawnPath = env.PATH === undefined ? await resolveUserSpawnPath() : undefined;
+ return {
+ args: params.args ?? [],
+ command: params.command,
+ env: spawnPath ? { ...env, PATH: spawnPath } : params.env,
+ name: params.name,
+ type: 'stdio',
+ };
+};
+
+/**
+ * Run a tunneled MCP call on this machine β€” a stdio server, or an HTTP
+ * endpoint only this machine's network reaches. Sessions are pooled across
+ * calls (stateful stdio servers keep their state) for the life of the
+ * connect process; {@link disposeDeviceMcp} ends them.
+ */
+export async function executeDeviceMcpCall(
+ call: DeviceMcpCall,
+ getToolAuth: () => ToolAuth | undefined,
+): Promise<DeviceMcpCallResult> {
+ currentToolAuth = getToolAuth;
+ try {
+ const mcp = await getRuntime();
+ const result = await mcp.runTool(
+ await toClientParams(call.params),
+ call.apiName,
+ call.arguments,
+ {
+ timeoutMs: call.timeout,
+ },
+ );
+ return {
+ content: result.content,
+ error: result.error?.message,
+ state: result.state,
+ success: result.success,
+ };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ return { content: message, error: message, state: undefined, success: false };
+ }
+}
+
+/**
+ * Disconnect every pooled MCP session so no stdio server outlives the process.
+ * Every disconnect starts synchronously, so an exit path that cannot await
+ * (connect's `cleanup()` right before `process.exit`) still closes each
+ * server's stdin; awaiting the result waits for the teardowns to settle.
+ */
+export async function disposeDeviceMcp(): Promise<void> {
+ const instance = runtimeInstance;
+ runtime = undefined;
+ runtimeInstance = undefined;
+ // `dispose()` starts every disconnect before its first await, so this call
+ // is already under way when an un-awaited caller moves on.
+ await instance?.dispose();
+}
diff --git a/apps/cli/src/device/systemInfo.test.ts b/apps/cli/src/device/systemInfo.test.ts
index e62dafae86c..9dc06346a66 100644
--- a/apps/cli/src/device/systemInfo.test.ts
+++ b/apps/cli/src/device/systemInfo.test.ts
@@ -61,6 +61,13 @@ describe('probeNativeRuntimes', () => {
expect(codexProbe.close).toHaveBeenCalledOnce();
});
+ /** @example The server tunnels stdio / local-network MCP calls only to a CLI that says it runs them. */
+ it('reports that this client runs tunneled MCP calls', async () => {
+ await expect(collectSystemInfo(uncachedProbe)).resolves.toMatchObject({
+ supportedToolCallTypes: ['tool', 'mcp'],
+ });
+ });
+
/** @example A handshake timeout must not stall device discovery or advertise support. */
it('bounds native Codex probing and closes the stalled client', async () => {
vi.useFakeTimers();
diff --git a/apps/cli/src/device/systemInfo.ts b/apps/cli/src/device/systemInfo.ts
index 0866c5436f4..1984e9339f3 100644
--- a/apps/cli/src/device/systemInfo.ts
+++ b/apps/cli/src/device/systemInfo.ts
@@ -79,7 +79,8 @@ export async function probeNativeRuntimes(): Promise<string[]> {
/**
* The answer to a gateway `system_info_request`: host paths and live native capabilities.
* `supportedTools` lists the opt-in tools this device can run; the server refuses those
- * tools on a device that does not list them.
+ * tools on a device that does not list them. `supportedToolCallTypes` tells it this
+ * client runs tunneled MCP calls, which older CLIs mis-dispatched by apiName.
*
* Use when: a gateway requests this connection's current system information.
* Expects: local paths and binary resolution belong to this connect process.
@@ -113,6 +114,8 @@ export async function collectSystemInfo(
musicPath: path.join(home, 'Music'),
picturesPath: path.join(home, 'Pictures'),
supportedAgentRuntimes: await nativeRuntimes.get(),
+ // Tunneled MCP calls (stdio / local-network servers) run on this machine.
+ supportedToolCallTypes: ['tool', 'mcp'],
...(supportedTools.length > 0 && { supportedTools }),
userDataPath: path.join(home, CLI_CONFIG_DIR_NAME),
videosPath: path.join(home, videosDir),
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 4b77fb2be58..5a08eb61a28 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -75,6 +75,7 @@
"@lobechat/device-control": "workspace:*",
"@lobechat/device-gateway-client": "workspace:*",
"@lobechat/device-identity": "workspace:*",
+ "@lobechat/device-mcp": "workspace:*",
"@lobechat/device-sandbox": "workspace:*",
"@lobechat/electron-client-ipc": "workspace:*",
"@lobechat/electron-mac-notifications": "workspace:*",
diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yaml
index 4752e861d71..650b17960e5 100644
--- a/apps/desktop/pnpm-lock.yaml
+++ b/apps/desktop/pnpm-lock.yaml
@@ -79,6 +79,9 @@ importers:
'@lobechat/device-identity':
specifier: workspace:*
version: link:../../packages/device-identity
+ '@lobechat/device-mcp':
+ specifier: workspace:*
+ version: link:../../packages/device-mcp
'@lobechat/device-sandbox':
specifier: workspace:*
version: link:../../packages/device-sandbox
@@ -397,6 +400,22 @@ importers:
specifier: 5.0.3
+ ../../packages/device-mcp:
+ dependencies:
+ '@lobechat/const':
+ specifier: workspace:*
+ version: link:../const
+ '@lobechat/utils':
+ specifier: workspace:*
+ version: link:../utils
+ '@modelcontextprotocol/client':
+ specifier: ~2.4.0
+ version: 2.4.0
+ devDependencies:
+ vitest:
+ specifier: 5.0.3
+
../../packages/device-sandbox:
dependencies:
'@anthropic-ai/sandbox-runtime':
@@ -834,6 +853,9 @@ importers:
'@lobechat/device-identity':
specifier: workspace:*
version: link:../../packages/device-identity
+ '@lobechat/device-mcp':
+ specifier: workspace:*
+ version: link:../../packages/device-mcp
'@lobechat/eval-rubric':
specifier: workspace:*
version: link:../../packages/eval-rubric
diff --git a/apps/desktop/pnpm-workspace.yaml b/apps/desktop/pnpm-workspace.yaml
index 1a5bd830d1c..4bba68fa7ef 100644
--- a/apps/desktop/pnpm-workspace.yaml
+++ b/apps/desktop/pnpm-workspace.yaml
@@ -19,6 +19,7 @@ packages:
- '../../packages/device-control'
- '../../packages/device-sandbox'
- '../../packages/device-gateway-client'
+ - '../../packages/device-mcp'
- '../../packages/device-identity'
- '../../packages/local-file-shell'
- '../../packages/tool-runtime'
diff --git a/apps/desktop/src/main/controllers/McpCtr.mcpApp.test.ts b/apps/desktop/src/main/controllers/McpCtr.mcpApp.test.ts
index 9402eb3bb39..d0f62c9a5dc 100644
--- a/apps/desktop/src/main/controllers/McpCtr.mcpApp.test.ts
+++ b/apps/desktop/src/main/controllers/McpCtr.mcpApp.test.ts
@@ -11,7 +11,7 @@ const { mcpClientMocks } = vi.hoisted(() => ({
mcpClientMocks: vi.fn(),
}));
-vi.mock('../libs/mcp/client', () => ({
+vi.mock('@lobechat/device-mcp/client', () => ({
MCPClient: class {
constructor(
public params: unknown,
@@ -94,7 +94,7 @@ describe('McpCtr MCP Apps', () => {
toolName: 'show_weather',
} as any);
- expect(mcpClientMocks).toHaveBeenCalledWith({ mcpApps: true });
+ expect(mcpClientMocks).toHaveBeenCalledWith(expect.objectContaining({ mcpApps: true }));
// With the server the view may be read back from
expect((result.state as any).mcpApp).toEqual({
preferredModelDisplayMode: 'fullscreen',
@@ -114,7 +114,7 @@ describe('McpCtr MCP Apps', () => {
toolName: 'show_weather',
} as any);
- expect(mcpClientMocks).toHaveBeenCalledWith({ mcpApps: false });
+ expect(mcpClientMocks).toHaveBeenCalledWith(expect.objectContaining({ mcpApps: false }));
expect(client.getToolUiResourceUri).not.toHaveBeenCalled();
expect(client.getToolUiMeta).not.toHaveBeenCalled();
expect((result.state as any).mcpApp).toBeUndefined();
@@ -135,7 +135,7 @@ describe('McpCtr MCP Apps', () => {
await run(true);
await run(true);
- expect(mcpClientMocks.mock.calls).toEqual([[{ mcpApps: false }], [{ mcpApps: true }]]);
+ expect(mcpClientMocks.mock.calls.map(([options]) => options.mcpApps)).toEqual([false, true]);
});
it("returns a view the tool's own media, not the chat's uploaded copies", async () => {
diff --git a/apps/desktop/src/main/controllers/McpCtr.toolVisibility.test.ts b/apps/desktop/src/main/controllers/McpCtr.toolVisibility.test.ts
index ed9292b82cf..4c68433d703 100644
--- a/apps/desktop/src/main/controllers/McpCtr.toolVisibility.test.ts
+++ b/apps/desktop/src/main/controllers/McpCtr.toolVisibility.test.ts
@@ -7,7 +7,7 @@ import McpCtr from './McpCtr';
const { mcpClientMocks } = vi.hoisted(() => ({ mcpClientMocks: vi.fn() }));
-vi.mock('../libs/mcp/client', () => ({
+vi.mock('@lobechat/device-mcp/client', () => ({
MCPClient: class {
constructor(
public params: unknown,
@@ -81,7 +81,7 @@ describe('McpCtr tool visibility', () => {
// A server may list the tools only its views call just to such a client
await discover(ctr);
- expect(mcpClientMocks).toHaveBeenCalledWith({ mcpApps: true });
+ expect(mcpClientMocks).toHaveBeenCalledWith(expect.objectContaining({ mcpApps: true }));
});
it('keeps view-only tools out of the stdio manifest the model reads', async () => {
diff --git a/apps/desktop/src/main/controllers/McpCtr.ts b/apps/desktop/src/main/controllers/McpCtr.ts
index 4c44cfa7afe..f6b800b814f 100644
--- a/apps/desktop/src/main/controllers/McpCtr.ts
+++ b/apps/desktop/src/main/controllers/McpCtr.ts
@@ -1,18 +1,20 @@
-import { createHash, randomUUID } from 'node:crypto';
-import path from 'node:path';
-
import {
buildMcpToolMetadata,
getMcpAppEntrypoints,
- getMcpServerFingerprint,
getMcpToolVisibility,
- isMcpThreadEntrypoint,
isMcpToolVisibleTo,
- lacksUiResourceMeta,
partitionMcpToolsForViews,
resolveMcpUiToolMeta,
- withListingUiMeta,
} from '@lobechat/const/mcpApp';
+import {
+ DeviceMcpRuntime,
+ type McpCallOptions,
+ type MCPClientParams,
+ type McpSessionOptions,
+ type McpTool,
+ type McpToolOutput,
+ withStdioOutput,
+} from '@lobechat/device-mcp';
import {
deserializeMcpIpcPayload,
type McpIpcPayload,
@@ -20,29 +22,14 @@ import {
} from '@lobechat/utils/mcpIpcPayload';
import { getMcpServerDescription } from '@lobechat/utils/mcpServerDescription';
+import { getDesktopEnv } from '@/env';
import FileService from '@/services/fileSrv';
import { createLogger } from '@/utils/logger';
-import type { MCPClient } from '../libs/mcp/client';
-import {
- isDeadTransportError,
- isStaleSessionError,
- serializeMcpClientParams,
-} from '../libs/mcp/sessionGuards';
-import type {
- AudioContent,
- ImageContent,
- MCPClientParams,
- McpTool,
- ResourceContent,
- ToolCallContent,
- ToolCallResult,
-} from '../libs/mcp/types';
import { ControllerModule, IpcMethod } from './index';
import { checkDeployOption } from './mcpInstallCheck';
const logger = createLogger('controllers:McpCtr');
-const loadMcpClient = () => import('../libs/mcp/client');
/**
* Desktop-only copy of `@lobechat/types`'s `CheckMcpInstallResult`.
@@ -172,18 +159,6 @@ export interface ReadUiResourceInput {
type SuperJSONSerialized<T = unknown> = McpIpcPayload<T>;
-interface McpSessionOptions {
- /** Announce MCP Apps on the session: the user has the `mcp_apps` flag. */
- mcpApps?: boolean;
-}
-
-/** How a tool call runs: whether a view made it, and whether MCP Apps are on. */
-interface McpCallOptions extends McpSessionOptions {
- /** An MCP App view's `tools/call`: only tools visible to the app run. */
- fromApp?: boolean;
- fromEntrypoint?: boolean;
-}
-
/**
* A manifest's api is what the model may call: tools whose MCP Apps visibility
* leaves out "model" exist only for their view, which reaches them through
@@ -220,152 +195,35 @@ const deserializePayload = deserializeMcpIpcPayload;
const serializePayload = serializeMcpIpcPayload;
-const safeParseToRecord = (value: unknown): Record<string, unknown> => {
- if (value && typeof value === 'object' && !Array.isArray(value))
- return value as Record<string, unknown>;
- if (typeof value === 'string') {
- try {
- const parsed = JSON.parse(value) as unknown;
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
- return parsed as Record<string, unknown>;
- } catch {
- // ignore
- }
- }
- return {};
-};
-
-const MEDIA_UPLOAD_CONFIG = {
- audio: {
- defaultExtension: 'mp3',
- defaultMimeType: 'audio/mpeg',
- pathnameSegment: 'audios',
- },
- image: {
- defaultExtension: 'png',
- defaultMimeType: 'image/png',
- pathnameSegment: 'images',
- },
-} as const;
-
-type MediaContentType = keyof typeof MEDIA_UPLOAD_CONFIG;
-
-const PREFERRED_MIME_EXTENSIONS: Record<string, string> = {
- 'audio/mpeg': 'mp3',
- 'audio/mp3': 'mp3',
- 'image/svg+xml': 'svg',
-};
-
-const normalizeMimeType = (mimeType: string | undefined, mediaType: MediaContentType) => {
- const normalized = mimeType?.split(';')[0]?.trim().toLowerCase();
- return normalized || MEDIA_UPLOAD_CONFIG[mediaType].defaultMimeType;
-};
-
-const getMediaContentType = (mimeType: string | undefined): MediaContentType | undefined => {
- const normalized = mimeType?.split(';')[0]?.trim().toLowerCase();
- if (normalized?.startsWith('image/')) return 'image';
- if (normalized?.startsWith('audio/')) return 'audio';
-};
-
-const getFileExtensionFromMimeType = (mimeType: string, mediaType: MediaContentType) => {
- const [, subtype = ''] = mimeType.split('/');
- const sanitizedSubtype = subtype
- .split('+')[0]
- .replaceAll(/[^a-z0-9]/gi, '')
- .toLowerCase();
-
- return (
- PREFERRED_MIME_EXTENSIONS[mimeType] ||
- sanitizedSubtype ||
- MEDIA_UPLOAD_CONFIG[mediaType].defaultExtension
- );
-};
-
-const todayShard = () => new Date().toISOString().split('T')[0];
-
-const toMarkdown = async (
- blocks: ToolCallContent[] | null | undefined,
- getHTTPURL: (key: string) => Promise<string>,
-) => {
- if (!blocks) return '';
-
- const parts = await Promise.all(
- blocks.map(async (item) => {
- switch (item.type) {
- case 'text': {
- return item.text;
- }
- case 'image': {
- const url = await getHTTPURL(item.data);
- return `![](${url})`;
- }
- case 'audio': {
- const url = await getHTTPURL(item.data);
- return `<resource type="${item.type}" url="${url}" />`;
- }
- case 'resource': {
- return `<resource type="${item.type}">${JSON.stringify(item.resource)}</resource>`;
- }
- default: {
- return '';
- }
- }
- }),
- );
-
- return parts.filter(Boolean).join('\n\n');
-};
-
/**
* MCP Controller (Desktop Main Process)
* Implements the same routes as `src/server/routers/desktop/mcp.ts`, but via IPC.
+ *
+ * Sessions, tool execution and media handling live in the shared
+ * `@lobechat/device-mcp` runtime, which `lh connect` runs too, so a tunneled
+ * call behaves the same on either device host.
*/
export default class McpCtr extends ControllerModule {
static override readonly groupName = 'mcp';
- /**
- * Long-lived MCP client pool keyed by serialized connection params.
- *
- * Stateful stdio MCP servers (e.g. IDA's `ida-mcp`: `open_database` sets a
- * current database that later `execute_python` calls depend on) lose their
- * in-process state when the session is torn down between tool calls. The
- * cloud-side MCPService already caches clients; the desktop / device-tunnel
- * path used to spawn a fresh process per call and kill it right after
- * (`finally disconnect()`), silently dropping all server-side state. We now
- * reuse one session per unique connection params, and only rebuild it when
- * a call fails.
- */
- private mcpClientPool = new Map<string, MCPClient>();
- /** The pool key each client was created under, so eviction finds its own entry. */
- private mcpClientKeys = new WeakMap<MCPClient, string>();
- private mcpClientInitialization?: Map<string, Promise<MCPClient>>;
-
- /**
- * Idle-reap policy for the pool: sessions untouched for longer than this
- * are disconnected and dropped at the next acquire/dispose sweep.
- *
- * Rationale: stdio subprocesses are cheap to respawn but leak when kept
- * forever β€” a changed token/env/command produces a NEW cache key while the
- * old entry stays connected for the life of the desktop process, so a
- * long-running session could accumulate every obsolete client. The TTL is
- * deliberately long (30 min ≫ any realistic think-turn between tool calls)
- * so actively used stateful sessions are never reaped mid-workflow: every
- * acquire refreshes lastUsedAt.
- */
- private static readonly MCP_POOL_IDLE_TTL_MS = 30 * 60 * 1000;
-
- private mcpClientLastUsedAt = new Map<string, number>();
+ private runtimeInstance?: DeviceMcpRuntime;
- // In-flight call tracking: eviction and idle reaping are deferred while a
- // client holds any lease; release performs a pending eviction disconnect.
- private mcpClientLeases = new Map<MCPClient, number>();
- private mcpClientPendingDisconnect = new Set<MCPClient>();
+ private get runtime(): DeviceMcpRuntime {
+ this.runtimeInstance ??= new DeviceMcpRuntime({
+ clientName: 'lobehub-desktop-mcp-client',
+ getMediaUrl: (key) => this.fileService.getFileHTTPURL(key),
+ logger,
+ toolTimeoutMs: getDesktopEnv().MCP_TOOL_TIMEOUT,
+ uploadMedia: (media) => this.uploadMcpMedia(media),
+ });
+ return this.runtimeInstance;
+ }
/**
* App shutdown hook: disconnect every pooled stdio session so no MCP
* subprocess outlives the desktop process. Electron does not await
- * Promise-returning listeners: every disconnect is initiated
- * synchronously before the first await (never throws).
+ * Promise-returning listeners; the runtime initiates every disconnect
+ * synchronously before its first await.
*/
async beforeAppReady() {
const { app } = await import('electron');
@@ -375,220 +233,31 @@ export default class McpCtr extends ControllerModule {
}
private async disposeAllPooledClients(): Promise<void> {
- const entries = [...this.mcpClientPool.entries()];
- this.mcpClientPool.clear();
- this.mcpClientLastUsedAt.clear();
- const teardowns = entries.map(([, client]) =>
- client.disconnect().catch((error: unknown) => {
- logger.warn('Failed to disconnect MCP client on dispose:', error);
- }),
- );
- await Promise.all(teardowns);
+ await this.runtimeInstance?.dispose();
}
private get fileService() {
return this.app.getService(FileService);
}
- /**
- * Disconnect and drop every pooled session that has been idle for longer
- * than the TTL. Never throws.
- */
- private async reapIdleClients(): Promise<void> {
- const now = Date.now();
- for (const [key, client] of this.mcpClientPool) {
- const lastUsed = this.mcpClientLastUsedAt.get(key) ?? 0;
- if (now - lastUsed < McpCtr.MCP_POOL_IDLE_TTL_MS) continue;
- // A session with active in-flight calls is still working: disconnecting
- // it mid-call would kill a valid long-running tool invocation (the
- // idle clock only refreshes at acquisition, not during the call).
- if (this.mcpClientLeases.has(client)) continue;
- this.mcpClientPool.delete(key);
- this.mcpClientLastUsedAt.delete(key);
- try {
- await client.disconnect();
- } catch (error) {
- logger.warn('Failed to reap idle MCP client:', error);
- }
- }
- }
-
- /**
- * Return a pooled client for the given params, creating (and caching) a new
- * one when the pool has no healthy entry. Callers must NOT disconnect the
- * returned client β€” pooled sessions outlive a single tool call.
- */
- private async acquireClient(
- params: MCPClientParams,
- { mcpApps = false }: McpSessionOptions = {},
- ): Promise<MCPClient> {
- // Sessions that announce MCP Apps and ones that don't are pooled apart
- const key = `${serializeMcpClientParams(params)}${mcpApps ? '#mcp-apps' : ''}`;
-
- // Every acquire refreshes the session's idle clock (fire-and-forget β€”
- // reaping must never delay or fail the tool call it runs alongside).
- this.mcpClientLastUsedAt.set(key, Date.now());
- void this.reapIdleClients().catch(() => {});
-
- const cached = this.mcpClientPool.get(key);
- if (cached) return cached;
-
- // Single-flight per key: concurrent manifest discovery + tool call on the
- // same uncached params must share one initialization, not spawn two
- // processes where the later map write silently replaces the first
- // (stranding whatever state the losing client had established).
- const inFlight = this.mcpClientInitialization?.get(key);
- if (inFlight) return inFlight;
-
- const creating = this.createClient(params, { mcpApps })
- .then((client) => {
- this.mcpClientKeys.set(client, key);
- this.mcpClientPool.set(key, client);
- this.mcpClientLastUsedAt.set(key, Date.now());
- return client;
- })
- .catch((error) => {
- // The acquire-time clock is an orphan when creation fails: failed
- // configs (serialized keys contain env values) must not accumulate.
- this.mcpClientLastUsedAt.delete(key);
- throw error;
- })
- .finally(() => {
- this.mcpClientInitialization?.delete(key);
- });
- (this.mcpClientInitialization ??= new Map()).set(key, creating);
- return creating;
- }
-
- /**
- * Run `fn` while holding a lease: eviction and idle reaping are deferred
- * while any lease is active. The last release refreshes the idle clock
- * (a call may outlast the TTL β€” the session is fresh the moment its work
- * ends, not when it started) and then performs any pending disconnect.
- */
- private async withClientLease<T>(client: MCPClient, fn: () => Promise<T>): Promise<T> {
- this.mcpClientLeases.set(client, (this.mcpClientLeases.get(client) ?? 0) + 1);
- try {
- return await fn();
- } finally {
- const remaining = (this.mcpClientLeases.get(client) ?? 1) - 1;
- if (remaining > 0) this.mcpClientLeases.set(client, remaining);
- else {
- this.mcpClientLeases.delete(client);
- // The idle clock must reflect when the LAST lease ended, not when
- // the call started: an invocation longer than the TTL would
- // otherwise release an already-expired timestamp and an unrelated
- // same-key sweep would disconnect this just-used session.
- for (const [key, pooled] of this.mcpClientPool) {
- if (pooled === client) this.mcpClientLastUsedAt.set(key, Date.now());
- }
- if (this.mcpClientPendingDisconnect.delete(client)) {
- try {
- await client.disconnect();
- } catch (error) {
- logger.warn('Failed to disconnect evicted MCP client:', error);
- }
- }
- }
- }
- }
-
- /**
- * Drop a pooled session after a failed call so the next attempt starts
- * fresh. Never throws β€” the original call error matters more than cleanup.
- *
- * Requires the exact client the failed call ran on: without that identity
- * we must not disconnect anything, or a concurrent same-key recreate (call
- * B installing its replacement while call A's initialization fails) would
- * get its live session killed while the pool keeps pointing at it β€” a
- * permanently dead pooled entry until restart.
- */
- private async evictClient(params: MCPClientParams, client?: MCPClient): Promise<void> {
- if (!client) return;
- const key = this.mcpClientKeys.get(client) ?? serializeMcpClientParams(params);
- const pooled = this.mcpClientPool.get(key);
- // Only evict when the failing call ran on the pooled instance β€”
- // a concurrent recreate may have already replaced it.
- if (pooled && pooled === client) {
- this.mcpClientPool.delete(key);
- this.mcpClientLastUsedAt.delete(key);
- }
- // Defer the disconnect while the client still has in-flight calls:
- // manifest discovery and tool execution share one pooled session, so an
- // eviction triggered by one of them must not abort the other mid-call.
- // The last lease release performs the deferred disconnect.
- if (this.mcpClientLeases.has(client)) {
- this.mcpClientPendingDisconnect.add(client);
- return;
- }
- try {
- await client.disconnect();
- } catch (error) {
- logger.warn('Failed to disconnect evicted MCP client:', error);
- }
- }
-
- private async createClient(params: MCPClientParams, options: McpSessionOptions = {}) {
- const { MCPClient } = await loadMcpClient();
- const client = new MCPClient(params, options);
- await client.initialize();
- return client;
- }
-
- private async uploadMcpMediaBlock(base64: string, mediaType: MediaContentType, mimeType: string) {
- const config = MEDIA_UPLOAD_CONFIG[mediaType];
- const ext = getFileExtensionFromMimeType(mimeType, mediaType);
- const buffer = Buffer.from(base64, 'base64');
- const hash = createHash('sha256').update(buffer).digest('hex');
- const id = randomUUID();
- const filename = `${id}.${ext}`;
- const filePath = path.posix.join('mcp', config.pathnameSegment, todayShard(), filename);
-
+ private async uploadMcpMedia({
+ base64,
+ filename,
+ hash,
+ mimeType,
+ path,
+ }: Parameters<ConstructorParameters<typeof DeviceMcpRuntime>[0]['uploadMedia']>[0]) {
const { metadata } = await this.fileService.uploadFile({
content: base64,
filename,
hash,
- path: filePath,
+ path,
type: mimeType,
});
return metadata.path;
}
- private async processContentBlocks(blocks: ToolCallContent[]): Promise<ToolCallContent[]> {
- return Promise.all(
- blocks.map(async (block) => {
- if (block.type === 'image' || block.type === 'audio') {
- const mediaType = block.type;
- const mimeType = normalizeMimeType(block.mimeType, mediaType);
- const data = await this.uploadMcpMediaBlock(block.data, mediaType, mimeType);
-
- return { ...block, data, mimeType };
- }
-
- if (block.type === 'resource') {
- const resourceBlock = block as ResourceContent;
- const resource = resourceBlock.resource;
- const mediaType = getMediaContentType(resource?.mimeType);
-
- if (!resource?.blob || !mediaType) return block;
-
- const mimeType = normalizeMimeType(resource.mimeType, mediaType);
- const data = await this.uploadMcpMediaBlock(resource.blob, mediaType, mimeType);
- const metadata = resourceBlock._meta ? { _meta: resourceBlock._meta } : {};
-
- if (mediaType === 'image') {
- return { ...metadata, data, mimeType, type: 'image' } as ImageContent;
- }
-
- return { ...metadata, data, mimeType, type: 'audio' } as AudioContent;
- }
-
- return block;
- }),
- );
- }
-
@IpcMethod()
async getStdioMcpServerManifest(payload: SuperJSONSerialized<GetStdioMcpServerManifestInput>) {
const input = deserializePayload<GetStdioMcpServerManifestInput>(payload);
@@ -600,12 +269,13 @@ export default class McpCtr extends ControllerModule {
type: 'stdio',
};
- let client: MCPClient | undefined;
+ let client: Awaited<ReturnType<DeviceMcpRuntime['acquireClient']>> | undefined;
try {
- client = await this.acquireClient(params, { mcpApps: input.mcpApps });
+ client = await this.runtime.acquireClient(params, { mcpApps: input.mcpApps });
+ const pooled = client;
// Lease for the manifest refresh too: a concurrent stale-session
// eviction must not disconnect underneath this pending request.
- const manifest = await this.withClientLease(client, () => client!.listManifests());
+ const manifest = await this.runtime.withClientLease(pooled, () => pooled.listManifests());
const identifier = input.name;
const api = toModelApi(manifest.tools || [], input.mcpApps);
@@ -630,24 +300,11 @@ export default class McpCtr extends ControllerModule {
// evict it so the next refresh starts fresh instead of reacquiring
// the same dead session forever. Identity-guarded: a concurrent
// recreate must not be disconnected.
- await this.evictClient(params, client);
- // If it's an MCPConnectionError with stderr logs, enhance the error message
- const { MCPConnectionError } = await loadMcpClient();
- if (error instanceof MCPConnectionError && error.stderrLogs.length > 0) {
- const stderrOutput = error.stderrLogs.join('\n');
- const enhancedError = new Error(
- `${error.message}\n\n--- STDIO Process Output ---\n${stderrOutput}`,
- );
- enhancedError.name = error.name;
- logger.error('getStdioMcpServerManifest failed with STDIO logs:', {
- message: error.message,
- stderrLogs: error.stderrLogs,
- });
- throw enhancedError;
- }
- throw error;
- } finally {
- // Manifest listing shares the pooled session; nothing to clean up here.
+ await this.runtime.evictClient(params, client);
+ const enhanced = await withStdioOutput(error);
+ if (enhanced !== error)
+ logger.error('getStdioMcpServerManifest failed with STDIO logs:', enhanced);
+ throw enhanced;
}
}
@@ -664,7 +321,7 @@ export default class McpCtr extends ControllerModule {
url: input.url,
};
- const client = await this.createClient(params, { mcpApps: input.mcpApps });
+ const client = await this.runtime.createClient(params, { mcpApps: input.mcpApps });
try {
const tools = await client.listTools();
const api = toModelApi(tools, input.mcpApps);
@@ -712,35 +369,18 @@ export default class McpCtr extends ControllerModule {
}),
}));
- if (input.http) {
- const client = await this.createClient(
- { ...input.http, type: 'http' },
- { mcpApps: input.mcpApps },
- );
- try {
- return serializePayload(toListed(await client.listTools()));
- } finally {
- await client.disconnect();
- }
- }
-
- const params: MCPClientParams = {
- args: input.stdio.args || [],
- command: input.stdio.command,
- env: input.stdio.env,
- name: input.stdio.name,
- type: 'stdio',
- };
- let client: MCPClient | undefined;
- try {
- client = await this.acquireClient(params, { mcpApps: input.mcpApps });
- const tools = await this.withClientLease(client, () => client!.listTools());
- return serializePayload(toListed(tools));
- } catch (error) {
- // Same as the manifest refresh: drop a broken pooled session.
- await this.evictClient(params, client);
- throw error;
- }
+ const params: MCPClientParams = input.http
+ ? { ...input.http, type: 'http' }
+ : {
+ args: input.stdio.args || [],
+ command: input.stdio.command,
+ env: input.stdio.env,
+ name: input.stdio.name,
+ type: 'stdio',
+ };
+ return serializePayload(
+ toListed(await this.runtime.listTools(params, { mcpApps: input.mcpApps })),
+ );
}
@IpcMethod()
@@ -758,6 +398,13 @@ export default class McpCtr extends ControllerModule {
return serializePayload(await this.runStdioMcpTool(input as StdioCallToolInput));
}
+ /**
+ * Read an MCP Apps `ui://` resource from a stdio or local-network HTTP
+ * server, so the chat can render a tool result's interactive view.
+ *
+ * Unlike the web routes, not gated by the `mcp_apps` flag: the main process
+ * has no per-user flags, and the renderer only asks while the flag is on.
+ */
/**
* Read an MCP Apps `ui://` resource from a stdio or local-network HTTP
* server, so the chat can render a tool result's interactive view.
@@ -785,84 +432,7 @@ export default class McpCtr extends ControllerModule {
throw new Error('Missing MCP server params');
}
- const read = (client: MCPClient) =>
- this.withClientLease(client, async () => {
- const result = await client.readResource(input.uri);
- // A view's _meta.ui may be declared once, on its resources/list entry
- if (!lacksUiResourceMeta(result, true)) return result;
-
- const listed = await client.listResources().catch((error) => {
- logger.warn('Failed to list resources for MCP App metadata:', { error });
- return [];
- });
- return withListingUiMeta(result, input.uri, listed, true);
- });
- // Reading is idempotent, so unlike tool calls a dead transport is retried
- // too: the stale session is evicted and the read runs once on a fresh one.
- const isSessionFailure = (error: unknown) =>
- isStaleSessionError(error) || isDeadTransportError(error);
-
- // Views are read only while MCP Apps are on, on a session that announces them
- const client = await this.acquireClient(params, { mcpApps: true });
- try {
- return serializePayload(await read(client));
- } catch (error) {
- if (!isSessionFailure(error)) throw error;
-
- logger.warn('MCP App resource read failed on pooled session, retrying with a fresh one:', {
- message: (error as Error).message,
- });
- await this.evictClient(params, client);
- const retryClient = await this.acquireClient(params, { mcpApps: true });
- try {
- return serializePayload(await read(retryClient));
- } catch (retryError) {
- if (isSessionFailure(retryError)) await this.evictClient(params, retryClient);
- throw retryError;
- }
- }
- }
-
- /** Fails closed: a view's call is refused while the tool's visibility can't be learned. */
- private async isToolCallableByApp(client: MCPClient, toolName: string) {
- try {
- return await client.isToolCallableByApp(toolName);
- } catch (error) {
- // A broken session is the call's own failure: let runMcpTool evict and
- // recover it, or every later view call would reuse the dead session
- if (isStaleSessionError(error, client.getProtocolEra()) || isDeadTransportError(error)) {
- throw error;
- }
- logger.warn('Failed to resolve MCP App visibility for tool:', { error, toolName });
- return false;
- }
- }
-
- /**
- * Fails open: while the tool's visibility can't be learned, the model's call
- * runs as it did before MCP Apps.
- */
- private async isToolHiddenFromModel(client: MCPClient, toolName: string) {
- try {
- return await client.isToolHiddenFromModel(toolName);
- } catch (error) {
- // A broken session is the call's own failure, recovered by runMcpTool
- if (isStaleSessionError(error, client.getProtocolEra()) || isDeadTransportError(error)) {
- throw error;
- }
- logger.warn('Failed to resolve MCP App visibility for tool:', { error, toolName });
- return false;
- }
- }
-
- /** Never fails the tool call: an unknown UI resource only means no interactive view. */
- private async getToolUiResourceUri(client: MCPClient, toolName: string) {
- try {
- return await client.getToolUiResourceUri(toolName);
- } catch (error) {
- logger.warn('Failed to resolve MCP App resource for tool:', { error, toolName });
- return undefined;
- }
+ return serializePayload(await this.runtime.readUiResource(params, input.uri));
}
/**
@@ -872,10 +442,8 @@ export default class McpCtr extends ControllerModule {
* result envelope; callers serialize as needed. Throws on failure so each
* caller can shape its own error response.
*/
- async runStdioMcpTool(
- input: StdioCallToolInput,
- ): Promise<{ content: string; state: unknown; success: boolean }> {
- return this.runMcpTool(
+ async runStdioMcpTool(input: StdioCallToolInput): Promise<McpToolOutput> {
+ return this.runtime.runTool(
{
args: input.params.args || [],
command: input.params.command,
@@ -904,202 +472,15 @@ export default class McpCtr extends ControllerModule {
toolName: string,
rawArgs: unknown,
options: McpCallOptions = {},
- ): Promise<{ content: string; state: unknown; success: boolean }> {
- return this.runMcpTool(
- {
- auth: input.auth,
- headers: input.headers,
- name: input.name,
- type: 'http',
- url: input.url,
- },
+ ): Promise<McpToolOutput> {
+ return this.runtime.runTool(
+ { auth: input.auth, headers: input.headers, name: input.name, type: 'http', url: input.url },
toolName,
rawArgs,
options,
);
}
- private async runMcpTool(
- params: MCPClientParams,
- toolName: string,
- rawArgs: unknown,
- { fromApp = false, fromEntrypoint = false, mcpApps = false }: McpCallOptions = {},
- ): Promise<{ content: string; state: unknown; success: boolean }> {
- try {
- const args = fromEntrypoint ? {} : safeParseToRecord(rawArgs);
-
- // Reuse the pooled session (stateful stdio servers keep per-process
- // state such as a selected database). Retry once on a fresh session β€”
- // but only for confirmed stale-session / transport failures that
- // happen before a tool result was produced. App-level failures (tool
- // rejected the args, media post-processing failed, …) are surfaced
- // as-is: re-running a mutating tool on a generic catch could apply
- // its side effect a second time. The failing client is tagged onto
- // the error so eviction carries an identity guard.
- const runOn = (client: MCPClient) =>
- this.withClientLease(client, async () => {
- try {
- if (
- fromEntrypoint &&
- !(mcpApps && isMcpThreadEntrypoint(await client.getToolUiMeta(toolName)))
- ) {
- const message = 'This tool does not declare an enabled thread entrypoint.';
- return {
- content: message,
- state: { content: [{ text: message, type: 'text' }], isError: true },
- success: false,
- };
- }
- // A view may only call tools whose visibility includes the app,
- // and only while MCP Apps are on
- if (
- !fromEntrypoint &&
- fromApp &&
- !(mcpApps && (await this.isToolCallableByApp(client, toolName)))
- ) {
- const message = `The tool "${toolName}" can't be called from an interactive view.`;
- return {
- content: message,
- error: { message, name: 'MCPToolError' },
- state: { content: [{ text: message, type: 'text' }], isError: true },
- success: false,
- };
- }
- // A tool the server keeps from the model is its views' alone, even
- // when the model names it (e.g. from an earlier turn)
- if (
- !fromEntrypoint &&
- !fromApp &&
- mcpApps &&
- (await this.isToolHiddenFromModel(client, toolName))
- ) {
- const message = `The tool "${toolName}" can only be called from its interactive view.`;
- return {
- content: message,
- error: { message, name: 'MCPToolError' },
- state: { content: [{ text: message, type: 'text' }], isError: true },
- success: false,
- };
- }
- const uiResourceUri = mcpApps
- ? await this.getToolUiResourceUri(client, toolName)
- : undefined;
- const preferredModelDisplayMode = uiResourceUri
- ? (await client.getToolUiMeta(toolName))?.preferredModelDisplayMode
- : undefined;
- const raw = (await client.callTool(toolName, args)) as ToolCallResult;
- // A view gets the tool's own MCP result: its media stays base64
- // `data`, not the uploaded keys the chat stores and renders
- const processed =
- raw.isError || fromApp || fromEntrypoint
- ? raw.content
- : await this.processContentBlocks(raw.content);
- const content =
- fromApp || fromEntrypoint
- ? processed
- .flatMap((block) => (block.type === 'text' ? [block.text] : []))
- .join('\n')
- : await toMarkdown(processed, (key) => this.fileService.getFileHTTPURL(key));
- const state = {
- ...raw,
- content: processed,
- // MCP Apps: the `ui://` resource the chat renders this result with,
- // and the server it may be read back from
- ...(uiResourceUri &&
- !raw.isError && {
- mcpApp: {
- resourceUri: uiResourceUri,
- ...(preferredModelDisplayMode && { preferredModelDisplayMode }),
- server: await getMcpServerFingerprint(params),
- },
- }),
- };
- return {
- content,
- ...(raw.isError ? { error: { message: content, name: 'MCPToolError' } } : {}),
- state,
- success: raw.isError !== true,
- };
- } catch (error) {
- throw Object.assign(error instanceof Error ? error : new Error(String(error)), {
- ranOnClient: client,
- });
- }
- });
-
- try {
- return await runOn(await this.acquireClient(params, { mcpApps }));
- } catch (firstError) {
- const failedClient = (firstError as { ranOnClient?: MCPClient })?.ranOnClient;
- if (!isStaleSessionError(firstError, failedClient?.getProtocolEra())) {
- // A dead stdio subprocess must still be evicted even though the
- // failed call is NOT replayed: the request may have reached the
- // server before the pipe died, so re-running a mutating tool
- // could apply its side effect twice. Without eviction the dead
- // client stays pooled and every later same-key acquisition
- // refreshes and returns the same unusable session until restart.
- if (isDeadTransportError(firstError)) {
- logger.warn('MCP tool call failed on a dead transport, evicting pooled session:', {
- message: (firstError as Error).message,
- toolName,
- });
- await this.evictClient(params, failedClient);
- } else {
- logger.warn('MCP tool call failed (no retry for app-level error):', {
- message: (firstError as Error).message,
- toolName,
- });
- }
- throw firstError;
- }
- logger.warn('MCP tool call failed on pooled session, retrying with a fresh one:', {
- message: (firstError as Error).message,
- toolName,
- });
- await this.evictClient(params, failedClient);
- // Route replacement creation through acquireClient: it single-flights
- // per key, so two concurrent calls that shared the same stale client
- // and both failed build ONE replacement process β€” not two racing
- // create/set writes that strand the loser (and its established state).
- const retryClient = await this.acquireClient(params, { mcpApps });
- try {
- return await runOn(retryClient);
- } catch (retryError) {
- // Evict the replacement on a transport-level failure β€” stale
- // errors authorize a further retry, dead transports prove the
- // replacement dead: neither is handed to the next call. A
- // post-processing failure after a SUCCESSFUL tool call is not a
- // session problem β€” the tool already ran, so the healthy
- // replacement stays pooled.
- if (
- isStaleSessionError(retryError, retryClient.getProtocolEra()) ||
- isDeadTransportError(retryError)
- ) {
- await this.evictClient(params, retryClient);
- }
- throw retryError;
- }
- }
- } catch (error) {
- // If it's an MCPConnectionError with stderr logs, enhance the error message
- const { MCPConnectionError } = await loadMcpClient();
- if (error instanceof MCPConnectionError && error.stderrLogs.length > 0) {
- const stderrOutput = error.stderrLogs.join('\n');
- const enhancedError = new Error(
- `${error.message}\n\n--- STDIO Process Output ---\n${stderrOutput}`,
- );
- enhancedError.name = error.name;
- logger.error('callTool failed with STDIO logs:', {
- message: error.message,
- stderrLogs: error.stderrLogs,
- });
- throw enhancedError;
- }
- logger.error('callTool failed:', error);
- throw error;
- }
- }
-
@IpcMethod()
async validMcpServerInstallable(
payload: SuperJSONSerialized<{
diff --git a/apps/desktop/src/main/controllers/__tests__/McpCtr.manifest.test.ts b/apps/desktop/src/main/controllers/__tests__/McpCtr.manifest.test.ts
new file mode 100644
index 00000000000..1cdd698c396
--- /dev/null
+++ b/apps/desktop/src/main/controllers/__tests__/McpCtr.manifest.test.ts
@@ -0,0 +1,173 @@
+import { deserializeMcpIpcPayload, serializeMcpIpcPayload } from '@lobechat/utils/mcpIpcPayload';
+import { SdkError, SdkErrorCode } from '@modelcontextprotocol/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { App } from '@/core/App';
+
+import McpCtr from '../McpCtr';
+
+const { mcpClientMocks } = vi.hoisted(() => ({
+ mcpClientMocks: vi.fn(),
+}));
+
+// The shared device MCP runtime lazily imports its client module; mock it so
+// no real stdio process is ever spawned.
+vi.mock('@lobechat/device-mcp/client', () => ({
+ MCPClient: class {
+ constructor(public params: unknown) {
+ return mcpClientMocks();
+ }
+ },
+ MCPConnectionError: class extends Error {
+ name = 'MCPConnectionError';
+ stderrLogs: string[] = [];
+ },
+}));
+
+const mockApp = {
+ getService: vi.fn(() => null),
+} as unknown as App;
+
+const makeClientInstance = (label: string) => ({
+ callTool: vi.fn().mockImplementation(async () => ({
+ content: [{ text: `${label}-result`, type: 'text' }],
+ isError: false,
+ })),
+ disconnect: vi.fn().mockResolvedValue(undefined),
+ getProtocolEra: vi.fn().mockReturnValue('legacy'),
+ initialize: vi.fn().mockResolvedValue(undefined),
+ listManifests: vi.fn().mockResolvedValue({ tools: [] }),
+});
+
+describe('McpCtr manifests', () => {
+ let ctr: McpCtr;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.resetAllMocks();
+ mcpClientMocks.mockReset();
+ ctr = new McpCtr(mockApp);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it.each(['My server description'])(
+ 'keeps stdio descriptions as metadata (%s)',
+ async (description) => {
+ const instance = {
+ ...makeClientInstance('tools-only'),
+ listManifests: vi.fn().mockResolvedValue({
+ prompts: undefined,
+ resources: undefined,
+ tools: [{ inputSchema: { type: 'object' }, name: 'hello' }],
+ }),
+ };
+ mcpClientMocks.mockReturnValue(instance);
+
+ const result = await ctr.getStdioMcpServerManifest(
+ serializeMcpIpcPayload({
+ command: 'test-command',
+ metadata: { description },
+ name: 'tools-only',
+ }),
+ );
+ const manifest = deserializeMcpIpcPayload<{ api: unknown[]; meta: { description?: string } }>(
+ result,
+ );
+
+ expect(manifest.api).toHaveLength(1);
+ expect(manifest.meta.description).toBe(description);
+ },
+ );
+
+ it.each(['My server description'])(
+ 'keeps HTTP descriptions as metadata (%s)',
+ async (description) => {
+ const instance = { ...makeClientInstance('http'), listTools: vi.fn().mockResolvedValue([]) };
+ mcpClientMocks.mockReturnValue(instance);
+
+ const result = await ctr.getStreamableMcpServerManifest(
+ serializeMcpIpcPayload({
+ identifier: 'empty-server',
+ metadata: { description },
+ url: 'http://localhost/mcp',
+ }),
+ );
+ const manifest = deserializeMcpIpcPayload<{ api: unknown[]; meta: { description?: string } }>(
+ result,
+ );
+
+ expect(manifest.api).toEqual([]);
+ expect(manifest.meta.description).toBe(description);
+ },
+ );
+
+ it.each([
+ {
+ capabilities: { tools: [{ name: 'hello' }] },
+ summary: '1 tool',
+ },
+ {
+ capabilities: { prompts: [], resources: [], tools: [] },
+ summary: 'no tools, prompts, or resources',
+ },
+ {
+ capabilities: {
+ prompts: [{ name: 'greet' }],
+ resources: [{ name: 'readme' }],
+ tools: [{ name: 'hello' }],
+ },
+ summary: '1 prompt, 1 resource, 1 tool',
+ },
+ ])('persists the automatic stdio description: $summary', async ({ capabilities, summary }) => {
+ const instance = makeClientInstance('automatic');
+ instance.listManifests.mockResolvedValue(capabilities);
+ mcpClientMocks.mockReturnValue(instance);
+
+ const result = await ctr.getStdioMcpServerManifest(
+ serializeMcpIpcPayload({ command: 'test-command', name: 'automatic' }),
+ );
+ const manifest = deserializeMcpIpcPayload<{ meta: { description: string } }>(result);
+
+ expect(manifest.meta.description).toBe(`automatic MCP server has ${summary}`);
+ expect(manifest.meta.description).not.toContain('undefined');
+ });
+
+ it.each([
+ { tools: [], summary: 'no tools, prompts, or resources' },
+ { tools: [{ name: 'hello' }], summary: '1 tool, like "hello"' },
+ ])('persists the automatic HTTP description: $summary', async ({ tools, summary }) => {
+ mcpClientMocks.mockReturnValue({
+ ...makeClientInstance('automatic'),
+ listTools: vi.fn().mockResolvedValue(tools),
+ });
+ const result = await ctr.getStreamableMcpServerManifest(
+ serializeMcpIpcPayload({ identifier: 'automatic', url: 'http://localhost/mcp' }),
+ );
+ const manifest = deserializeMcpIpcPayload<{ meta: { description: string } }>(result);
+
+ expect(manifest.meta.description).toBe(`automatic MCP server has ${summary}`);
+ expect(manifest.meta.description).not.toContain('undefined');
+ });
+
+ it('evicts the pooled client when listManifests fails on a stale session', async () => {
+ const seeded = makeClientInstance('seeded');
+ seeded.listManifests.mockRejectedValue(
+ new SdkError(SdkErrorCode.ConnectionClosed, 'Connection closed'),
+ );
+ mcpClientMocks.mockReturnValue(seeded);
+
+ await expect(
+ ctr.getStdioMcpServerManifest({
+ args: ['--stdio'],
+ command: 'ida-mcp',
+ name: 'ida-mcp',
+ } as any),
+ ).rejects.toThrow('Connection closed');
+
+ // Broken session evicted + disconnected, so the next refresh starts fresh.
+ expect(seeded.disconnect).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/server/src/services/connector/exec.test.ts b/apps/server/src/services/connector/exec.test.ts
index 49a2503a398..037ce53fd05 100644
--- a/apps/server/src/services/connector/exec.test.ts
+++ b/apps/server/src/services/connector/exec.test.ts
@@ -343,9 +343,10 @@ describe('callConnectorToolById', () => {
};
const ctx = makeCtx([stdioConnector], [tool()]);
- await expect(
- callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx),
- ).rejects.toHaveProperty('code', 'BAD_REQUEST');
+ const call = callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx);
+ await expect(call).rejects.toHaveProperty('code', 'BAD_REQUEST');
+ // Either device client runs it: the desktop app or `lh connect`.
+ await expect(call).rejects.toThrow('the desktop app or `lh connect`');
expect(mcpService.callTool).not.toHaveBeenCalled();
},
);
diff --git a/apps/server/src/services/connector/exec.ts b/apps/server/src/services/connector/exec.ts
index da49636d551..d9d1f596029 100644
--- a/apps/server/src/services/connector/exec.ts
+++ b/apps/server/src/services/connector/exec.ts
@@ -235,7 +235,7 @@ export const callConnectorToolById = async (
// Background tool-list refresh is best-effort β€” never fail the tool call.
}
- // Stdio runs on a desktop device, never in the server process. Private HTTP
+ // 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 =
@@ -247,7 +247,7 @@ export const callConnectorToolById = async (
throw new ConnectorToolCallError(
'BAD_REQUEST',
`Connector '${connector.name}' points at an MCP endpoint that only your machine can reach (stdio or local network). ` +
- 'Run these tools in the desktop app through a configured device gateway.',
+ 'It runs only on your own device β€” the desktop app or `lh connect` β€” through a configured device gateway.',
);
}
diff --git a/apps/server/src/services/deviceGateway/__tests__/deviceChannels.test.ts b/apps/server/src/services/deviceGateway/__tests__/deviceChannels.test.ts
index 27b6022a1e4..002a9606e0d 100644
--- a/apps/server/src/services/deviceGateway/__tests__/deviceChannels.test.ts
+++ b/apps/server/src/services/deviceGateway/__tests__/deviceChannels.test.ts
@@ -1,13 +1,15 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const queryDeviceListMock = vi.fn();
+const readDeviceSystemInfoMock = vi.fn();
vi.mock('../index', () => ({
deviceGateway: {
queryDeviceList: (...args: unknown[]) => queryDeviceListMock(...args),
+ readDeviceSystemInfo: (...args: unknown[]) => readDeviceSystemInfoMock(...args),
},
}));
-const { resolveDeviceClientKind } = await import('../deviceChannels');
+const { resolveDeviceClientKind, resolveMcpClientKinds } = await import('../deviceChannels');
const withChannels = (...channels: string[]) => [
{ channels: channels.map((channel) => ({ channel })), deviceId: 'device-1' },
@@ -42,3 +44,46 @@ describe('resolveDeviceClientKind', () => {
await expect(resolveDeviceClientKind('user-1', 'device-1')).resolves.toBe('unknown');
});
});
+
+describe('resolveMcpClientKinds', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('pins the call to the desktop app whenever it is connected, without asking the CLI', async () => {
+ queryDeviceListMock.mockResolvedValueOnce(withChannels('cli', 'desktop'));
+ await expect(resolveMcpClientKinds('user-1', 'device-1')).resolves.toEqual(['desktop']);
+ await expect(
+ resolveMcpClientKinds('user-1', 'device-1', undefined, 'unknown'),
+ ).resolves.toEqual(['desktop']);
+ expect(readDeviceSystemInfoMock).not.toHaveBeenCalled();
+ });
+
+ it('routes to lh connect when that CLI says it runs MCP calls', async () => {
+ queryDeviceListMock.mockResolvedValueOnce(withChannels('cli'));
+ readDeviceSystemInfoMock.mockResolvedValueOnce({
+ ok: true,
+ systemInfo: { supportedToolCallTypes: ['tool', 'mcp'] },
+ });
+
+ await expect(resolveMcpClientKinds('user-1', 'device-1', 'ws-1')).resolves.toEqual(['cli']);
+ expect(readDeviceSystemInfoMock).toHaveBeenCalledWith('user-1', 'device-1', 'ws-1', {
+ clientKinds: ['cli'],
+ });
+ });
+
+ it('refuses a CLI that predates MCP support, or that did not answer', async () => {
+ readDeviceSystemInfoMock.mockResolvedValueOnce({
+ ok: true,
+ systemInfo: { supportedTools: [] },
+ });
+ await expect(
+ resolveMcpClientKinds('user-1', 'device-1', undefined, 'cli-only'),
+ ).resolves.toBeUndefined();
+
+ readDeviceSystemInfoMock.mockResolvedValueOnce({ ok: false, reason: 'TIMEOUT' });
+ await expect(
+ resolveMcpClientKinds('user-1', 'device-1', undefined, 'cli-only'),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/deviceGateway/agents.ts b/apps/server/src/services/deviceGateway/agents.ts
index 4f1f5e31890..b7ec2e4a0b2 100644
--- a/apps/server/src/services/deviceGateway/agents.ts
+++ b/apps/server/src/services/deviceGateway/agents.ts
@@ -259,6 +259,8 @@ export async function executeMcpCall(
mcpCall: {
apiName: string;
arguments: string;
+ /** Which of the device's clients runs the call (see `resolveMcpClientKinds`). */
+ clientKinds?: DeviceClient[];
deviceId: string;
identifier: string;
params: GatewayMcpParams;
diff --git a/apps/server/src/services/deviceGateway/clientKinds.ts b/apps/server/src/services/deviceGateway/clientKinds.ts
index 6b847034a24..e91e30e7e07 100644
--- a/apps/server/src/services/deviceGateway/clientKinds.ts
+++ b/apps/server/src/services/deviceGateway/clientKinds.ts
@@ -10,8 +10,10 @@ const DESKTOP_ONLY: DeviceClient[] = ['desktop'];
* capability is declared rather than listed here:
*
* - builtin device tools β†’ the manifest's `deviceClients`
- * - MCP calls β†’ desktop only (`lh connect` has no MCP client and would
- * dispatch the call by `apiName` to a same-named local tool)
+ * - MCP calls β†’ the client `resolveMcpClientKinds` picked for the device,
+ * passed explicitly by the tunnel. Desktop only when a caller passes none:
+ * that is the one client known to run them without reading the device's
+ * system info (an older `lh connect` dispatches them by `apiName`)
* - message API β†’ desktop only (only the desktop app implements a messenger)
* - RPC β†’ `deviceRpcClients` in `@lobechat/device-control`
*
diff --git a/apps/server/src/services/deviceGateway/deviceChannels.ts b/apps/server/src/services/deviceGateway/deviceChannels.ts
index a4a8911454a..329e92036e1 100644
--- a/apps/server/src/services/deviceGateway/deviceChannels.ts
+++ b/apps/server/src/services/deviceGateway/deviceChannels.ts
@@ -1,3 +1,4 @@
+import type { DeviceClient } from '@lobechat/types';
import debug from 'debug';
import { deviceGateway } from './index';
@@ -13,7 +14,8 @@ const DESKTOP_CHANNELS = new Set(['desktop', 'desktop-dev']);
* prefers the CLI channel and tool calls carry no channel hint, so a
* desktop-only call may still land on the CLI
* - `cli-only` β€” only `lh connect` is connected; it handles local-system
- * file/shell calls and answers anything else with `Unknown tool API`
+ * file/shell calls, plus whatever its system info opts into (browser,
+ * MCP tunnel)
* - `unknown` β€” the device is not in the live list or reports no channel
* labels (older gateway); callers keep their previous behaviour
*/
@@ -27,6 +29,16 @@ export type DeviceClientKind = 'cli-only' | 'desktop' | 'mixed' | 'unknown';
* check this before dispatch: the gateway delivers a call to whichever
* connection the device holds, and a CLI-only device cannot run it.
*/
+export const clientKindFromChannels = (
+ deviceChannels: ReadonlyArray<{ channel?: string | null }> | undefined,
+): DeviceClientKind => {
+ const channels = (deviceChannels ?? []).map((c) => c.channel).filter((c): c is string => !!c);
+ if (channels.length === 0) return 'unknown';
+ const desktopChannels = channels.filter((c) => DESKTOP_CHANNELS.has(c)).length;
+ if (desktopChannels === 0) return 'cli-only';
+ return desktopChannels === channels.length ? 'desktop' : 'mixed';
+};
+
export const resolveDeviceClientKind = async (
userId: string,
deviceId: string,
@@ -34,14 +46,43 @@ export const resolveDeviceClientKind = async (
): Promise<DeviceClientKind> => {
try {
const devices = await deviceGateway.queryDeviceList(userId, workspaceId);
- const device = devices.find((d) => d.deviceId === deviceId);
- const channels = (device?.channels ?? []).map((c) => c.channel).filter((c): c is string => !!c);
- if (channels.length === 0) return 'unknown';
- const desktopChannels = channels.filter((c) => DESKTOP_CHANNELS.has(c)).length;
- if (desktopChannels === 0) return 'cli-only';
- return desktopChannels === channels.length ? 'desktop' : 'mixed';
+ return clientKindFromChannels(devices.find((d) => d.deviceId === deviceId)?.channels);
} catch (error) {
log('device presence lookup failed for %s: %O', deviceId, error);
return 'unknown';
}
};
+
+/**
+ * Which client on `deviceId` runs a tunneled MCP call (a stdio or
+ * local-network server), or `undefined` when none of its clients can.
+ *
+ * The desktop app always can and wins whenever it is connected: one call per
+ * device must land on one process, or a stateful stdio server's session would
+ * split across the two clients. A device with only `lh connect` runs it when
+ * that CLI reports `mcp` in `supportedToolCallTypes` β€” an older CLI
+ * dispatched the call by apiName to a same-named local tool. `unknown`
+ * presence keeps the desktop routing these calls always had.
+ *
+ * Pass `clientKind` when the caller already read the device's channels.
+ */
+export const resolveMcpClientKinds = async (
+ userId: string,
+ deviceId: string,
+ workspaceId?: string,
+ clientKind?: DeviceClientKind,
+): Promise<DeviceClient[] | undefined> => {
+ const kind = clientKind ?? (await resolveDeviceClientKind(userId, deviceId, workspaceId));
+ if (kind !== 'cli-only') return ['desktop'];
+
+ const cli = await deviceGateway.readDeviceSystemInfo(userId, deviceId, workspaceId, {
+ clientKinds: ['cli'],
+ });
+ if (cli.ok && cli.systemInfo.supportedToolCallTypes?.includes('mcp')) return ['cli'];
+ log(
+ 'cli-only device %s cannot run MCP calls: %s',
+ deviceId,
+ cli.ok ? 'CLI predates MCP support' : cli.reason,
+ );
+ return undefined;
+};
diff --git a/apps/server/src/services/toolExecution/__tests__/index.test.ts b/apps/server/src/services/toolExecution/__tests__/index.test.ts
index 39a58fdebf4..2921280b1ac 100644
--- a/apps/server/src/services/toolExecution/__tests__/index.test.ts
+++ b/apps/server/src/services/toolExecution/__tests__/index.test.ts
@@ -18,8 +18,13 @@ vi.mock('@/server/services/deviceGateway', () => ({
executeToolCall: vi.fn(),
isConfigured: false,
queryDeviceList: vi.fn().mockResolvedValue([]),
+ // An `lh connect` that predates MCP support reports no `mcp` call type.
+ readDeviceSystemInfo: vi.fn().mockResolvedValue({ ok: true, systemInfo: {} }),
},
}));
+
+/** System info from an `lh connect` that runs tunneled MCP calls. */
+const mcpCapableCli = { ok: true, systemInfo: { supportedToolCallTypes: ['tool', 'mcp'] } };
const mcpAppsEnabled = vi.hoisted(() => vi.fn().mockResolvedValue(false));
vi.mock('@/server/services/mcp/featureGate', () => ({ isMcpAppsEnabled: mcpAppsEnabled }));
vi.mock('@/server/services/deviceGateway/dispatchAuthorization', () => ({
@@ -584,8 +589,8 @@ describe('ToolExecutionService', () => {
// order and includes offline DB rows β€” the fallback must skip those.
vi.mocked(getScopedOnlineDevices).mockResolvedValue([
{ channels: [{ channel: 'desktop' }], deviceId: 'offline-row', online: false },
- // A newer CLI-only connection must be skipped: the CLI's
- // tool_call_request handler cannot execute `mcp` calls.
+ // A newer CLI-only connection must be skipped when that CLI predates
+ // MCP support: it would dispatch the call by apiName.
{ channels: [{ channel: 'cli' }], deviceId: 'cli-only', online: true },
{
channels: [{ channel: 'cli' }, { channel: 'desktop' }],
@@ -601,15 +606,70 @@ describe('ToolExecutionService', () => {
expect(getScopedOnlineDevices).toHaveBeenCalledWith(context.serverDB, 'user-1', undefined);
expect(deviceGateway.queryDeviceList).not.toHaveBeenCalled();
+ // The desktop app beside `lh connect` runs it, pinned so the gateway
+ // never hands the call to the CLI.
+ expect(deviceGateway.executeMcpCall).toHaveBeenCalledWith(
+ expect.objectContaining({ clientKinds: ['desktop'], deviceId: 'newest' }),
+ undefined,
+ );
+ });
+
+ it('falls back to the newest online lh connect device that runs MCP calls', async () => {
+ vi.mocked(deviceGateway.readDeviceSystemInfo).mockResolvedValueOnce(mcpCapableCli as any);
+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([
+ { channels: [{ channel: 'cli' }], deviceId: 'devbox-cli', online: true },
+ { channels: [{ channel: 'desktop' }], deviceId: 'older-desktop', online: true },
+ ] as any);
+ const service = makeService();
+
+ const result = await service.executeTool(
+ mcpPayload,
+ contextWith({ args: [], command: 'npx', name: 'my-mcp', type: 'stdio' }),
+ );
+
+ expect(result.success).toBe(true);
+ expect(deviceGateway.readDeviceSystemInfo).toHaveBeenCalledWith(
+ 'user-1',
+ 'devbox-cli',
+ undefined,
+ { clientKinds: ['cli'] },
+ );
+ expect(deviceGateway.executeMcpCall).toHaveBeenCalledWith(
+ expect.objectContaining({ clientKinds: ['cli'], deviceId: 'devbox-cli' }),
+ undefined,
+ );
+ });
+
+ it('tunnels to a CLI-only active device whose lh connect runs MCP calls', async () => {
+ vi.mocked(deviceGateway.queryDeviceList).mockResolvedValue([
+ { channels: [{ channel: 'cli' }], deviceId: 'mac-mini-cli' },
+ ] as any);
+ vi.mocked(deviceGateway.readDeviceSystemInfo).mockResolvedValueOnce(mcpCapableCli as any);
+ const service = makeService();
+
+ const result = await service.executeTool(
+ mcpPayload,
+ contextWith(
+ { args: [], command: 'npx', name: 'my-mcp', type: 'stdio' },
+ { activeDeviceId: 'mac-mini-cli', workspaceId: 'ws-1' },
+ ),
+ );
+
+ expect(result.success).toBe(true);
+ expect(getScopedOnlineDevices).not.toHaveBeenCalled();
expect(deviceGateway.executeMcpCall).toHaveBeenCalledWith(
- expect.objectContaining({ deviceId: 'newest' }),
+ expect.objectContaining({
+ clientKinds: ['cli'],
+ deviceId: 'mac-mini-cli',
+ workspaceId: 'ws-1',
+ }),
undefined,
);
});
- // `lh connect` answers `mcp` tool calls with `Unknown tool API: <tool>` β€” an
- // active device that is CLI-only must not receive the tunnel (Honcho-Memory
- // vents: calls worked until the agent activated a CLI-only Mac mini).
+ // An older `lh connect` answers `mcp` tool calls by apiName β€” an active
+ // device whose only client is such a CLI must not receive the tunnel
+ // (Honcho-Memory vents: calls worked until the agent activated a CLI-only Mac mini).
it('skips a CLI-only active device and tunnels to the newest desktop device', async () => {
vi.mocked(deviceGateway.queryDeviceList).mockResolvedValue([
{ channels: [{ channel: 'cli' }], deviceId: 'mac-mini-cli' },
@@ -635,7 +695,7 @@ describe('ToolExecutionService', () => {
);
});
- it('fails with an actionable error when only CLI devices are online', async () => {
+ it('fails with an actionable error when only older CLI devices are online', async () => {
vi.mocked(deviceGateway.queryDeviceList).mockResolvedValue([
{ channels: [{ channel: 'cli' }], deviceId: 'mac-mini-cli' },
] as any);
@@ -658,7 +718,7 @@ describe('ToolExecutionService', () => {
expect(result.content).toContain('lh connect');
});
- it('fails closed for a workspace run whose active device is CLI-only', async () => {
+ it('fails closed for a workspace run whose active device has only an older CLI', async () => {
vi.mocked(deviceGateway.queryDeviceList).mockResolvedValue([
{ channels: [{ channel: 'cli' }], deviceId: 'ws-cli' },
] as any);
@@ -851,7 +911,7 @@ describe('ToolExecutionService', () => {
expect(callTool).not.toHaveBeenCalled();
expect(result.success).toBe(false);
expect((result.error as any)?.code).toBe('MCP_DEVICE_UNAVAILABLE');
- expect(result.content).toContain('open the LobeHub desktop app');
+ expect(result.content).toContain('Open the LobeHub desktop app or run `lh connect`');
});
it('fails closed when no serverDB is available to apply device visibility', async () => {
diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.ts
index 3172951f5a2..008f4f531c6 100644
--- a/apps/server/src/services/toolExecution/index.ts
+++ b/apps/server/src/services/toolExecution/index.ts
@@ -1,6 +1,6 @@
import { BRANDING_NAME } from '@lobechat/business-const';
import { DEFAULT_TOOL_RESULT_MAX_LENGTH, truncateToolResult } from '@lobechat/prompts/toolResult';
-import { type ChatToolPayload } from '@lobechat/types';
+import { type ChatToolPayload, type DeviceClient } from '@lobechat/types';
import { isDeviceOnlyMcpEndpoint } from '@lobechat/utils/mcpEndpoint';
import debug from 'debug';
@@ -11,7 +11,10 @@ import {
getConnectorToolPermission,
} from '@/libs/mcp/connectorPermissionCheck';
import { deviceGateway } from '@/server/services/deviceGateway';
-import { resolveDeviceClientKind } from '@/server/services/deviceGateway/deviceChannels';
+import {
+ clientKindFromChannels,
+ 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';
@@ -31,6 +34,13 @@ import {
const log = debug('lobe-server:tool-execution-service');
+/** The device a device-only MCP call runs on, and which of its clients runs it. */
+interface McpTunnelTarget {
+ clientKinds: DeviceClient[];
+ deviceId: string;
+ workspaceId?: string;
+}
+
interface ToolExecutionServiceDeps {
builtinToolsExecutor: BuiltinToolsExecutor;
mcpService: MCPService;
@@ -319,13 +329,13 @@ export class ToolExecutionService {
return await this.executeCloudMCPTool(payload, context, mcpParams);
}
- // Stdio must run on a desktop device. Without a configured gateway or a
+ // 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)) {
if (!deviceGateway.isConfigured) {
- const message = `MCP server '${identifier}' uses stdio and must run on a desktop device, but this server's device gateway is not configured. Configure a device gateway on the server and connect the desktop app on the machine that hosts this MCP server, then retry.`;
+ 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 {
content: message,
error: { code: 'MCP_GATEWAY_NOT_CONFIGURED', message },
@@ -338,7 +348,7 @@ 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). No online ${BRANDING_NAME} desktop app was found to run it (a device connected only through the \`lh connect\` CLI cannot run MCP servers) β€” open the ${BRANDING_NAME} desktop app on the machine that hosts this MCP server, then retry.`;
+ 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.`;
return {
content: message,
error: { code: 'MCP_DEVICE_UNAVAILABLE', message },
@@ -407,7 +417,7 @@ export class ToolExecutionService {
*/
private async resolveMcpTunnelTarget(
context: ToolExecutionContext,
- ): Promise<{ deviceId: string; workspaceId?: string } | undefined> {
+ ): Promise<McpTunnelTarget | undefined> {
// Workspace devices live under the `workspace:<id>` principal in the
// gateway, so device lookup AND the tunneled call itself must carry the
// same scope β€” resolved the way the local-system/browser device runtimes
@@ -415,16 +425,16 @@ export class ToolExecutionService {
// workspace when the run context lost it).
const workspaceId = await resolveRunWorkspaceId(context);
if (context.activeDeviceId) {
- // Only the desktop app handles `mcp` tool calls; a device whose only
- // live connection is `lh connect` answers them with `Unknown tool API`.
- // Such an active device is skipped: personal runs fall through to the
- // newest desktop device below, workspace runs fail closed.
- const clientKind =
+ // The desktop app and an `lh connect` that reports MCP support run the
+ // call; a device whose only client is an older CLI cannot. Such an
+ // active device is skipped: personal runs fall through to the newest
+ // capable device below, workspace runs fail closed.
+ const clientKinds =
context.userId !== undefined
- ? await resolveDeviceClientKind(context.userId, context.activeDeviceId, workspaceId)
- : 'unknown';
- if (clientKind !== 'cli-only') return { deviceId: context.activeDeviceId, workspaceId };
- log('Active device %s is CLI-only; not tunneling MCP to it', context.activeDeviceId);
+ ? await resolveMcpClientKinds(context.userId, context.activeDeviceId, workspaceId)
+ : ['desktop' as const];
+ if (clientKinds) return { clientKinds, deviceId: context.activeDeviceId, workspaceId };
+ log('Active device %s cannot run MCP calls; not tunneling to it', context.activeDeviceId);
}
// The implicit fallback is PERSONAL-scope only. In a workspace run the
// connector may have been authorized by ANOTHER member, and tunneling its
@@ -439,16 +449,23 @@ export class ToolExecutionService {
if (!context.userId || !context.serverDB) return undefined;
try {
const devices = await getScopedOnlineDevices(context.serverDB, context.userId, undefined);
- // Already sorted online-first / most-recently-active; drop offline rows.
- // Only the desktop app handles `mcp` tool calls β€” the CLI's
- // tool_call_request handler ignores `toolCall.type`/`params`, so a
- // device whose only live connection is `lh connect` would fail the call.
- const newest = devices.find(
- (d) =>
- d.online &&
- d.channels?.some((c) => c.channel === 'desktop' || c.channel === 'desktop-dev'),
- );
- return newest ? { deviceId: newest.deviceId, workspaceId: undefined } : 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;
}
@@ -468,7 +485,7 @@ export class ToolExecutionService {
payload: ChatToolPayload,
context: ToolExecutionContext,
mcpParams: StdioMCPParams | HttpMCPClientParams,
- target: { deviceId: string; workspaceId?: string },
+ target: McpTunnelTarget,
): Promise<ToolExecutionResult> {
const { identifier, apiName, arguments: args } = payload;
@@ -526,6 +543,9 @@ export class ToolExecutionService {
type: 'http',
url: mcpParams.url,
},
+ // Pin the client resolved for this device, so the call never lands on
+ // one of its clients that cannot run it.
+ clientKinds: target.clientKinds,
userId: context.userId!,
// Address the workspace device pool when the run is workspace-scoped β€”
// omitting this would route the call to the personal pool and miss an
diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.ts
index ac67e3ae4bf..800cd70fbfc 100644
--- a/packages/device-gateway-client/src/http.test.ts
+++ b/packages/device-gateway-client/src/http.test.ts
@@ -658,6 +658,27 @@ describe('GatewayHttpClient', () => {
expect(body.deviceId).toBe('device-1');
});
+ it('sends the client the caller picked for the device', async () => {
+ mockFetch({
+ json: vi.fn().mockResolvedValue({ content: 'ok', success: true }),
+ ok: true,
+ });
+
+ await client.executeMcpCall({
+ apiName: 'echo',
+ arguments: '{}',
+ clientKinds: ['cli'],
+ deviceId: 'device-1',
+ identifier: 'echo-mcp',
+ params: { args: [], command: 'echo-mcp', name: 'echo-mcp', type: 'stdio' },
+ userId: 'user-1',
+ });
+
+ const body = JSON.parse((vi.mocked(fetch).mock.calls[0][1] as RequestInit).body as string);
+ expect(body.clientKinds).toEqual(['cli']);
+ expect(body.toolCall.clientKinds).toBeUndefined();
+ });
+
it('should surface non-ok responses as a failed result', async () => {
mockFetch({
ok: false,
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index 1a72be9b1a5..da49ac2bb5c 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -174,6 +174,8 @@ export class GatewayHttpClient {
async executeMcpCall(mcpCall: {
apiName: string;
arguments: string;
+ /** The device's client that runs the call; omitted, `resolveClientKinds` decides. */
+ clientKinds?: DeviceClient[];
deviceId?: string;
identifier: string;
params: GatewayMcpParams;
@@ -181,9 +183,9 @@ export class GatewayHttpClient {
userId: string;
workspaceId?: string;
}): Promise<DeviceToolCallResult> {
- const { deviceId, timeout, userId, workspaceId, ...toolCall } = mcpCall;
+ const { clientKinds, deviceId, timeout, userId, workspaceId, ...toolCall } = mcpCall;
return this.postToolCall(
- { deviceId, timeout, userId, workspaceId },
+ { clientKinds, deviceId, timeout, userId, workspaceId },
{ ...toolCall, type: 'mcp' },
);
}
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index e544f273f61..6c842d144dc 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -44,6 +44,12 @@ export interface DeviceSystemInfo {
* `codex-app-server-v1` runs `lh hetero exec --codex-app-server` with native turn provenance.
*/
supportedAgentRuntimes?: string[];
+ /**
+ * Tunneled tool-call kinds this client runs beyond plain `'tool'` calls
+ * (e.g. `'mcp'`); absent on older clients. The desktop app runs MCP calls
+ * without reporting it β€” the server routes those to it by channel.
+ */
+ supportedToolCallTypes?: GatewayToolCallType[];
/** Opt-in tool identifiers supported by this client; absent on older clients. */
supportedTools?: string[];
userDataPath: string;
diff --git a/packages/device-mcp/package.json b/packages/device-mcp/package.json
new file mode 100644
index 00000000000..1dfb4a28620
--- /dev/null
+++ b/packages/device-mcp/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "@lobechat/device-mcp",
+ "version": "1.0.0",
+ "private": true,
+ "description": "Runs MCP servers only the user's machine can reach (stdio, localhost / LAN HTTP) for device hosts: the desktop app and lh connect.",
+ "sideEffects": false,
+ "exports": {
+ ".": "./src/index.ts",
+ "./client": "./src/client.ts"
+ },
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "scripts": {
+ "test": "bunx vitest run --silent='passed-only'",
+ "test:coverage": "bunx vitest run --coverage"
+ },
+ "dependencies": {
+ "@lobechat/const": "workspace:*",
+ "@lobechat/utils": "workspace:*",
+ "@modelcontextprotocol/client": "~2.4.0"
+ },
+ "devDependencies": {
+ "vitest": "5.0.0"
+ }
+}
diff --git a/apps/desktop/src/main/libs/mcp/client.mcpApp.test.ts b/packages/device-mcp/src/client.mcpApp.test.ts
similarity index 100%
rename from apps/desktop/src/main/libs/mcp/client.mcpApp.test.ts
rename to packages/device-mcp/src/client.mcpApp.test.ts
diff --git a/apps/desktop/src/main/libs/mcp/client.negotiation.test.ts b/packages/device-mcp/src/client.negotiation.test.ts
similarity index 90%
rename from apps/desktop/src/main/libs/mcp/client.negotiation.test.ts
rename to packages/device-mcp/src/client.negotiation.test.ts
index c19738d3577..da5f3c0915f 100644
--- a/apps/desktop/src/main/libs/mcp/client.negotiation.test.ts
+++ b/packages/device-mcp/src/client.negotiation.test.ts
@@ -5,7 +5,7 @@ import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, it } from 'vitest';
-import { startNegotiationServers } from '../../../../../../src/libs/mcp/__tests__/fixtures/negotiationServers';
+import { startNegotiationServers } from '../../../src/libs/mcp/__tests__/fixtures/negotiationServers';
import { MCPClient } from './client';
describe('desktop transport protocol policy', () => {
@@ -52,10 +52,7 @@ describe('desktop transport protocol policy', () => {
command: process.execPath,
args: [
fileURLToPath(
- new URL(
- '../../../../../../src/libs/mcp/__tests__/fixtures/legacyStdio.mjs',
- import.meta.url,
- ),
+ new URL('../../../src/libs/mcp/__tests__/fixtures/legacyStdio.mjs', import.meta.url),
),
trace,
],
diff --git a/apps/desktop/src/main/libs/mcp/__tests__/client.stderr.test.ts b/packages/device-mcp/src/client.stderr.test.ts
similarity index 97%
rename from apps/desktop/src/main/libs/mcp/__tests__/client.stderr.test.ts
rename to packages/device-mcp/src/client.stderr.test.ts
index e6882e86b68..ee3b255cd53 100644
--- a/apps/desktop/src/main/libs/mcp/__tests__/client.stderr.test.ts
+++ b/packages/device-mcp/src/client.stderr.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
-import { MCPClient } from '../client';
+import { MCPClient } from './client';
/**
* Focused test for the bounded stderr tail: only the stderr listener
diff --git a/apps/desktop/src/main/libs/mcp/client.test.ts b/packages/device-mcp/src/client.test.ts
similarity index 100%
rename from apps/desktop/src/main/libs/mcp/client.test.ts
rename to packages/device-mcp/src/client.test.ts
diff --git a/apps/desktop/src/main/libs/mcp/client.ts b/packages/device-mcp/src/client.ts
similarity index 96%
rename from apps/desktop/src/main/libs/mcp/client.ts
rename to packages/device-mcp/src/client.ts
index a46b0ee28cd..e331216e464 100644
--- a/apps/desktop/src/main/libs/mcp/client.ts
+++ b/packages/device-mcp/src/client.ts
@@ -19,8 +19,6 @@ import {
} from '@modelcontextprotocol/client';
import { getDefaultEnvironment, StdioClientTransport } from '@modelcontextprotocol/client/stdio';
-import { getDesktopEnv } from '@/env';
-
import { reapOrphanedProcessGroup, terminatePrecheckProcess } from './process-tree';
import type { MCPClientParams, McpPrompt, McpResource, McpTool, ToolCallResult } from './types';
@@ -348,10 +346,23 @@ export function describeStdioSpawnFailure(input: StdioSpawnFailureInput): string
);
}
+export interface MCPClientOptions {
+ /** `clientInfo.name` announced to the server. */
+ clientName?: string;
+ /**
+ * Announce MCP Apps (SEP-1865), so servers expose their interactive views.
+ * Only for users with the `mcp_apps` flag: a server may answer an
+ * announcing client with app-specific results instead of its text fallback.
+ */
+ mcpApps?: boolean;
+ /** Default per-call `tools/call` deadline; the SDK default applies when unset. */
+ toolTimeoutMs?: number;
+}
+
export class MCPClient {
/**
* Upper bound on retained stderr lines. Pooled clients can live for the
- * whole desktop session; without a cap a verbose long-lived MCP server
+ * whole host process session; without a cap a verbose long-lived MCP server
* would grow `stderrLogs` (and every enhanced error built from it)
* without limit. Only the most recent tail is kept for diagnostics.
*/
@@ -371,6 +382,7 @@ export class MCPClient {
/** tool name β†’ `ui://` resource URI, filled from the last `listTools` */
private uiResourceUris?: Map<string, string>;
private readonly mcpApps: boolean;
+ private readonly toolTimeoutMs?: number;
private toolUiMeta?: Map<string, McpUiToolMeta>;
/**
* The tools a view may call (`_meta.ui.visibility` with "app", or unset), from
@@ -385,19 +397,15 @@ export class MCPClient {
constructor(
params: MCPClientParams,
{
+ clientName = 'lobehub-device-mcp-client',
mcpApps = false,
- }: {
- /**
- * Announce MCP Apps (SEP-1865), so servers expose their interactive views.
- * Only for users with the `mcp_apps` flag: a server may answer an
- * announcing client with app-specific results instead of its text fallback.
- */
- mcpApps?: boolean;
- } = {},
+ toolTimeoutMs,
+ }: MCPClientOptions = {},
) {
this.mcpApps = mcpApps;
+ this.toolTimeoutMs = toolTimeoutMs;
this.mcp = new Client(
- { name: 'lobehub-desktop-mcp-client', version: '1.0.0' },
+ { name: clientName, version: '1.0.0' },
{
...(mcpApps && {
capabilities: {
@@ -483,7 +491,7 @@ export class MCPClient {
const lines = text.split('\n').filter((line) => line.trim());
this.stderrLogs.push(...lines);
// Keep only the most recent tail: a pooled, long-lived stdio
- // server must not grow desktop memory without bound.
+ // server must not grow host memory without bound.
if (this.stderrLogs.length > MCPClient.STDERR_LOG_LIMIT) {
this.stderrLogs.splice(0, this.stderrLogs.length - MCPClient.STDERR_LOG_LIMIT);
}
@@ -903,13 +911,21 @@ export class MCPClient {
};
}
- async callTool(toolName: string, args: any): Promise<ToolCallResult> {
+ /**
+ * `timeoutMs` overrides the client-wide `toolTimeoutMs` for one call: a
+ * tunneled call carries the caller's own deadline. Without either the SDK
+ * default applies.
+ */
+ async callTool(
+ toolName: string,
+ args: any,
+ { timeoutMs }: { timeoutMs?: number } = {},
+ ): Promise<ToolCallResult> {
+ const timeout = timeoutMs ?? this.toolTimeoutMs;
try {
const result = await this.mcp.callTool(
{ arguments: args, name: toolName },
- {
- timeout: getDesktopEnv().MCP_TOOL_TIMEOUT,
- },
+ timeout === undefined ? undefined : { timeout },
);
return result as ToolCallResult;
} catch (error) {
diff --git a/packages/device-mcp/src/content.test.ts b/packages/device-mcp/src/content.test.ts
new file mode 100644
index 00000000000..cbae2dc27db
--- /dev/null
+++ b/packages/device-mcp/src/content.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { contentBlocksToMarkdown, uploadMediaBlocks } from './content';
+
+const png = Buffer.from('image-bytes').toString('base64');
+
+describe('uploadMediaBlocks', () => {
+ it('replaces media bytes with the key the host stored them under', async () => {
+ const upload = vi.fn(async ({ path }: { path: string }) => `stored/${path}`);
+
+ const [image, text] = await uploadMediaBlocks(
+ [
+ { data: png, mimeType: 'image/png; charset=binary', type: 'image' },
+ { text: 'caption', type: 'text' },
+ ],
+ upload,
+ );
+
+ expect(upload).toHaveBeenCalledWith(
+ expect.objectContaining({
+ base64: png,
+ buffer: Buffer.from('image-bytes'),
+ mimeType: 'image/png',
+ path: expect.stringMatching(/^mcp\/images\/\d{4}-\d{2}-\d{2}\/[\da-f-]+\.png$/),
+ }),
+ );
+ expect(image).toMatchObject({
+ data: expect.stringMatching(/^stored\/mcp\/images\//),
+ type: 'image',
+ });
+ expect(text).toEqual({ text: 'caption', type: 'text' });
+ });
+
+ it('turns media the host cannot store into a note instead of failing the call', async () => {
+ const blocks = await uploadMediaBlocks(
+ [
+ { data: png, mimeType: 'image/png', type: 'image' },
+ { resource: { blob: png, mimeType: 'audio/mpeg', uri: 'file://a.mp3' }, type: 'resource' },
+ ],
+ async () => undefined,
+ );
+
+ expect(blocks).toEqual([
+ { text: expect.stringContaining('an image (image/png)'), type: 'text' },
+ { text: expect.stringContaining('audio (audio/mpeg)'), type: 'text' },
+ ]);
+ await expect(contentBlocksToMarkdown(blocks, async (key) => key)).resolves.toContain(
+ 'could not upload',
+ );
+ });
+});
diff --git a/packages/device-mcp/src/content.ts b/packages/device-mcp/src/content.ts
new file mode 100644
index 00000000000..132224c5082
--- /dev/null
+++ b/packages/device-mcp/src/content.ts
@@ -0,0 +1,177 @@
+import { createHash, randomUUID } from 'node:crypto';
+import path from 'node:path';
+
+import type {
+ AudioContent,
+ ImageContent,
+ ResourceContent,
+ TextContent,
+ ToolCallContent,
+} from './types';
+
+/**
+ * Stores one media block a tool returned and answers the key the result keeps
+ * in place of its base64 bytes. `path` is a suggested storage path
+ * (`mcp/<images|audios>/<day>/<uuid>.<ext>`); a host with its own naming may
+ * ignore it. Answers `undefined` when this host cannot store media right now
+ * (e.g. no server credentials): the block is then replaced by a text note the
+ * model can explain, instead of failing a tool call that already ran.
+ */
+export type McpMediaUploader = (media: {
+ /** The block's bytes as the server sent them (base64, no `data:` prefix). */
+ base64: string;
+ buffer: Buffer;
+ filename: string;
+ hash: string;
+ mimeType: string;
+ path: string;
+}) => Promise<string | undefined>;
+
+/** Resolves a key {@link McpMediaUploader} returned to a URL the chat can load. */
+export type McpMediaUrlResolver = (key: string) => Promise<string>;
+
+const MEDIA_UPLOAD_CONFIG = {
+ audio: {
+ defaultExtension: 'mp3',
+ defaultMimeType: 'audio/mpeg',
+ pathnameSegment: 'audios',
+ },
+ image: {
+ defaultExtension: 'png',
+ defaultMimeType: 'image/png',
+ pathnameSegment: 'images',
+ },
+} as const;
+
+type MediaContentType = keyof typeof MEDIA_UPLOAD_CONFIG;
+
+const PREFERRED_MIME_EXTENSIONS: Record<string, string> = {
+ 'audio/mpeg': 'mp3',
+ 'audio/mp3': 'mp3',
+ 'image/svg+xml': 'svg',
+};
+
+const normalizeMimeType = (mimeType: string | undefined, mediaType: MediaContentType) => {
+ const normalized = mimeType?.split(';')[0]?.trim().toLowerCase();
+ return normalized || MEDIA_UPLOAD_CONFIG[mediaType].defaultMimeType;
+};
+
+const getMediaContentType = (mimeType: string | undefined): MediaContentType | undefined => {
+ const normalized = mimeType?.split(';')[0]?.trim().toLowerCase();
+ if (normalized?.startsWith('image/')) return 'image';
+ if (normalized?.startsWith('audio/')) return 'audio';
+};
+
+const getFileExtensionFromMimeType = (mimeType: string, mediaType: MediaContentType) => {
+ const [, subtype = ''] = mimeType.split('/');
+ const sanitizedSubtype = subtype
+ .split('+')[0]
+ .replaceAll(/[^a-z0-9]/gi, '')
+ .toLowerCase();
+
+ return (
+ PREFERRED_MIME_EXTENSIONS[mimeType] ||
+ sanitizedSubtype ||
+ MEDIA_UPLOAD_CONFIG[mediaType].defaultExtension
+ );
+};
+
+const todayShard = () => new Date().toISOString().split('T')[0];
+
+const uploadMediaBlock = async (
+ upload: McpMediaUploader,
+ base64: string,
+ mediaType: MediaContentType,
+ mimeType: string,
+) => {
+ const config = MEDIA_UPLOAD_CONFIG[mediaType];
+ const ext = getFileExtensionFromMimeType(mimeType, mediaType);
+ const buffer = Buffer.from(base64, 'base64');
+ const hash = createHash('sha256').update(buffer).digest('hex');
+ const filename = `${randomUUID()}.${ext}`;
+ const filePath = path.posix.join('mcp', config.pathnameSegment, todayShard(), filename);
+
+ return upload({ base64, buffer, filename, hash, mimeType, path: filePath });
+};
+
+const mediaUnavailable = (mediaType: MediaContentType, mimeType: string): TextContent => ({
+ text: `[The MCP tool returned ${mediaType === 'image' ? 'an image' : 'audio'} (${mimeType}) that this device could not upload, so it is not shown.]`,
+ type: 'text',
+});
+
+/**
+ * Replace the base64 bytes of every image / audio block (and media `resource`
+ * blobs) with the key the uploader stored them under, so a tool result stays
+ * small and the chat loads media by URL.
+ */
+export const uploadMediaBlocks = (
+ blocks: ToolCallContent[],
+ upload: McpMediaUploader,
+): Promise<ToolCallContent[]> =>
+ Promise.all(
+ blocks.map(async (block) => {
+ if (block.type === 'image' || block.type === 'audio') {
+ const mediaType = block.type;
+ const mimeType = normalizeMimeType(block.mimeType, mediaType);
+ const data = await uploadMediaBlock(upload, block.data, mediaType, mimeType);
+ if (data === undefined) return mediaUnavailable(mediaType, mimeType);
+
+ return { ...block, data, mimeType };
+ }
+
+ if (block.type === 'resource') {
+ const resourceBlock = block as ResourceContent;
+ const resource = resourceBlock.resource;
+ const mediaType = getMediaContentType(resource?.mimeType);
+
+ if (!resource?.blob || !mediaType) return block;
+
+ const mimeType = normalizeMimeType(resource.mimeType, mediaType);
+ const data = await uploadMediaBlock(upload, resource.blob, mediaType, mimeType);
+ if (data === undefined) return mediaUnavailable(mediaType, mimeType);
+ const metadata = resourceBlock._meta ? { _meta: resourceBlock._meta } : {};
+
+ if (mediaType === 'image') {
+ return { ...metadata, data, mimeType, type: 'image' } as ImageContent;
+ }
+
+ return { ...metadata, data, mimeType, type: 'audio' } as AudioContent;
+ }
+
+ return block;
+ }),
+ );
+
+/** Render processed content blocks as the markdown the model reads. */
+export const contentBlocksToMarkdown = async (
+ blocks: ToolCallContent[] | null | undefined,
+ getHTTPURL: McpMediaUrlResolver,
+) => {
+ if (!blocks) return '';
+
+ const parts = await Promise.all(
+ blocks.map(async (item) => {
+ switch (item.type) {
+ case 'text': {
+ return item.text;
+ }
+ case 'image': {
+ const url = await getHTTPURL(item.data);
+ return `![](${url})`;
+ }
+ case 'audio': {
+ const url = await getHTTPURL(item.data);
+ return `<resource type="${item.type}" url="${url}" />`;
+ }
+ case 'resource': {
+ return `<resource type="${item.type}">${JSON.stringify(item.resource)}</resource>`;
+ }
+ default: {
+ return '';
+ }
+ }
+ }),
+ );
+
+ return parts.filter(Boolean).join('\n\n');
+};
diff --git a/packages/device-mcp/src/index.ts b/packages/device-mcp/src/index.ts
new file mode 100644
index 00000000000..c74c9c5ac0b
--- /dev/null
+++ b/packages/device-mcp/src/index.ts
@@ -0,0 +1,16 @@
+export type { McpMediaUploader, McpMediaUrlResolver } from './content';
+export { contentBlocksToMarkdown, uploadMediaBlocks } from './content';
+export type {
+ DeviceMcpLogger,
+ DeviceMcpRuntimeOptions,
+ McpCallOptions,
+ McpSessionOptions,
+ McpToolOutput,
+} from './runtime';
+export { DeviceMcpRuntime, withStdioOutput } from './runtime';
+export {
+ isDeadTransportError,
+ isStaleSessionError,
+ serializeMcpClientParams,
+} from './sessionGuards';
+export type * from './types';
diff --git a/apps/desktop/src/main/libs/mcp/process-tree.test.ts b/packages/device-mcp/src/process-tree.test.ts
similarity index 100%
rename from apps/desktop/src/main/libs/mcp/process-tree.test.ts
rename to packages/device-mcp/src/process-tree.test.ts
diff --git a/apps/desktop/src/main/libs/mcp/process-tree.ts b/packages/device-mcp/src/process-tree.ts
similarity index 100%
rename from apps/desktop/src/main/libs/mcp/process-tree.ts
rename to packages/device-mcp/src/process-tree.ts
diff --git a/apps/desktop/src/main/controllers/__tests__/McpCtr.session-reuse.test.ts b/packages/device-mcp/src/runtime.test.ts
similarity index 78%
rename from apps/desktop/src/main/controllers/__tests__/McpCtr.session-reuse.test.ts
rename to packages/device-mcp/src/runtime.test.ts
index 35d4f441cd5..ee1102f792f 100644
--- a/apps/desktop/src/main/controllers/__tests__/McpCtr.session-reuse.test.ts
+++ b/packages/device-mcp/src/runtime.test.ts
@@ -1,15 +1,19 @@
-import { deserializeMcpIpcPayload, serializeMcpIpcPayload } from '@lobechat/utils/mcpIpcPayload';
import { SdkError, SdkErrorCode, SdkHttpError } from '@modelcontextprotocol/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import type { App } from '@/core/App';
+import { DeviceMcpRuntime } from './runtime';
-import McpCtr from '../McpCtr';
+interface StdioToolInput {
+ args: unknown;
+ env: Record<string, string> | undefined;
+ params: { args?: string[]; command: string; name: string };
+ toolName: string;
+}
const createStdioToolInput = (
toolName: string,
env: Record<string, string> | undefined,
-): Parameters<McpCtr['runStdioMcpTool']>[0] => ({
+): StdioToolInput => ({
args: '',
env,
params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
@@ -20,10 +24,9 @@ const { mcpClientMocks } = vi.hoisted(() => ({
mcpClientMocks: vi.fn(),
}));
-// The controller lazily imports the MCP client module; mock the module so no
-// real stdio process is ever spawned. The specifier must mirror the
-// controller's own dynamic import (`../libs/mcp/client` relative to McpCtr.ts).
-vi.mock('../../libs/mcp/client', () => ({
+// The runtime lazily imports the MCP client module; mock the module so no
+// real stdio process is ever spawned.
+vi.mock('./client', () => ({
MCPClient: class {
constructor(public params: unknown) {
return mcpClientMocks();
@@ -35,10 +38,6 @@ vi.mock('../../libs/mcp/client', () => ({
},
}));
-const mockApp = {
- getService: vi.fn(() => null),
-} as unknown as App;
-
const makeClientInstance = (label: string) => ({
callTool: vi.fn().mockImplementation(async () => ({
content: [{ text: `${label}-result`, type: 'text' }],
@@ -50,119 +49,58 @@ const makeClientInstance = (label: string) => ({
listManifests: vi.fn().mockResolvedValue({ tools: [] }),
});
-describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
- let ctr: McpCtr;
+/** Drives the runtime with the call shapes the device hosts send it. */
+const createHarness = (uploadMedia: ReturnType<typeof vi.fn>) => {
+ const runtime = new DeviceMcpRuntime({
+ getMediaUrl: async (key) => `https://files.test/${key}`,
+ uploadMedia,
+ });
+ return {
+ disposeAllPooledClients: () => runtime.dispose(),
+ listStdioTools: (input: StdioToolInput) =>
+ runtime.listTools({
+ args: input.params.args || [],
+ command: input.params.command,
+ env: input.env,
+ name: input.params.name,
+ type: 'stdio',
+ }),
+ get mcpClientLastUsedAt() {
+ return (runtime as any).lastUsedAt as Map<string, number>;
+ },
+ runHttpMcpTool: (http: { name: string; url: string }, toolName: string, args: unknown) =>
+ runtime.runTool({ ...http, type: 'http' }, toolName, args),
+ runStdioMcpTool: (input: StdioToolInput) =>
+ runtime.runTool(
+ {
+ args: input.params.args || [],
+ command: input.params.command,
+ env: input.env,
+ name: input.params.name,
+ type: 'stdio',
+ },
+ input.toolName,
+ input.args,
+ ),
+ };
+};
+
+describe('DeviceMcpRuntime stdio session reuse (T-801 stateful MCP servers)', () => {
+ let ctr: ReturnType<typeof createHarness>;
+ let uploadMedia: ReturnType<typeof vi.fn>;
beforeEach(() => {
vi.clearAllMocks();
vi.resetAllMocks();
mcpClientMocks.mockReset();
- ctr = new McpCtr(mockApp);
+ uploadMedia = vi.fn(async ({ path }: { path: string }) => path);
+ ctr = createHarness(uploadMedia);
});
afterEach(() => {
vi.restoreAllMocks();
});
- it.each(['My server description'])(
- 'keeps stdio descriptions as metadata (%s)',
- async (description) => {
- const instance = {
- ...makeClientInstance('tools-only'),
- listManifests: vi.fn().mockResolvedValue({
- prompts: undefined,
- resources: undefined,
- tools: [{ inputSchema: { type: 'object' }, name: 'hello' }],
- }),
- };
- mcpClientMocks.mockReturnValue(instance);
-
- const result = await ctr.getStdioMcpServerManifest(
- serializeMcpIpcPayload({
- command: 'test-command',
- metadata: { description },
- name: 'tools-only',
- }),
- );
- const manifest = deserializeMcpIpcPayload<{ api: unknown[]; meta: { description?: string } }>(
- result,
- );
-
- expect(manifest.api).toHaveLength(1);
- expect(manifest.meta.description).toBe(description);
- },
- );
-
- it.each(['My server description'])(
- 'keeps HTTP descriptions as metadata (%s)',
- async (description) => {
- const instance = { ...makeClientInstance('http'), listTools: vi.fn().mockResolvedValue([]) };
- mcpClientMocks.mockReturnValue(instance);
-
- const result = await ctr.getStreamableMcpServerManifest(
- serializeMcpIpcPayload({
- identifier: 'empty-server',
- metadata: { description },
- url: 'http://localhost/mcp',
- }),
- );
- const manifest = deserializeMcpIpcPayload<{ api: unknown[]; meta: { description?: string } }>(
- result,
- );
-
- expect(manifest.api).toEqual([]);
- expect(manifest.meta.description).toBe(description);
- },
- );
-
- it.each([
- {
- capabilities: { tools: [{ name: 'hello' }] },
- summary: '1 tool',
- },
- {
- capabilities: { prompts: [], resources: [], tools: [] },
- summary: 'no tools, prompts, or resources',
- },
- {
- capabilities: {
- prompts: [{ name: 'greet' }],
- resources: [{ name: 'readme' }],
- tools: [{ name: 'hello' }],
- },
- summary: '1 prompt, 1 resource, 1 tool',
- },
- ])('persists the automatic stdio description: $summary', async ({ capabilities, summary }) => {
- const instance = makeClientInstance('automatic');
- instance.listManifests.mockResolvedValue(capabilities);
- mcpClientMocks.mockReturnValue(instance);
-
- const result = await ctr.getStdioMcpServerManifest(
- serializeMcpIpcPayload({ command: 'test-command', name: 'automatic' }),
- );
- const manifest = deserializeMcpIpcPayload<{ meta: { description: string } }>(result);
-
- expect(manifest.meta.description).toBe(`automatic MCP server has ${summary}`);
- expect(manifest.meta.description).not.toContain('undefined');
- });
-
- it.each([
- { tools: [], summary: 'no tools, prompts, or resources' },
- { tools: [{ name: 'hello' }], summary: '1 tool, like "hello"' },
- ])('persists the automatic HTTP description: $summary', async ({ tools, summary }) => {
- mcpClientMocks.mockReturnValue({
- ...makeClientInstance('automatic'),
- listTools: vi.fn().mockResolvedValue(tools),
- });
- const result = await ctr.getStreamableMcpServerManifest(
- serializeMcpIpcPayload({ identifier: 'automatic', url: 'http://localhost/mcp' }),
- );
- const manifest = deserializeMcpIpcPayload<{ meta: { description: string } }>(result);
-
- expect(manifest.meta.description).toBe(`automatic MCP server has ${summary}`);
- expect(manifest.meta.description).not.toContain('undefined');
- });
-
it('returns a failed tool result without replaying an MCP isError result', async () => {
const instance = makeClientInstance('failed');
instance.callTool.mockResolvedValue({
@@ -199,8 +137,8 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
const instance = makeClientInstance('first');
mcpClientMocks.mockReturnValue(instance);
- await ctr.runStdioMcpTool(createStdioToolInput('open_database', undefined) as any);
- await ctr.runStdioMcpTool(createStdioToolInput('execute_python', undefined) as any);
+ await ctr.runStdioMcpTool(createStdioToolInput('open_database', undefined));
+ await ctr.runStdioMcpTool(createStdioToolInput('execute_python', undefined));
// Exactly ONE MCPClient was constructed for both calls: the stdio
// process is NOT respawned per call, so server-side state survives.
@@ -217,13 +155,13 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
const second = makeClientInstance('b');
mcpClientMocks.mockReturnValueOnce(first).mockReturnValueOnce(second);
- await ctr.runStdioMcpTool(createStdioToolInput('open_database', undefined) as any);
+ await ctr.runStdioMcpTool(createStdioToolInput('open_database', undefined));
await ctr.runStdioMcpTool({
args: '',
env: { IDB_PATH: '/other' },
params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
toolName: 'open_database',
- } as any);
+ });
expect(mcpClientMocks).toHaveBeenCalledTimes(2);
});
@@ -238,9 +176,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
const fresh = makeClientInstance('fresh');
mcpClientMocks.mockReturnValueOnce(stale).mockReturnValueOnce(fresh).mockReturnValue(fresh);
- const result = await ctr.runStdioMcpTool(
- createStdioToolInput('execute_python', undefined) as any,
- );
+ const result = await ctr.runStdioMcpTool(createStdioToolInput('execute_python', undefined));
// The stale session was evicted + disconnected, the retry succeeded.
expect(stale.disconnect).toHaveBeenCalledTimes(1);
@@ -248,7 +184,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
expect(result.success).toBe(true);
// Next call reuses the replacement session (pool stays warm).
- await ctr.runStdioMcpTool(createStdioToolInput('execute_python', undefined) as any);
+ await ctr.runStdioMcpTool(createStdioToolInput('execute_python', undefined));
expect(mcpClientMocks).toHaveBeenCalledTimes(2);
});
@@ -264,7 +200,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
});
await expect(
- ctr.runStdioMcpTool(createStdioToolInput('execute_python', undefined) as any),
+ ctr.runStdioMcpTool(createStdioToolInput('execute_python', undefined)),
).rejects.toThrow('Session not found');
});
@@ -276,7 +212,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
mcpClientMocks.mockReturnValue(pooled);
await expect(
- ctr.runStdioMcpTool(createStdioToolInput('execute_python', undefined) as any),
+ ctr.runStdioMcpTool(createStdioToolInput('execute_python', undefined)),
).rejects.toThrow('no open database instance');
// App-level failure: no eviction, no disconnect, no second invocation.
@@ -294,10 +230,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
});
mcpClientMocks.mockReturnValue(pooled);
// Simulate media upload failure inside processContentBlocks.
- (ctr as any).app.getService = vi.fn(() => ({
- getFileHTTPURL: vi.fn(),
- uploadFile: vi.fn().mockRejectedValue(new Error('upload unavailable')),
- }));
+ uploadMedia.mockRejectedValue(new Error('upload unavailable'));
await expect(
ctr.runStdioMcpTool({
@@ -305,7 +238,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
env: undefined,
params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
toolName: 'render_screenshot',
- } as any),
+ }),
).rejects.toThrow('upload unavailable');
// The tool ran exactly once β€” its side effect must not be re-applied.
@@ -321,37 +254,18 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
env: undefined,
params: { args: ['--port', '8080', 'serve'], command: 'svc', name: 'svc' },
toolName: 'ping',
- } as any);
+ });
await ctr.runStdioMcpTool({
args: '',
env: undefined,
params: { args: ['serve', '--port', '8080'], command: 'svc', name: 'svc' },
toolName: 'ping',
- } as any);
+ });
// Same tokens, different order β†’ distinct sessions, never reused.
expect(mcpClientMocks).toHaveBeenCalledTimes(2);
});
- it('evicts the pooled client when listManifests fails on a stale session', async () => {
- const seeded = makeClientInstance('seeded');
- seeded.listManifests.mockRejectedValue(
- new SdkError(SdkErrorCode.ConnectionClosed, 'Connection closed'),
- );
- mcpClientMocks.mockReturnValue(seeded);
-
- await expect(
- ctr.getStdioMcpServerManifest({
- args: ['--stdio'],
- command: 'ida-mcp',
- name: 'ida-mcp',
- } as any),
- ).rejects.toThrow('Connection closed');
-
- // Broken session evicted + disconnected, so the next refresh starts fresh.
- expect(seeded.disconnect).toHaveBeenCalledTimes(1);
- });
-
it('does NOT retry on a generic JSON-RPC -32000 app-level error (no double side effects)', async () => {
const pooled = makeClientInstance('pooled');
// Generic -32000 is the server-side application error range β€” a mutating
@@ -362,7 +276,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
mcpClientMocks.mockReturnValue(pooled);
await expect(
- ctr.runStdioMcpTool(createStdioToolInput('delete_record', undefined) as any),
+ ctr.runStdioMcpTool(createStdioToolInput('delete_record', undefined)),
).rejects.toThrow('tool execution failed');
// Exactly one invocation, no eviction, no disconnect.
@@ -388,7 +302,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
return instance;
});
- const params = createStdioToolInput('open_database', undefined) as any;
+ const params = createStdioToolInput('open_database', undefined);
const first = ctr.runStdioMcpTool(params);
// Let the first call reach its pending initialize() before the second.
@@ -422,7 +336,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
.mockReturnValue(replacement);
await expect(
- ctr.runStdioMcpTool(createStdioToolInput('execute_python', undefined) as any),
+ ctr.runStdioMcpTool(createStdioToolInput('execute_python', undefined)),
).rejects.toThrow('Session not found');
// Both the stale session and the proven-dead replacement were evicted.
@@ -443,7 +357,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
.mockReturnValueOnce(replacement) // single-flight creates ONE replacement
.mockReturnValue(replacement);
- const params = createStdioToolInput('execute_python', undefined) as any;
+ const params = createStdioToolInput('execute_python', undefined);
// Two concurrent calls share the stale session; both fail stale and both
// enter the retry path.
@@ -480,9 +394,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
mcpClientMocks.mockReturnValueOnce(stale).mockReturnValueOnce(fresh).mockReturnValue(fresh);
// Post-processing (media upload) fails AFTER the tool succeeded.
- const uploadSpy = vi
- .spyOn(ctr as any, 'uploadMcpMediaBlock')
- .mockRejectedValue(new Error('upload failed'));
+ const uploadSpy = uploadMedia.mockRejectedValue(new Error('upload failed'));
await expect(
ctr.runStdioMcpTool({
@@ -490,7 +402,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
env: undefined,
params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
toolName: 'render_chart',
- } as any),
+ }),
).rejects.toThrow('upload failed');
uploadSpy.mockRestore();
@@ -518,7 +430,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
env: { TOKEN: 'v1' },
params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
toolName: 'open_database',
- } as any;
+ };
await ctr.runStdioMcpTool(oldParams);
// User rotates the token β†’ new cache key, new session; the old entry
@@ -528,7 +440,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
env: { TOKEN: 'v2' },
params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
toolName: 'open_database',
- } as any;
+ };
await ctr.runStdioMcpTool(newParams);
expect(mcpClientMocks).toHaveBeenCalledTimes(2);
@@ -556,10 +468,10 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
const b = makeClientInstance('b');
mcpClientMocks.mockReturnValueOnce(a).mockReturnValueOnce(b);
- await ctr.runStdioMcpTool(createStdioToolInput('t', undefined) as any);
- await ctr.runStdioMcpTool(createStdioToolInput('t', { TOKEN: 'x' }) as any);
+ await ctr.runStdioMcpTool(createStdioToolInput('t', undefined));
+ await ctr.runStdioMcpTool(createStdioToolInput('t', { TOKEN: 'x' }));
- await (ctr as any).disposeAllPooledClients();
+ await ctr.disposeAllPooledClients();
expect(a.disconnect).toHaveBeenCalledTimes(1);
expect(b.disconnect).toHaveBeenCalledTimes(1);
@@ -579,23 +491,24 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
mcpClientMocks.mockImplementation(() => shared);
let releaseManifest!: () => void;
- shared.listManifests.mockImplementation(
+ const listTools = vi.fn(
() =>
- new Promise<void>((resolve) => {
- releaseManifest = resolve;
+ new Promise<never[]>((resolve) => {
+ releaseManifest = () => resolve([]);
}),
);
+ Object.assign(shared, { listTools });
- const params = createStdioToolInput('t', undefined) as any;
+ const params = createStdioToolInput('t', undefined);
- const manifestPromise = ctr.getStdioMcpServerManifest(params);
+ const manifestPromise = ctr.listStdioTools(params);
await vi.waitFor(() => {
- expect(shared.listManifests).toHaveBeenCalled();
+ expect(listTools).toHaveBeenCalled();
});
// First tool call: stale error β†’ evicts the shared client β†’ retry on
// the replacement (same mocked instance) β†’ stale again β†’ propagates.
- await expect(ctr.runStdioMcpTool({ ...params, toolName: 'explode' } as any)).rejects.toThrow(
+ await expect(ctr.runStdioMcpTool({ ...params, toolName: 'explode' })).rejects.toThrow(
'Session not found',
);
// Eviction happened (client left the pool) but the disconnect is
@@ -633,7 +546,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
}),
);
- const params = createStdioToolInput('t', undefined) as any;
+ const params = createStdioToolInput('t', undefined);
const callPromise = ctr.runStdioMcpTool(params);
await vi.advanceTimersByTimeAsync(31 * 60 * 1000);
@@ -660,10 +573,10 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
env: { TOKEN: 'secret-v1' },
params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
toolName: 't',
- } as any),
+ }),
).rejects.toThrow('spawn failed');
- const clocks = (ctr as any).mcpClientLastUsedAt as Map<string, number>;
+ const clocks = ctr.mcpClientLastUsedAt;
expect(clocks.size).toBe(0);
});
@@ -681,7 +594,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
mcpClientMocks.mockReturnValueOnce(dead).mockReturnValue(replacement);
await expect(
- ctr.runStdioMcpTool(createStdioToolInput('delete_record', undefined) as any),
+ ctr.runStdioMcpTool(createStdioToolInput('delete_record', undefined)),
).rejects.toThrow('Connection closed');
// Dead session evicted + disconnected; the failure was still surfaced
@@ -692,7 +605,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
expect(mcpClientMocks).toHaveBeenCalledTimes(1);
// The next call builds a FRESH session instead of reusing the corpse.
- await ctr.runStdioMcpTool(createStdioToolInput('open_database', undefined) as any);
+ await ctr.runStdioMcpTool(createStdioToolInput('open_database', undefined));
expect(mcpClientMocks).toHaveBeenCalledTimes(2);
expect(replacement.callTool).toHaveBeenCalledTimes(1);
});
@@ -707,7 +620,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
);
mcpClientMocks.mockReturnValue(pooled);
- await expect(ctr.runStdioMcpTool(createStdioToolInput('t', undefined) as any)).rejects.toThrow(
+ await expect(ctr.runStdioMcpTool(createStdioToolInput('t', undefined))).rejects.toThrow(
'Connection closed by tool sandbox',
);
@@ -739,7 +652,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
}),
);
- const longParams = createStdioToolInput('t', undefined) as any;
+ const longParams = createStdioToolInput('t', undefined);
const callPromise = ctr.runStdioMcpTool(longParams);
await vi.advanceTimersByTimeAsync(40 * 60 * 1000);
await callPromise;
@@ -752,7 +665,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
env: { TOKEN: 'other' },
params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
toolName: 't',
- } as any);
+ });
expect(longCall.disconnect).not.toHaveBeenCalled();
} finally {
@@ -760,7 +673,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
}
});
- it('will-quit disposal initiates every disconnect synchronously (Electron cannot await listeners)', async () => {
+ it('dispose initiates every disconnect synchronously (Electron cannot await listeners)', async () => {
const a = makeClientInstance('a');
const b = makeClientInstance('b');
let releaseA: () => void = () => {};
@@ -772,14 +685,14 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
});
mcpClientMocks.mockReturnValueOnce(a).mockReturnValueOnce(b);
- await ctr.runStdioMcpTool(createStdioToolInput('t', undefined) as any);
- await ctr.runStdioMcpTool(createStdioToolInput('t', { TOKEN: 'x' }) as any);
+ await ctr.runStdioMcpTool(createStdioToolInput('t', undefined));
+ await ctr.runStdioMcpTool(createStdioToolInput('t', { TOKEN: 'x' }));
// The disposal promise resolves only after BOTH teardowns settle, and
// both were initiated up front (b's disconnect is called before a's
// gated one resolves) β€” so Electron's non-awaiting will-quit still
// reaches every stdio child.
- const disposal = (ctr as any).disposeAllPooledClients();
+ const disposal = ctr.disposeAllPooledClients();
await vi.waitFor(() => expect(b.disconnect).toHaveBeenCalledTimes(1));
expect(a.disconnect).toHaveBeenCalledTimes(1);
releaseA();
diff --git a/packages/device-mcp/src/runtime.ts b/packages/device-mcp/src/runtime.ts
new file mode 100644
index 00000000000..c4d2c43826c
--- /dev/null
+++ b/packages/device-mcp/src/runtime.ts
@@ -0,0 +1,600 @@
+import {
+ getMcpServerFingerprint,
+ isMcpThreadEntrypoint,
+ lacksUiResourceMeta,
+ withListingUiMeta,
+} from '@lobechat/const/mcpApp';
+
+import type { MCPClient } from './client';
+import {
+ contentBlocksToMarkdown,
+ type McpMediaUploader,
+ type McpMediaUrlResolver,
+ uploadMediaBlocks,
+} from './content';
+import {
+ isDeadTransportError,
+ isStaleSessionError,
+ serializeMcpClientParams,
+} from './sessionGuards';
+import type { MCPClientParams, ToolCallContent, ToolCallResult } from './types';
+
+const loadMcpClient = () => import('./client');
+
+export interface DeviceMcpLogger {
+ error: (message: string, ...args: unknown[]) => void;
+ warn: (message: string, ...args: unknown[]) => void;
+}
+
+export interface DeviceMcpRuntimeOptions {
+ /** `clientInfo.name` every session announces. */
+ clientName?: string;
+ /** Resolves an uploaded media key to the URL the model's markdown links to. */
+ getMediaUrl: McpMediaUrlResolver;
+ logger?: DeviceMcpLogger;
+ /** Idle sessions older than this are disconnected at the next sweep. */
+ poolIdleTtlMs?: number;
+ /** Default `tools/call` deadline; a call's own `timeoutMs` wins. */
+ toolTimeoutMs?: number;
+ /** Stores a tool result's image / audio bytes and answers their key. */
+ uploadMedia: McpMediaUploader;
+}
+
+/** Whether MCP Apps are announced on the session a call runs on. */
+export interface McpSessionOptions {
+ /** Announce MCP Apps on the session: the user has the `mcp_apps` flag. */
+ mcpApps?: boolean;
+}
+
+/** How a tool call runs: whether a view made it, and whether MCP Apps are on. */
+export interface McpCallOptions extends McpSessionOptions {
+ /** An MCP App view's `tools/call`: only tools visible to the app run. */
+ fromApp?: boolean;
+ fromEntrypoint?: boolean;
+ /** This call's deadline, e.g. the one a tunneled call carries. */
+ timeoutMs?: number;
+}
+
+export interface McpToolOutput {
+ content: string;
+ error?: { message: string; name: string };
+ state: unknown;
+ success: boolean;
+}
+
+const DEFAULT_POOL_IDLE_TTL_MS = 30 * 60 * 1000;
+
+const noopLogger: DeviceMcpLogger = { error: () => {}, warn: () => {} };
+
+const safeParseToRecord = (value: unknown): Record<string, unknown> => {
+ if (value && typeof value === 'object' && !Array.isArray(value))
+ return value as Record<string, unknown>;
+ if (typeof value === 'string') {
+ try {
+ const parsed = JSON.parse(value) as unknown;
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
+ return parsed as Record<string, unknown>;
+ } catch {
+ // ignore
+ }
+ }
+ return {};
+};
+
+/**
+ * An `MCPConnectionError` carries the stdio server's stderr tail; fold it into
+ * the message so the caller (and the model) sees why the process failed.
+ * Other errors pass through unchanged.
+ */
+export const withStdioOutput = async (error: unknown): Promise<unknown> => {
+ const { MCPConnectionError } = await loadMcpClient();
+ if (error instanceof MCPConnectionError && error.stderrLogs.length > 0) {
+ const enhanced = new Error(
+ `${error.message}\n\n--- STDIO Process Output ---\n${error.stderrLogs.join('\n')}`,
+ );
+ enhanced.name = error.name;
+ return enhanced;
+ }
+ return error;
+};
+
+/**
+ * Runs MCP servers only the user's machine can reach β€” stdio binaries and
+ * localhost / LAN HTTP endpoints β€” for every device host (the desktop app's
+ * main process and `lh connect`), so both execute a tunneled call the same way.
+ *
+ * Sessions are pooled per connection params. Stateful stdio servers (e.g. IDA's
+ * `ida-mcp`: `open_database` sets a current database that later
+ * `execute_python` calls depend on) lose their in-process state when the
+ * session is torn down between calls, so one session is reused per unique
+ * params and rebuilt only when a call fails on it.
+ */
+export class DeviceMcpRuntime {
+ private readonly options: DeviceMcpRuntimeOptions;
+ private readonly logger: DeviceMcpLogger;
+ private readonly poolIdleTtlMs: number;
+
+ private pool = new Map<string, MCPClient>();
+ /** The pool key each client was created under, so eviction finds its own entry. */
+ private clientKeys = new WeakMap<MCPClient, string>();
+ private initialization = new Map<string, Promise<MCPClient>>();
+ private lastUsedAt = new Map<string, number>();
+ // In-flight call tracking: eviction and idle reaping are deferred while a
+ // client holds any lease; release performs a pending eviction disconnect.
+ private leases = new Map<MCPClient, number>();
+ private pendingDisconnect = new Set<MCPClient>();
+
+ constructor(options: DeviceMcpRuntimeOptions) {
+ this.options = options;
+ this.logger = options.logger ?? noopLogger;
+ /**
+ * Rationale for the idle TTL: stdio subprocesses are cheap to respawn but
+ * leak when kept forever β€” a changed token/env/command produces a NEW
+ * cache key while the old entry stays connected for the life of the host
+ * process. It is deliberately long (30 min ≫ any realistic think-turn
+ * between tool calls) so actively used stateful sessions are never reaped
+ * mid-workflow: every acquire refreshes the clock.
+ */
+ this.poolIdleTtlMs = options.poolIdleTtlMs ?? DEFAULT_POOL_IDLE_TTL_MS;
+ }
+
+ /** A fresh, unpooled session. The caller owns it and must disconnect it. */
+ async createClient(params: MCPClientParams, { mcpApps = false }: McpSessionOptions = {}) {
+ const { MCPClient } = await loadMcpClient();
+ const client = new MCPClient(params, {
+ clientName: this.options.clientName,
+ mcpApps,
+ toolTimeoutMs: this.options.toolTimeoutMs,
+ });
+ await client.initialize();
+ return client;
+ }
+
+ /**
+ * Disconnect every pooled session so no MCP subprocess outlives the host.
+ * Every disconnect is initiated synchronously before the first await, so a
+ * host that cannot await its shutdown listener (Electron's `will-quit`)
+ * still reaches every child. Never throws.
+ */
+ async dispose(): Promise<void> {
+ const entries = [...this.pool.entries()];
+ this.pool.clear();
+ this.lastUsedAt.clear();
+ const teardowns = entries.map(([, client]) =>
+ client.disconnect().catch((error: unknown) => {
+ this.logger.warn('Failed to disconnect MCP client on dispose:', error);
+ }),
+ );
+ await Promise.all(teardowns);
+ }
+
+ /**
+ * Disconnect and drop every pooled session that has been idle for longer
+ * than the TTL. Never throws.
+ */
+ private async reapIdleClients(): Promise<void> {
+ const now = Date.now();
+ for (const [key, client] of this.pool) {
+ const lastUsed = this.lastUsedAt.get(key) ?? 0;
+ if (now - lastUsed < this.poolIdleTtlMs) continue;
+ // A session with active in-flight calls is still working: disconnecting
+ // it mid-call would kill a valid long-running tool invocation (the
+ // idle clock only refreshes at acquisition, not during the call).
+ if (this.leases.has(client)) continue;
+ this.pool.delete(key);
+ this.lastUsedAt.delete(key);
+ try {
+ await client.disconnect();
+ } catch (error) {
+ this.logger.warn('Failed to reap idle MCP client:', error);
+ }
+ }
+ }
+
+ /**
+ * Return a pooled client for the given params, creating (and caching) a new
+ * one when the pool has no healthy entry. Callers must NOT disconnect the
+ * returned client β€” pooled sessions outlive a single tool call.
+ */
+ async acquireClient(
+ params: MCPClientParams,
+ { mcpApps = false }: McpSessionOptions = {},
+ ): Promise<MCPClient> {
+ // Sessions that announce MCP Apps and ones that don't are pooled apart
+ const key = `${serializeMcpClientParams(params)}${mcpApps ? '#mcp-apps' : ''}`;
+
+ // Every acquire refreshes the session's idle clock (fire-and-forget β€”
+ // reaping must never delay or fail the tool call it runs alongside).
+ this.lastUsedAt.set(key, Date.now());
+ void this.reapIdleClients().catch(() => {});
+
+ const cached = this.pool.get(key);
+ if (cached) return cached;
+
+ // Single-flight per key: concurrent manifest discovery + tool call on the
+ // same uncached params must share one initialization, not spawn two
+ // processes where the later map write silently replaces the first
+ // (stranding whatever state the losing client had established).
+ const inFlight = this.initialization.get(key);
+ if (inFlight) return inFlight;
+
+ const creating = this.createClient(params, { mcpApps })
+ .then((client) => {
+ this.clientKeys.set(client, key);
+ this.pool.set(key, client);
+ this.lastUsedAt.set(key, Date.now());
+ return client;
+ })
+ .catch((error) => {
+ // The acquire-time clock is an orphan when creation fails: failed
+ // configs (serialized keys contain env values) must not accumulate.
+ this.lastUsedAt.delete(key);
+ throw error;
+ })
+ .finally(() => {
+ this.initialization.delete(key);
+ });
+ this.initialization.set(key, creating);
+ return creating;
+ }
+
+ /**
+ * Run `fn` while holding a lease: eviction and idle reaping are deferred
+ * while any lease is active. The last release refreshes the idle clock
+ * (a call may outlast the TTL β€” the session is fresh the moment its work
+ * ends, not when it started) and then performs any pending disconnect.
+ */
+ async withClientLease<T>(client: MCPClient, fn: () => Promise<T>): Promise<T> {
+ this.leases.set(client, (this.leases.get(client) ?? 0) + 1);
+ try {
+ return await fn();
+ } finally {
+ const remaining = (this.leases.get(client) ?? 1) - 1;
+ if (remaining > 0) this.leases.set(client, remaining);
+ else {
+ this.leases.delete(client);
+ for (const [key, pooled] of this.pool) {
+ if (pooled === client) this.lastUsedAt.set(key, Date.now());
+ }
+ if (this.pendingDisconnect.delete(client)) {
+ try {
+ await client.disconnect();
+ } catch (error) {
+ this.logger.warn('Failed to disconnect evicted MCP client:', error);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Drop a pooled session after a failed call so the next attempt starts
+ * fresh. Never throws β€” the original call error matters more than cleanup.
+ *
+ * Requires the exact client the failed call ran on: without that identity
+ * we must not disconnect anything, or a concurrent same-key recreate (call
+ * B installing its replacement while call A's initialization fails) would
+ * get its live session killed while the pool keeps pointing at it β€” a
+ * permanently dead pooled entry until restart.
+ */
+ async evictClient(params: MCPClientParams, client?: MCPClient): Promise<void> {
+ if (!client) return;
+ const key = this.clientKeys.get(client) ?? serializeMcpClientParams(params);
+ const pooled = this.pool.get(key);
+ // Only evict when the failing call ran on the pooled instance β€”
+ // a concurrent recreate may have already replaced it.
+ if (pooled && pooled === client) {
+ this.pool.delete(key);
+ this.lastUsedAt.delete(key);
+ }
+ // Defer the disconnect while the client still has in-flight calls:
+ // manifest discovery and tool execution share one pooled session, so an
+ // eviction triggered by one of them must not abort the other mid-call.
+ // The last lease release performs the deferred disconnect.
+ if (this.leases.has(client)) {
+ this.pendingDisconnect.add(client);
+ return;
+ }
+ try {
+ await client.disconnect();
+ } catch (error) {
+ this.logger.warn('Failed to disconnect evicted MCP client:', error);
+ }
+ }
+
+ /**
+ * Every tool the server lists, on the pooled session (stdio) or a one-shot
+ * one (HTTP, which keeps no process state worth reusing).
+ */
+ async listTools(params: MCPClientParams, options: McpSessionOptions = {}) {
+ if (params.type === 'http') {
+ const client = await this.createClient(params, options);
+ try {
+ return await client.listTools();
+ } finally {
+ await client.disconnect();
+ }
+ }
+
+ let client: MCPClient | undefined;
+ try {
+ client = await this.acquireClient(params, options);
+ const pooled = client;
+ return await this.withClientLease(pooled, () => pooled.listTools());
+ } catch (error) {
+ // Drop a broken pooled session so the next refresh starts fresh.
+ await this.evictClient(params, client);
+ throw await withStdioOutput(error);
+ }
+ }
+
+ /**
+ * Read an MCP Apps `ui://` resource, so the chat can render a tool result's
+ * interactive view. Reading is idempotent, so unlike tool calls a dead
+ * transport is retried too: the stale session is evicted and the read runs
+ * once on a fresh one.
+ */
+ async readUiResource(params: MCPClientParams, uri: string) {
+ if (!uri?.startsWith('ui://')) throw new Error('Only ui:// resources can be read');
+
+ const read = (client: MCPClient) =>
+ this.withClientLease(client, async () => {
+ const result = await client.readResource(uri);
+ // A view's _meta.ui may be declared once, on its resources/list entry
+ if (!lacksUiResourceMeta(result, true)) return result;
+
+ const listed = await client.listResources().catch((error) => {
+ this.logger.warn('Failed to list resources for MCP App metadata:', { error });
+ return [];
+ });
+ return withListingUiMeta(result, uri, listed, true);
+ });
+ const isSessionFailure = (error: unknown) =>
+ isStaleSessionError(error) || isDeadTransportError(error);
+
+ // Views are read only while MCP Apps are on, on a session that announces them
+ const client = await this.acquireClient(params, { mcpApps: true });
+ try {
+ return await read(client);
+ } catch (error) {
+ if (!isSessionFailure(error)) throw error;
+
+ this.logger.warn(
+ 'MCP App resource read failed on pooled session, retrying with a fresh one:',
+ {
+ message: (error as Error).message,
+ },
+ );
+ await this.evictClient(params, client);
+ const retryClient = await this.acquireClient(params, { mcpApps: true });
+ try {
+ return await read(retryClient);
+ } catch (retryError) {
+ if (isSessionFailure(retryError)) await this.evictClient(params, retryClient);
+ throw retryError;
+ }
+ }
+ }
+
+ /** Fails closed: a view's call is refused while the tool's visibility can't be learned. */
+ private async isToolCallableByApp(client: MCPClient, toolName: string) {
+ try {
+ return await client.isToolCallableByApp(toolName);
+ } catch (error) {
+ // A broken session is the call's own failure: let runTool evict and
+ // recover it, or every later view call would reuse the dead session
+ if (isStaleSessionError(error, client.getProtocolEra()) || isDeadTransportError(error)) {
+ throw error;
+ }
+ this.logger.warn('Failed to resolve MCP App visibility for tool:', { error, toolName });
+ return false;
+ }
+ }
+
+ /**
+ * Fails open: while the tool's visibility can't be learned, the model's call
+ * runs as it did before MCP Apps.
+ */
+ private async isToolHiddenFromModel(client: MCPClient, toolName: string) {
+ try {
+ return await client.isToolHiddenFromModel(toolName);
+ } catch (error) {
+ // A broken session is the call's own failure, recovered by runTool
+ if (isStaleSessionError(error, client.getProtocolEra()) || isDeadTransportError(error)) {
+ throw error;
+ }
+ this.logger.warn('Failed to resolve MCP App visibility for tool:', { error, toolName });
+ return false;
+ }
+ }
+
+ /** Never fails the tool call: an unknown UI resource only means no interactive view. */
+ private async getToolUiResourceUri(client: MCPClient, toolName: string) {
+ try {
+ return await client.getToolUiResourceUri(toolName);
+ } catch (error) {
+ this.logger.warn('Failed to resolve MCP App resource for tool:', { error, toolName });
+ return undefined;
+ }
+ }
+
+ private async callOnClient(
+ client: MCPClient,
+ params: MCPClientParams,
+ toolName: string,
+ args: Record<string, unknown>,
+ { fromApp = false, fromEntrypoint = false, mcpApps = false, timeoutMs }: McpCallOptions,
+ ): Promise<McpToolOutput> {
+ if (
+ fromEntrypoint &&
+ !(mcpApps && isMcpThreadEntrypoint(await client.getToolUiMeta(toolName)))
+ ) {
+ const message = 'This tool does not declare an enabled thread entrypoint.';
+ return {
+ content: message,
+ state: { content: [{ text: message, type: 'text' }], isError: true },
+ success: false,
+ };
+ }
+ // A view may only call tools whose visibility includes the app,
+ // and only while MCP Apps are on
+ if (
+ !fromEntrypoint &&
+ fromApp &&
+ !(mcpApps && (await this.isToolCallableByApp(client, toolName)))
+ ) {
+ const message = `The tool "${toolName}" can't be called from an interactive view.`;
+ return {
+ content: message,
+ error: { message, name: 'MCPToolError' },
+ state: { content: [{ text: message, type: 'text' }], isError: true },
+ success: false,
+ };
+ }
+ // A tool the server keeps from the model is its views' alone, even
+ // when the model names it (e.g. from an earlier turn)
+ if (
+ !fromEntrypoint &&
+ !fromApp &&
+ mcpApps &&
+ (await this.isToolHiddenFromModel(client, toolName))
+ ) {
+ const message = `The tool "${toolName}" can only be called from its interactive view.`;
+ return {
+ content: message,
+ error: { message, name: 'MCPToolError' },
+ state: { content: [{ text: message, type: 'text' }], isError: true },
+ success: false,
+ };
+ }
+ const uiResourceUri = mcpApps ? await this.getToolUiResourceUri(client, toolName) : undefined;
+ const preferredModelDisplayMode = uiResourceUri
+ ? (await client.getToolUiMeta(toolName))?.preferredModelDisplayMode
+ : undefined;
+ const raw = (
+ timeoutMs === undefined
+ ? await client.callTool(toolName, args)
+ : await client.callTool(toolName, args, { timeoutMs })
+ ) as ToolCallResult;
+ // A view gets the tool's own MCP result: its media stays base64
+ // `data`, not the uploaded keys the chat stores and renders
+ const processed: ToolCallContent[] =
+ raw.isError || fromApp || fromEntrypoint
+ ? raw.content
+ : await uploadMediaBlocks(raw.content, this.options.uploadMedia);
+ const content =
+ fromApp || fromEntrypoint
+ ? processed.flatMap((block) => (block.type === 'text' ? [block.text] : [])).join('\n')
+ : await contentBlocksToMarkdown(processed, this.options.getMediaUrl);
+ const state = {
+ ...raw,
+ content: processed,
+ // MCP Apps: the `ui://` resource the chat renders this result with,
+ // and the server it may be read back from
+ ...(uiResourceUri &&
+ !raw.isError && {
+ mcpApp: {
+ resourceUri: uiResourceUri,
+ ...(preferredModelDisplayMode && { preferredModelDisplayMode }),
+ server: await getMcpServerFingerprint(params),
+ },
+ }),
+ };
+ return {
+ content,
+ ...(raw.isError ? { error: { message: content, name: 'MCPToolError' } } : {}),
+ state,
+ success: raw.isError !== true,
+ };
+ }
+
+ /**
+ * Call one tool on the pooled session for `params`. Returns the result
+ * envelope; throws on failure so each host can shape its own error.
+ *
+ * Retries once on a fresh session β€” but only for confirmed stale-session /
+ * transport failures that happen before a tool result was produced.
+ * App-level failures (tool rejected the args, media post-processing
+ * failed, …) are surfaced as-is: re-running a mutating tool on a generic
+ * catch could apply its side effect a second time.
+ */
+ async runTool(
+ params: MCPClientParams,
+ toolName: string,
+ rawArgs: unknown,
+ options: McpCallOptions = {},
+ ): Promise<McpToolOutput> {
+ const { mcpApps = false } = options;
+ try {
+ const args = options.fromEntrypoint ? {} : safeParseToRecord(rawArgs);
+
+ // The failing client is tagged onto the error so eviction carries an
+ // identity guard.
+ const runOn = (client: MCPClient) =>
+ this.withClientLease(client, async () => {
+ try {
+ return await this.callOnClient(client, params, toolName, args, options);
+ } catch (error) {
+ throw Object.assign(error instanceof Error ? error : new Error(String(error)), {
+ ranOnClient: client,
+ });
+ }
+ });
+
+ try {
+ return await runOn(await this.acquireClient(params, { mcpApps }));
+ } catch (firstError) {
+ const failedClient = (firstError as { ranOnClient?: MCPClient })?.ranOnClient;
+ if (!isStaleSessionError(firstError, failedClient?.getProtocolEra())) {
+ // A dead stdio subprocess must still be evicted even though the
+ // failed call is NOT replayed: the request may have reached the
+ // server before the pipe died, so re-running a mutating tool
+ // could apply its side effect twice. Without eviction the dead
+ // client stays pooled and every later same-key acquisition
+ // returns the same unusable session until restart.
+ if (isDeadTransportError(firstError)) {
+ this.logger.warn('MCP tool call failed on a dead transport, evicting pooled session:', {
+ message: (firstError as Error).message,
+ toolName,
+ });
+ await this.evictClient(params, failedClient);
+ } else {
+ this.logger.warn('MCP tool call failed (no retry for app-level error):', {
+ message: (firstError as Error).message,
+ toolName,
+ });
+ }
+ throw firstError;
+ }
+ this.logger.warn('MCP tool call failed on pooled session, retrying with a fresh one:', {
+ message: (firstError as Error).message,
+ toolName,
+ });
+ await this.evictClient(params, failedClient);
+ // Route replacement creation through acquireClient: it single-flights
+ // per key, so two concurrent calls that shared the same stale client
+ // and both failed build ONE replacement process.
+ const retryClient = await this.acquireClient(params, { mcpApps });
+ try {
+ return await runOn(retryClient);
+ } catch (retryError) {
+ // Evict the replacement on a transport-level failure. A
+ // post-processing failure after a SUCCESSFUL tool call is not a
+ // session problem β€” the tool already ran, so the healthy
+ // replacement stays pooled.
+ if (
+ isStaleSessionError(retryError, retryClient.getProtocolEra()) ||
+ isDeadTransportError(retryError)
+ ) {
+ await this.evictClient(params, retryClient);
+ }
+ throw retryError;
+ }
+ }
+ } catch (error) {
+ const enhanced = await withStdioOutput(error);
+ this.logger.error('callTool failed:', enhanced);
+ throw enhanced;
+ }
+ }
+}
diff --git a/apps/desktop/src/main/libs/mcp/sessionGuards.test.ts b/packages/device-mcp/src/sessionGuards.test.ts
similarity index 100%
rename from apps/desktop/src/main/libs/mcp/sessionGuards.test.ts
rename to packages/device-mcp/src/sessionGuards.test.ts
diff --git a/apps/desktop/src/main/libs/mcp/sessionGuards.ts b/packages/device-mcp/src/sessionGuards.ts
similarity index 100%
rename from apps/desktop/src/main/libs/mcp/sessionGuards.ts
rename to packages/device-mcp/src/sessionGuards.ts
diff --git a/apps/desktop/src/main/libs/mcp/types.ts b/packages/device-mcp/src/types.ts
similarity index 100%
rename from apps/desktop/src/main/libs/mcp/types.ts
rename to packages/device-mcp/src/types.ts
diff --git a/packages/device-mcp/vitest.config.mts b/packages/device-mcp/vitest.config.mts
new file mode 100644
index 00000000000..4ac6027d578
--- /dev/null
+++ b/packages/device-mcp/vitest.config.mts
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ environment: 'node',
+ },
+});
diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts
index 500433586df..1fd68becd31 100644
--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts
+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts
@@ -307,6 +307,28 @@ const mergePathValues = (...values: Array<string | undefined>): string | undefin
return segments.length > 0 ? segments.join(path.delimiter) : undefined;
};
+/**
+ * The PATH a child spawned by this process should search: the login shell's
+ * PATH (the Windows registry's on Windows) merged ahead of the inherited one.
+ *
+ * Use when: a long-lived host started by a service manager (launchd, systemd)
+ * spawns user tools β€” `npx`, `uvx`, nvm-installed binaries β€” that only the
+ * user's login shell puts on PATH.
+ * Returns: the inherited PATH when nothing could be recovered; never throws.
+ */
+export const resolveUserSpawnPath = async (
+ currentPath: string | undefined = process.env.PATH,
+): Promise<string | undefined> => {
+ try {
+ const recovered = isWindows()
+ ? await getWindowsRegistryPath()
+ : await getCurrentLoginShellPath();
+ return mergePathValues(recovered, currentPath) ?? currentPath;
+ } catch {
+ return currentPath;
+ }
+};
+
const recoverProbeEnvironment = async (
probeEnv?: NodeJS.ProcessEnv,
): Promise<RecoveredProbeEnvironment | undefined> => {