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): add explicit type discriminator to tunneled tool calls (#15473)

Arvin Xu2bb39f470a63
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index f128b345995..4ee6a285bfa 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -3,7 +3,10 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import type { AgentRunRequestMessage } from '@lobechat/device-gateway-client';
+import type {
+ AgentRunRequestMessage,
+ GatewayMcpStdioParams,
+} from '@lobechat/device-gateway-client';
import type {
EditLocalFileParams,
GatewayConnectionStatus,
@@ -28,6 +31,7 @@ import ImessageBridgeService from '@/services/imessageBridgeSrv';
import HeterogeneousAgentCtr from './HeterogeneousAgentCtr';
import { ControllerModule, IpcMethod } from './index';
import LocalFileCtr from './LocalFileCtr';
+import McpCtr from './McpCtr';
import RemoteServerConfigCtr from './RemoteServerConfigCtr';
import ShellCommandCtr from './ShellCommandCtr';
@@ -170,6 +174,10 @@ export default class GatewayConnectionCtr extends ControllerModule {
return this.app.getController(HeterogeneousAgentCtr);
}
+ private get mcpCtr() {
+ return this.app.getController(McpCtr);
+ }
+
// ─── Lifecycle ───
afterAppReady() {
@@ -184,6 +192,9 @@ export default class GatewayConnectionCtr extends ControllerModule {
// Wire up tool call handler
srv.setToolCallHandler((apiName, args) => this.executeToolCall(apiName, args));
+ // Wire up MCP call handler (tunneled stdio MCP calls from the cloud server)
+ srv.setMcpCallHandler((mcpCall) => this.executeMcpCall(mcpCall));
+
// Wire up message API handler
srv.setMessageApiHandler((platform, apiName, payload) =>
this.executeMessageApi(platform, apiName, payload),
@@ -459,9 +470,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
}
case 'getAgentProfile': {
- const result = await this.getAgentProfile(
- args as { agentId?: string; platform: string },
- );
+ const result = await this.getAgentProfile(args as { agentId?: string; platform: string });
return { content: JSON.stringify(result), state: result, success: true };
}
@@ -495,6 +504,32 @@ export default class GatewayConnectionCtr extends ControllerModule {
}
}
+ /**
+ * Execute a stdio MCP tool call tunneled from the cloud server. The server
+ * can't spawn the user's local MCP binary, so it forwards the connection
+ * params (command/args/env); we run the call through the local MCP client,
+ * which spawns the stdio server on this machine.
+ */
+ private async executeMcpCall(mcpCall: {
+ apiName: string;
+ arguments: string;
+ identifier: string;
+ params: GatewayMcpStdioParams;
+ }): Promise<BuiltinServerRuntimeOutput> {
+ const { apiName, arguments: args, params: stdioParams } = mcpCall;
+
+ return this.mcpCtr.runStdioMcpTool({
+ args,
+ env: stdioParams.env,
+ params: {
+ args: stdioParams.args,
+ command: stdioParams.command,
+ name: stdioParams.name,
+ },
+ toolName: apiName,
+ });
+ }
+
private async executeMessageApi(
platform: string,
apiName: string,
diff --git a/apps/desktop/src/main/controllers/McpCtr.ts b/apps/desktop/src/main/controllers/McpCtr.ts
index a30a3bd6295..63cf000f97a 100644
--- a/apps/desktop/src/main/controllers/McpCtr.ts
+++ b/apps/desktop/src/main/controllers/McpCtr.ts
@@ -91,7 +91,7 @@ interface GetStreamableMcpServerManifestInput {
url: string;
}
-interface CallToolInput {
+export interface CallToolInput {
args: any;
env: any;
params: GetStdioMcpServerManifestInput;
@@ -324,6 +324,19 @@ export default class McpCtr extends ControllerModule {
@IpcMethod()
async callTool(payload: SuperJSONSerialized<CallToolInput>) {
const input = deserializePayload<CallToolInput>(payload);
+ return serializePayload(await this.runStdioMcpTool(input));
+ }
+
+ /**
+ * Core stdio MCP tool execution, shared by the renderer IPC path
+ * ({@link callTool}) and the device-gateway tunnel (GatewayConnectionCtr,
+ * which runs MCP calls forwarded from the cloud server). Returns the plain
+ * result envelope; callers serialize as needed. Throws on failure so each
+ * caller can shape its own error response.
+ */
+ async runStdioMcpTool(
+ input: CallToolInput,
+ ): Promise<{ content: string; state: unknown; success: boolean }> {
const params: MCPClientParams = {
args: input.params.args || [],
command: input.params.command,
@@ -342,11 +355,11 @@ export default class McpCtr extends ControllerModule {
const content = await toMarkdown(processed, (key) => this.fileService.getFileHTTPURL(key));
- return serializePayload({
+ return {
content,
state: { ...raw, content: processed },
success: true,
- });
+ };
} catch (error) {
// If it's an MCPConnectionError with stderr logs, enhance the error message
if (error instanceof MCPConnectionError && error.stderrLogs.length > 0) {
diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
index c5e286f3185..e461271fb5d 100644
--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
@@ -9,6 +9,7 @@ import ImessageBridgeService from '@/services/imessageBridgeSrv';
import GatewayConnectionCtr from '../GatewayConnectionCtr';
import HeterogeneousAgentCtr from '../HeterogeneousAgentCtr';
import LocalFileCtr from '../LocalFileCtr';
+import McpCtr from '../McpCtr';
import RemoteServerConfigCtr from '../RemoteServerConfigCtr';
import ShellCommandCtr from '../ShellCommandCtr';
@@ -69,6 +70,26 @@ const { ipcMainHandleMock, MockGatewayClient } = vi.hoisted(() => {
});
}
+ simulateMcpCallRequest(
+ apiName: string,
+ args: object,
+ params: object,
+ requestId = 'mcp-req-1',
+ identifier = 'kimi-datasource',
+ ) {
+ this.emit('tool_call_request', {
+ requestId,
+ toolCall: {
+ apiName,
+ arguments: JSON.stringify(args),
+ identifier,
+ params,
+ type: 'mcp',
+ },
+ type: 'tool_call_request',
+ });
+ }
+
simulateMessageApiRequest(
platform: string,
apiName: string,
@@ -123,6 +144,7 @@ const { ipcMainHandleMock, MockGatewayClient } = vi.hoisted(() => {
vi.mock('electron', () => ({
app: {
+ getAppPath: vi.fn(() => '/mock/app'),
getPath: vi.fn((name: string) => `/mock/${name}`),
},
ipcMain: { handle: ipcMainHandleMock },
@@ -229,6 +251,10 @@ const mockImessageBridgeSrv = {
handleGatewayMessageApi: vi.fn().mockResolvedValue({ ok: true }),
} as unknown as ImessageBridgeService;
+const mockMcpCtr = {
+ runStdioMcpTool: vi.fn().mockResolvedValue({ content: 'mcp result', state: {}, success: true }),
+} as unknown as McpCtr;
+
const mockRemoteServerConfigCtr = {
getAccessToken: vi.fn().mockResolvedValue('mock-access-token'),
getRemoteServerUrl: vi.fn().mockResolvedValue('https://server.example.com'),
@@ -247,6 +273,7 @@ const mockApp = {
if (Cls === LocalFileCtr) return mockLocalFileCtr;
if (Cls === ShellCommandCtr) return mockShellCommandCtr;
if (Cls === HeterogeneousAgentCtr) return mockHeterogeneousAgentCtr;
+ if (Cls === McpCtr) return mockMcpCtr;
return null;
}),
getService: vi.fn((Cls) => {
@@ -606,6 +633,89 @@ describe('GatewayConnectionCtr', () => {
},
});
});
+
+ it('should route tunneled stdio MCP calls to McpCtr.runStdioMcpTool', async () => {
+ const client = await connectAndOpen();
+
+ client.simulateMcpCallRequest(
+ 'getStock',
+ { symbol: 'AAPL' },
+ { args: ['stock-mcp'], command: 'npx', env: { TOKEN: 'secret' }, name: 'kimi-datasource' },
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ // The builtin local-system switch is keyed on apiName and would reject
+ // 'getStock'; the `type: 'mcp'` discriminator routes to the MCP client.
+ expect(mockMcpCtr.runStdioMcpTool).toHaveBeenCalledWith({
+ args: '{"symbol":"AAPL"}',
+ env: { TOKEN: 'secret' },
+ params: { args: ['stock-mcp'], command: 'npx', name: 'kimi-datasource' },
+ toolName: 'getStock',
+ });
+ });
+
+ it('should NOT route to MCP when params are present but type is not mcp', async () => {
+ // Regression: routing must follow the explicit `type` discriminator, not
+ // the mere presence of `params`. A builtin call that happens to carry a
+ // `params` field must still go to the builtin switch.
+ const client = await connectAndOpen();
+
+ client.emit('tool_call_request', {
+ requestId: 'tool-with-params',
+ toolCall: {
+ apiName: 'readFile',
+ arguments: JSON.stringify({ path: '/a.txt' }),
+ identifier: 'lobe-local-system',
+ params: { args: [], command: 'npx', name: 'x' },
+ type: 'tool',
+ },
+ type: 'tool_call_request',
+ });
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(mockMcpCtr.runStdioMcpTool).not.toHaveBeenCalled();
+ expect(mockLocalFileCtr.readFile).toHaveBeenCalled();
+ });
+
+ it('should send tool_call_response envelope for a successful MCP call', async () => {
+ vi.mocked(mockMcpCtr.runStdioMcpTool).mockResolvedValueOnce({
+ content: 'stock: 100',
+ state: { rows: 1 },
+ success: true,
+ });
+ const client = await connectAndOpen();
+
+ client.simulateMcpCallRequest(
+ 'getStock',
+ {},
+ { args: [], command: 'npx', name: 'kimi-datasource' },
+ 'mcp-ok',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(client.sendToolCallResponse).toHaveBeenCalledWith({
+ requestId: 'mcp-ok',
+ result: { content: 'stock: 100', state: { rows: 1 }, success: true },
+ });
+ });
+
+ it('should send error response when the MCP call throws', async () => {
+ vi.mocked(mockMcpCtr.runStdioMcpTool).mockRejectedValueOnce(new Error('spawn ENOENT'));
+ const client = await connectAndOpen();
+
+ client.simulateMcpCallRequest(
+ 'getStock',
+ {},
+ { args: [], command: 'missing-bin', name: 'kimi-datasource' },
+ 'mcp-err',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(client.sendToolCallResponse).toHaveBeenCalledWith({
+ requestId: 'mcp-err',
+ result: { content: 'spawn ENOENT', error: 'spawn ENOENT', success: false },
+ });
+ });
});
describe('message API routing', () => {
diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
index b3c402e39cb..33d9eac9810 100644
--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts
+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
@@ -3,6 +3,7 @@ import os from 'node:os';
import type {
AgentRunRequestMessage,
+ GatewayMcpStdioParams,
MessageApiRequestMessage,
SystemInfoRequestMessage,
ToolCallRequestMessage,
@@ -44,6 +45,21 @@ interface ToolCallHandler {
(apiName: string, args: unknown): Promise<ToolCallResult>;
}
+/**
+ * Handler for tunneled stdio MCP calls. Unlike {@link ToolCallHandler} (which
+ * keys on `apiName` for builtin local-system tools), this carries the MCP
+ * server identity + connection params so the device can spawn the local stdio
+ * server and invoke the tool on it.
+ */
+interface McpCallHandler {
+ (mcpCall: {
+ apiName: string;
+ arguments: string;
+ identifier: string;
+ params: GatewayMcpStdioParams;
+ }): Promise<ToolCallResult>;
+}
+
/**
* Coerce a runtime error (which may be an Error, string, or `{ message }`
* object) into the string shape the wire protocol expects. Returns undefined
@@ -93,6 +109,7 @@ export default class GatewayConnectionService extends ServiceModule {
private tokenProvider: (() => Promise<string | null>) | null = null;
private tokenRefresher: (() => Promise<{ error?: string; success: boolean }>) | null = null;
private toolCallHandler: ToolCallHandler | null = null;
+ private mcpCallHandler: McpCallHandler | null = null;
private messageApiHandler: MessageApiHandler | null = null;
private agentRunHandler: AgentRunHandler | null = null;
private deviceRegistrar: DeviceRegistrar | null = null;
@@ -120,6 +137,14 @@ export default class GatewayConnectionService extends ServiceModule {
this.toolCallHandler = handler;
}
+ /**
+ * Set the MCP call handler (routes tunneled stdio MCP calls to McpCtr, which
+ * spawns the local stdio server). Distinct from the builtin tool-call handler.
+ */
+ setMcpCallHandler(handler: McpCallHandler) {
+ this.mcpCallHandler = handler;
+ }
+
setMessageApiHandler(handler: MessageApiHandler) {
this.messageApiHandler = handler;
}
@@ -408,18 +433,35 @@ export default class GatewayConnectionService extends ServiceModule {
client: GatewayClient,
) => {
const { requestId, toolCall } = request;
- const { apiName, arguments: argsStr } = toolCall;
+ const { apiName, arguments: argsStr, identifier, params, type } = toolCall;
- logger.info(`Received tool call: apiName=${apiName}, requestId=${requestId}`);
+ logger.info(
+ `Received tool call: apiName=${apiName}, requestId=${requestId}, type=${type ?? 'tool'}`,
+ );
try {
- if (!this.toolCallHandler) {
- throw new Error('No tool call handler configured');
+ let result: ToolCallResult;
+
+ if (type === 'mcp') {
+ // Tunneled stdio MCP call: route to the local MCP client (spawns the
+ // stdio server). Routing is driven by the explicit `type` discriminator,
+ // not by sniffing the payload β€” the builtin local-system tool switch
+ // keys on `apiName` and has no MCP server context.
+ if (!this.mcpCallHandler) {
+ throw new Error('No MCP call handler configured');
+ }
+ if (!params) {
+ throw new Error('MCP tool call missing connection params');
+ }
+ result = await this.mcpCallHandler({ apiName, arguments: argsStr, identifier, params });
+ } else {
+ if (!this.toolCallHandler) {
+ throw new Error('No tool call handler configured');
+ }
+ const args = JSON.parse(argsStr);
+ result = await this.toolCallHandler(apiName, args);
}
- const args = JSON.parse(argsStr);
- const result = await this.toolCallHandler(apiName, args);
-
// Forward the typed envelope unchanged. Critically, do NOT stringify the
// whole result into `content` β€” that would bury the structured payload
// inside a JSON blob and lose `state`. The wire protocol carries each
diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.ts
index 4c01a24011c..f5ef6906f82 100644
--- a/packages/device-gateway-client/src/http.test.ts
+++ b/packages/device-gateway-client/src/http.test.ts
@@ -268,6 +268,10 @@ describe('GatewayHttpClient', () => {
signal,
}),
);
+ // Builtin calls are tagged so the device routes on `type`, not payload shape.
+ const init = vi.mocked(fetch).mock.calls[0][1];
+ const body = JSON.parse((init as RequestInit).body as string);
+ expect(body.toolCall.type).toBe('tool');
});
it('should use default gateway timeout plus HTTP caller padding when timeout is absent', async () => {
@@ -324,11 +328,12 @@ describe('GatewayHttpClient', () => {
success: true,
});
- // Rides the same endpoint as executeToolCall; the device routes on
- // the presence of `toolCall.params`.
+ // Rides the same endpoint as executeToolCall; the device routes on the
+ // explicit `toolCall.type` discriminator, not on the shape of the payload.
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.type).toBe('mcp');
expect(body.toolCall.identifier).toBe('kimi-datasource');
expect(body.toolCall.params.command).toBe('npx');
expect(body.toolCall.params.env).toEqual({ TOKEN: 'secret' });
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index b1c83f674ee..a4fdb1e11bc 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -1,4 +1,9 @@
-import type { DeviceSystemInfo, GatewayDevice, GatewayMcpStdioParams } from './types';
+import type {
+ DeviceSystemInfo,
+ GatewayDevice,
+ GatewayMcpStdioParams,
+ GatewayToolCallType,
+} from './types';
const DEFAULT_GATEWAY_TOOL_CALL_TIMEOUT_MS = 30_000;
const HTTP_CALL_TIMEOUT_PADDING_MS = 30_000;
@@ -58,7 +63,7 @@ export class GatewayHttpClient {
params: { deviceId?: string; timeout?: number; userId: string },
toolCall: { apiName: string; arguments: string; identifier: string },
): Promise<DeviceToolCallResult> {
- return this.postToolCall(params, toolCall);
+ return this.postToolCall(params, { ...toolCall, type: 'tool' });
}
/**
@@ -80,7 +85,7 @@ export class GatewayHttpClient {
userId: string;
}): Promise<DeviceToolCallResult> {
const { deviceId, timeout, userId, ...toolCall } = mcpCall;
- return this.postToolCall({ deviceId, timeout, userId }, toolCall);
+ return this.postToolCall({ deviceId, timeout, userId }, { ...toolCall, type: 'mcp' });
}
private async postToolCall(
@@ -90,6 +95,7 @@ export class GatewayHttpClient {
arguments: string;
identifier: string;
params?: GatewayMcpStdioParams;
+ type?: GatewayToolCallType;
},
): Promise<DeviceToolCallResult> {
const timeout =
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index 8dced08a991..1e2d98bde39 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -103,6 +103,17 @@ export interface GatewayMcpStdioParams {
type: 'stdio';
}
+/**
+ * How the device should execute a tunneled tool call. Explicit so routing never
+ * depends on structural sniffing (e.g. "does `params` exist?") β€” the gateway
+ * relays every call over one `tool-call` channel, so the discriminator must be
+ * a dedicated field, not the shape of the payload.
+ *
+ * `'tool'` is the generic builtin/local-system call; `'mcp'` is a tunneled
+ * stdio MCP call. Open to future kinds (e.g. `'skill'`).
+ */
+export type GatewayToolCallType = 'tool' | 'mcp';
+
export interface ToolCallRequestMessage {
/** Operation that triggered the call, propagated by the gateway for tracing. */
operationId?: string;
@@ -113,12 +124,14 @@ export interface ToolCallRequestMessage {
apiName: string;
arguments: string;
identifier: string;
+ /** Stdio MCP connection params β€” present only when `type === 'mcp'`. */
+ params?: GatewayMcpStdioParams;
/**
- * 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.
+ * Routing discriminator. `'mcp'` β†’ the device's local MCP client (spawns
+ * the stdio server); `'tool'` (or omitted, for back-compat with older
+ * servers) β†’ the builtin local-system tool switch.
*/
- params?: GatewayMcpStdioParams;
+ type?: GatewayToolCallType;
};
type: 'tool_call_request';
}