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(gateway): tunnel stdio MCP tool calls to the device (#15469)

Arvin Xuf35f984268a0
diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.ts
index fd561e04fc7..4c01a24011c 100644
--- a/packages/device-gateway-client/src/http.test.ts
+++ b/packages/device-gateway-client/src/http.test.ts
@@ -291,6 +291,72 @@ describe('GatewayHttpClient', () => {
});
});
+ describe('executeMcpCall', () => {
+ it('should tunnel the call over the tool-call relay with stdio params', async () => {
+ mockFetch({
+ json: vi.fn().mockResolvedValue({
+ content: 'stock data',
+ state: { rows: 3 },
+ success: true,
+ }),
+ ok: true,
+ });
+
+ const result = await client.executeMcpCall({
+ apiName: 'getStock',
+ arguments: '{"symbol":"AAPL"}',
+ deviceId: 'device-1',
+ identifier: 'kimi-datasource',
+ params: {
+ args: ['stock-mcp'],
+ command: 'npx',
+ env: { TOKEN: 'secret' },
+ name: 'kimi-datasource',
+ type: 'stdio',
+ },
+ userId: 'user-1',
+ });
+
+ expect(result).toEqual({
+ content: 'stock data',
+ error: undefined,
+ state: { rows: 3 },
+ success: true,
+ });
+
+ // Rides the same endpoint as executeToolCall; the device routes on
+ // the presence of `toolCall.params`.
+ const [url, init] = vi.mocked(fetch).mock.calls[0];
+ expect(url).toBe('https://gateway.test.com/api/device/tool-call');
+ const body = JSON.parse((init as RequestInit).body as string);
+ expect(body.toolCall.identifier).toBe('kimi-datasource');
+ expect(body.toolCall.params.command).toBe('npx');
+ expect(body.toolCall.params.env).toEqual({ TOKEN: 'secret' });
+ // Routing fields are lifted out of the call descriptor, not tunneled.
+ expect(body.toolCall.deviceId).toBeUndefined();
+ expect(body.deviceId).toBe('device-1');
+ });
+
+ it('should surface non-ok responses as a failed result', async () => {
+ mockFetch({
+ ok: false,
+ status: 503,
+ text: vi.fn().mockResolvedValue('DEVICE_OFFLINE'),
+ });
+
+ const result = await client.executeMcpCall({
+ apiName: 'getStock',
+ arguments: '{}',
+ identifier: 'kimi-datasource',
+ params: { args: [], command: 'npx', name: 'kimi-datasource', type: 'stdio' },
+ userId: 'user-1',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe('DEVICE_OFFLINE');
+ });
+ });
+
describe('executeMessageApi', () => {
it('should return message API result on success', async () => {
mockFetch({
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index 2ba375aba84..b1c83f674ee 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -1,4 +1,4 @@
-import type { DeviceSystemInfo, GatewayDevice } from './types';
+import type { DeviceSystemInfo, GatewayDevice, GatewayMcpStdioParams } from './types';
const DEFAULT_GATEWAY_TOOL_CALL_TIMEOUT_MS = 30_000;
const HTTP_CALL_TIMEOUT_PADDING_MS = 30_000;
@@ -57,6 +57,40 @@ export class GatewayHttpClient {
async executeToolCall(
params: { deviceId?: string; timeout?: number; userId: string },
toolCall: { apiName: string; arguments: string; identifier: string },
+ ): Promise<DeviceToolCallResult> {
+ return this.postToolCall(params, toolCall);
+ }
+
+ /**
+ * Tunnel a stdio MCP tool call to the device. Rides the same
+ * `/api/device/tool-call` relay as {@link executeToolCall} β€” the gateway
+ * forwards `toolCall` opaquely β€” but carries `params` (the stdio connection
+ * params) so the device routes it to its local MCP client (spawning the
+ * stdio server) rather than the builtin local-system tool switch. The cloud
+ * server can't spawn the user's binary, so execution must happen on the
+ * device.
+ */
+ async executeMcpCall(mcpCall: {
+ apiName: string;
+ arguments: string;
+ deviceId?: string;
+ identifier: string;
+ params: GatewayMcpStdioParams;
+ timeout?: number;
+ userId: string;
+ }): Promise<DeviceToolCallResult> {
+ const { deviceId, timeout, userId, ...toolCall } = mcpCall;
+ return this.postToolCall({ deviceId, timeout, userId }, toolCall);
+ }
+
+ private async postToolCall(
+ params: { deviceId?: string; timeout?: number; userId: string },
+ toolCall: {
+ apiName: string;
+ arguments: string;
+ identifier: string;
+ params?: GatewayMcpStdioParams;
+ },
): Promise<DeviceToolCallResult> {
const timeout =
typeof params.timeout === 'number' && Number.isFinite(params.timeout)
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index 1c9445a6b92..8dced08a991 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -90,6 +90,19 @@ export interface AuthExpiredMessage {
type: 'auth_expired';
}
+/**
+ * Stdio MCP connection params forwarded to the device for a tunneled MCP tool
+ * call. The cloud server can't spawn the user's local MCP binary, so the
+ * command/args/env travel to the device, which spawns and calls it locally.
+ */
+export interface GatewayMcpStdioParams {
+ args: string[];
+ command: string;
+ env?: Record<string, string>;
+ name: string;
+ type: 'stdio';
+}
+
export interface ToolCallRequestMessage {
/** Operation that triggered the call, propagated by the gateway for tracing. */
operationId?: string;
@@ -100,6 +113,12 @@ export interface ToolCallRequestMessage {
apiName: string;
arguments: string;
identifier: string;
+ /**
+ * Present only for tunneled stdio MCP calls. When set, the device routes
+ * the call to its local MCP client (spawning the stdio server) instead of
+ * the builtin local-system tool switch.
+ */
+ params?: GatewayMcpStdioParams;
};
type: 'tool_call_request';
}
diff --git a/src/server/services/toolExecution/__tests__/deviceProxy.test.ts b/src/server/services/toolExecution/__tests__/deviceProxy.test.ts
index 418d3503d8e..749ef4aee82 100644
--- a/src/server/services/toolExecution/__tests__/deviceProxy.test.ts
+++ b/src/server/services/toolExecution/__tests__/deviceProxy.test.ts
@@ -9,6 +9,7 @@ const mockEnv = vi.hoisted(() => ({
}));
const mockClient = vi.hoisted(() => ({
+ executeMcpCall: vi.fn(),
executeMessageApi: vi.fn(),
executeToolCall: vi.fn(),
getDeviceSystemInfo: vi.fn(),
@@ -291,6 +292,73 @@ describe('DeviceProxy', () => {
});
});
+ describe('executeMcpCall', () => {
+ const mcpCall = {
+ apiName: 'getStock',
+ arguments: '{"symbol":"AAPL"}',
+ deviceId: 'dev-1',
+ identifier: 'kimi-datasource',
+ params: {
+ args: ['stock-mcp'],
+ command: 'npx',
+ env: { TOKEN: 'secret' },
+ name: 'kimi-datasource',
+ type: 'stdio' as const,
+ },
+ userId: 'user-1',
+ };
+
+ it('should return error when not configured', async () => {
+ const proxy = new DeviceProxy();
+ const result = await proxy.executeMcpCall(mcpCall);
+
+ expect(result).toEqual({
+ content: 'Device Gateway is not configured',
+ error: 'GATEWAY_NOT_CONFIGURED',
+ success: false,
+ });
+ });
+
+ it('should forward the mcp call with default timeout', async () => {
+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
+ const expected = { content: 'stock data', state: { rows: 3 }, success: true };
+ mockClient.executeMcpCall.mockResolvedValue(expected);
+
+ const proxy = new DeviceProxy();
+ const result = await proxy.executeMcpCall(mcpCall);
+
+ expect(result).toEqual(expected);
+ expect(mockClient.executeMcpCall).toHaveBeenCalledWith({ ...mcpCall, timeout: 30_000 });
+ });
+
+ it('should use custom timeout', async () => {
+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
+ mockClient.executeMcpCall.mockResolvedValue({ content: 'ok', success: true });
+
+ const proxy = new DeviceProxy();
+ await proxy.executeMcpCall(mcpCall, 60_000);
+
+ expect(mockClient.executeMcpCall).toHaveBeenCalledWith({ ...mcpCall, timeout: 60_000 });
+ });
+
+ it('should return error result on exception', async () => {
+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
+ mockClient.executeMcpCall.mockRejectedValue(new Error('connection refused'));
+
+ const proxy = new DeviceProxy();
+ const result = await proxy.executeMcpCall(mcpCall);
+
+ expect(result).toEqual({
+ content: 'Device MCP call error: connection refused',
+ error: 'connection refused',
+ success: false,
+ });
+ });
+ });
+
describe('executeMessageApi', () => {
const params = { deviceId: 'dev-1', userId: 'user-1' };
const api = { apiName: 'sendText', payload: { chatGuid: 'chat-1' }, platform: 'imessage' };
diff --git a/src/server/services/toolExecution/deviceProxy.ts b/src/server/services/toolExecution/deviceProxy.ts
index 3f87700e5b0..984d18a5a1b 100644
--- a/src/server/services/toolExecution/deviceProxy.ts
+++ b/src/server/services/toolExecution/deviceProxy.ts
@@ -5,6 +5,7 @@ import {
type DeviceSystemInfo,
type DeviceToolCallResult,
GatewayHttpClient,
+ type GatewayMcpStdioParams,
} from '@lobechat/device-gateway-client';
import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
import debug from 'debug';
@@ -135,6 +136,48 @@ export class DeviceProxy {
}
}
+ /**
+ * Tunnel a stdio MCP tool call to a connected device. The cloud server can't
+ * spawn the user's local MCP binary, so the command/args/env are forwarded
+ * to the device, which spawns the stdio server and runs the call locally.
+ */
+ async executeMcpCall(
+ mcpCall: {
+ apiName: string;
+ arguments: string;
+ deviceId: string;
+ identifier: string;
+ params: GatewayMcpStdioParams;
+ userId: string;
+ },
+ timeout = 30_000,
+ ): Promise<DeviceToolCallResult> {
+ const client = this.getClient();
+ if (!client) {
+ return {
+ content: 'Device Gateway is not configured',
+ error: 'GATEWAY_NOT_CONFIGURED',
+ success: false,
+ };
+ }
+
+ log(
+ 'executeMcpCall: userId=%s, deviceId=%s, mcp=%s/%s',
+ mcpCall.userId,
+ mcpCall.deviceId,
+ mcpCall.identifier,
+ mcpCall.apiName,
+ );
+
+ try {
+ return await client.executeMcpCall({ ...mcpCall, timeout });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ log('executeMcpCall: error β€” %s', message);
+ return { content: `Device MCP call error: ${message}`, error: message, success: false };
+ }
+ }
+
async executeMessageApi(
params: { deviceId: string; userId: string },
api: { apiName: string; payload: Record<string, unknown>; platform: string },
diff --git a/src/server/services/toolExecution/index.ts b/src/server/services/toolExecution/index.ts
index 0994ab80ef4..b9a0c8b81e0 100644
--- a/src/server/services/toolExecution/index.ts
+++ b/src/server/services/toolExecution/index.ts
@@ -2,7 +2,7 @@ import { type ChatToolPayload } from '@lobechat/types';
import { safeParseJSON } from '@lobechat/utils';
import debug from 'debug';
-import { type CloudMCPParams, type ToolCallContent } from '@/libs/mcp';
+import { type CloudMCPParams, type StdioMCPParams, type ToolCallContent } from '@/libs/mcp';
import { contentBlocksToString } from '@/server/services/mcp/contentProcessor';
import {
DEFAULT_TOOL_RESULT_MAX_LENGTH,
@@ -12,6 +12,7 @@ import {
import { DiscoverService } from '../discover';
import { type MCPService } from '../mcp';
import { type BuiltinToolsExecutor } from './builtin';
+import { deviceProxy } from './deviceProxy';
import { classifyToolError } from './errorClassification';
import {
type ToolExecutionContext,
@@ -191,7 +192,21 @@ export class ToolExecutionService {
return await this.executeCloudMCPTool(payload, context, mcpParams);
}
- // For stdio/http/sse types, use standard MCP service
+ // Stdio MCP can't run on the cloud server β€” the binary lives on the
+ // user's machine. When a device gateway is configured and a device is
+ // active, tunnel the call to that device, which spawns the stdio server
+ // locally. Standalone Electron (no gateway) falls through to the
+ // in-process MCP service below, where spawning is on the user's machine.
+ if (
+ mcpParams.type === 'stdio' &&
+ deviceProxy.isConfigured &&
+ context.activeDeviceId &&
+ context.userId
+ ) {
+ return await this.executeMcpViaDevice(payload, context, mcpParams);
+ }
+
+ // For stdio (in-process) / http/sse types, use standard MCP service
const result = await this.mcpService.callTool({
argsStr: args,
clientParams: mcpParams,
@@ -218,6 +233,62 @@ export class ToolExecutionService {
}
}
+ /**
+ * Execute a stdio MCP tool call on the user's device via the device gateway.
+ * Forwards the stdio connection params (command/args/env) so the device can
+ * spawn the local MCP server and run the call β€” something the cloud server
+ * cannot do. Callers must ensure `activeDeviceId` and `userId` are set.
+ */
+ private async executeMcpViaDevice(
+ payload: ChatToolPayload,
+ context: ToolExecutionContext,
+ mcpParams: StdioMCPParams,
+ ): Promise<ToolExecutionResult> {
+ const { identifier, apiName, arguments: args } = payload;
+
+ log(
+ 'Executing stdio MCP tool via device: %s:%s (device=%s)',
+ identifier,
+ apiName,
+ context.activeDeviceId,
+ );
+
+ const result = await deviceProxy.executeMcpCall(
+ {
+ apiName,
+ arguments: args,
+ deviceId: context.activeDeviceId!,
+ identifier,
+ params: {
+ args: mcpParams.args ?? [],
+ command: mcpParams.command,
+ env: mcpParams.env,
+ name: mcpParams.name,
+ type: 'stdio',
+ },
+ userId: context.userId!,
+ },
+ context.executionTimeoutMs,
+ );
+
+ if (!result.success) {
+ return {
+ content: result.content,
+ error: {
+ code: 'MCP_DEVICE_EXECUTION_ERROR',
+ message: result.error || result.content,
+ },
+ success: false,
+ };
+ }
+
+ return {
+ content: result.content,
+ state: (result.state as Record<string, any>) ?? undefined,
+ success: true,
+ };
+ }
+
private async executeCloudMCPTool(
payload: ChatToolPayload,
context: ToolExecutionContext,