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.

πŸ› fix: install and run local MCP connectors (stdio / LAN http) on desktop (#17673)

YuTengjing9fc4dffc39de
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index 8d4a28c2f8c..86b26650fcf 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -4,10 +4,7 @@ import os from 'node:os';
import path from 'node:path';
import { type DeviceControlDeps, executeDeviceRpc as runDeviceRpc } from '@lobechat/device-control';
-import type {
- AgentRunRequestMessage,
- GatewayMcpStdioParams,
-} from '@lobechat/device-gateway-client';
+import type { AgentRunRequestMessage, GatewayMcpParams } from '@lobechat/device-gateway-client';
import type {
EditLocalFileParams,
GatewayConnectionStatus,
@@ -605,26 +602,35 @@ 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.
+ * Execute an MCP tool call tunneled from the cloud server, for MCP servers
+ * only this machine can reach: stdio (the server can't spawn the user's
+ * local binary) and localhost / LAN HTTP endpoints (the server's fetch
+ * can't reach them). The connection params ride along; we run the call
+ * through the local MCP client.
*/
private async executeMcpCall(mcpCall: {
apiName: string;
arguments: string;
identifier: string;
- params: GatewayMcpStdioParams;
+ params: GatewayMcpParams;
}): Promise<BuiltinServerRuntimeOutput> {
- const { apiName, arguments: args, params: stdioParams } = mcpCall;
+ const { apiName, arguments: args, params } = mcpCall;
+
+ if (params.type === 'http') {
+ return this.mcpCtr.runHttpMcpTool(
+ { auth: params.auth, headers: params.headers, name: params.name, url: params.url },
+ apiName,
+ args,
+ );
+ }
return this.mcpCtr.runStdioMcpTool({
args,
- env: stdioParams.env,
+ env: params.env,
params: {
- args: stdioParams.args,
- command: stdioParams.command,
- name: stdioParams.name,
+ args: params.args,
+ command: params.command,
+ name: params.name,
},
toolName: apiName,
});
diff --git a/apps/desktop/src/main/controllers/McpCtr.ts b/apps/desktop/src/main/controllers/McpCtr.ts
index 0b19ef6bf45..47bc88f6da0 100644
--- a/apps/desktop/src/main/controllers/McpCtr.ts
+++ b/apps/desktop/src/main/controllers/McpCtr.ts
@@ -410,20 +410,58 @@ export default class McpCtr extends ControllerModule {
async runStdioMcpTool(
input: CallToolInput,
): Promise<{ content: string; state: unknown; success: boolean }> {
- const params: MCPClientParams = {
- args: input.params.args || [],
- command: input.params.command,
- env: input.env,
- name: input.params.name,
- type: 'stdio',
- };
+ return this.runMcpTool(
+ {
+ args: input.params.args || [],
+ command: input.params.command,
+ env: input.env,
+ name: input.params.name,
+ type: 'stdio',
+ },
+ input.toolName,
+ input.args,
+ );
+ }
+
+ /**
+ * HTTP counterpart of {@link runStdioMcpTool} for the device-gateway tunnel:
+ * the cloud server forwards calls to localhost / LAN MCP endpoints that only
+ * this machine's network can reach, with the (server-decrypted) auth attached.
+ */
+ async runHttpMcpTool(
+ input: {
+ auth?: { accessToken?: string; token?: string; type: 'none' | 'bearer' | 'oauth2' };
+ headers?: Record<string, string>;
+ name: string;
+ url: string;
+ },
+ toolName: string,
+ rawArgs: unknown,
+ ): Promise<{ content: string; state: unknown; success: boolean }> {
+ return this.runMcpTool(
+ {
+ auth: input.auth,
+ headers: input.headers,
+ name: input.name,
+ type: 'http',
+ url: input.url,
+ },
+ toolName,
+ rawArgs,
+ );
+ }
+ private async runMcpTool(
+ params: MCPClientParams,
+ toolName: string,
+ rawArgs: unknown,
+ ): Promise<{ content: string; state: unknown; success: boolean }> {
let client: MCPClient | undefined;
try {
client = await this.createClient(params);
- const args = safeParseToRecord(input.args);
+ const args = safeParseToRecord(rawArgs);
- const raw = (await client.callTool(input.toolName, args)) as ToolCallResult;
+ const raw = (await client.callTool(toolName, args)) as ToolCallResult;
const processed = raw.isError ? raw.content : await this.processContentBlocks(raw.content);
const content = await toMarkdown(processed, (key) => this.fileService.getFileHTTPURL(key));
diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
index 0a369cec6a3..bdbc3433a2b 100644
--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts
+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
@@ -9,7 +9,7 @@ import type {
} from '@lobechat/device-control';
import type {
AgentRunRequestMessage,
- GatewayMcpStdioParams,
+ GatewayMcpParams,
MessageApiRequestMessage,
RpcRequestMessage,
SystemInfoRequestMessage,
@@ -65,7 +65,7 @@ interface McpCallHandler {
apiName: string;
arguments: string;
identifier: string;
- params: GatewayMcpStdioParams;
+ params: GatewayMcpParams;
}): Promise<ToolCallResult>;
}
diff --git a/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts
index f615af7248f..c1d4cfc0624 100644
--- a/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts
@@ -219,7 +219,7 @@ describe('connectorRouter.create β€” sourceType handling on existing rows', () =
const result = await caller().create(baseCustomInput);
- expect(result).toEqual({ id: 'conn-existing' });
+ expect(result).toEqual({ id: 'conn-existing', isNew: false });
expect(connectorModelMock.create).not.toHaveBeenCalled();
expect(connectorModelMock.update).toHaveBeenCalledTimes(1);
expect(connectorModelMock.update).toHaveBeenCalledWith(
@@ -251,7 +251,7 @@ describe('connectorRouter.create β€” sourceType handling on existing rows', () =
const result = await caller().create(baseCustomInput);
- expect(result).toEqual({ id: 'conn-new' });
+ expect(result).toEqual({ id: 'conn-new', isNew: true });
expect(connectorModelMock.create).toHaveBeenCalledWith(
expect.objectContaining({ identifier: 'legacy-mcp', sourceType: 'custom' }),
);
diff --git a/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.ts b/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.ts
new file mode 100644
index 00000000000..9960d36dc72
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.ts
@@ -0,0 +1,116 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ConnectorModel } from '@/database/models/connector';
+import { ConnectorToolModel } from '@/database/models/connectorTool';
+import { ConnectorStatus } from '@/database/schemas';
+
+import { connectorRouter } from '../connector';
+
+// `vi.mock` is hoisted by vitest's transformer above all imports at runtime,
+// so the relative import order doesn't matter functionally β€” the mocks below
+// are still active when the router module is evaluated. They live below the
+// imports to satisfy `import-x/first` without disabling the rule.
+vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));
+vi.mock('@/database/models/connector', () => ({ ConnectorModel: vi.fn() }));
+vi.mock('@/database/models/connectorTool', () => ({ ConnectorToolModel: vi.fn() }));
+vi.mock('@/database/models/plugin', () => ({ PluginModel: vi.fn() }));
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },
+}));
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');
+ // The real `wsCompatProcedure` validates a Better-Auth session; for unit
+ // tests we skip auth and rely on the test ctx already carrying `userId`.
+ return {
+ requireWorkspaceRoleWhenScoped: () => mod.trpc.middleware(async (opts: any) => opts.next()),
+ wsCompatProcedure: mod.trpc.procedure,
+ };
+});
+vi.mock('@/libs/trpc/lambda/middleware', () => ({
+ serverDatabase: async (opts: any) =>
+ opts.next({ ctx: { ...opts.ctx, serverDB: opts.ctx.serverDB ?? {} } }),
+}));
+
+const CONNECTOR_ID = '9f1f6f30-0000-4000-8000-000000000001';
+
+// The desktop-reported install path for MCP servers the cloud can't reach
+// (stdio / localhost / LAN endpoints, #16533): the client lists the tools
+// locally and reports them into an existing connector row.
+describe('connectorRouter.syncToolsFromClientById', () => {
+ let connectorModelMock: any;
+ let connectorToolModelMock: any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ connectorModelMock = {
+ findById: vi.fn().mockResolvedValue({
+ id: CONNECTOR_ID,
+ identifier: 'my-local-mcp',
+ userId: 'user_test',
+ }),
+ updateStatus: vi.fn(),
+ };
+ connectorToolModelMock = { upsertMany: vi.fn() };
+
+ vi.mocked(ConnectorModel).mockImplementation(() => connectorModelMock);
+ vi.mocked(ConnectorToolModel).mockImplementation(() => connectorToolModelMock);
+ });
+
+ const caller = () =>
+ connectorRouter.createCaller({
+ serverDB: {},
+ userId: 'user_test',
+ } as any);
+
+ it('upserts the reported tools and promotes the connector to connected', async () => {
+ const res = await caller().syncToolsFromClientById({
+ id: CONNECTOR_ID,
+ tools: [
+ { description: 'list things', inputSchema: { type: 'object' }, toolName: 'list_things' },
+ { toolName: 'delete_thing' },
+ ],
+ });
+
+ expect(res).toEqual({ toolCount: 2 });
+ expect(connectorToolModelMock.upsertMany).toHaveBeenCalledWith(CONNECTOR_ID, [
+ expect.objectContaining({ crudType: 'read', toolName: 'list_things' }),
+ expect.objectContaining({ crudType: 'delete', toolName: 'delete_thing' }),
+ ]);
+ expect(connectorModelMock.updateStatus).toHaveBeenCalledWith(
+ CONNECTOR_ID,
+ ConnectorStatus.connected,
+ );
+ });
+
+ it('rejects an unknown connector id', async () => {
+ connectorModelMock.findById.mockResolvedValue(undefined);
+
+ await expect(
+ caller().syncToolsFromClientById({ id: CONNECTOR_ID, tools: [] }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(connectorToolModelMock.upsertMany).not.toHaveBeenCalled();
+ });
+
+ it("rejects reporting into another member's workspace connector", async () => {
+ connectorModelMock.findById.mockResolvedValue({
+ id: CONNECTOR_ID,
+ identifier: 'my-local-mcp',
+ userId: 'someone_else',
+ });
+
+ await expect(
+ connectorRouter
+ .createCaller({
+ serverDB: {},
+ userId: 'user_test',
+ workspaceId: 'ws_1',
+ workspaceRole: 'member',
+ } as any)
+ .syncToolsFromClientById({ id: CONNECTOR_ID, tools: [] }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(connectorToolModelMock.upsertMany).not.toHaveBeenCalled();
+ expect(connectorModelMock.updateStatus).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.ts
index 2b1bddf7dc4..1bdbc920760 100644
--- a/apps/server/src/routers/lambda/connector.ts
+++ b/apps/server/src/routers/lambda/connector.ts
@@ -342,10 +342,14 @@ export const connectorRouter = router({
sourceType: input.sourceType,
status: ConnectorStatus.disconnected,
});
- return { id: existing.id };
+ // `isNew` lets clients tell a fresh row from an updated pre-existing one β€”
+ // client-side caches can't answer this reliably (the connector list may
+ // not be fetched yet), and rollback-on-sync-failure must never delete a
+ // connector the user already had.
+ return { id: existing.id, isNew: false };
}
- return ctx.connectorModel.create({
+ const created = await ctx.connectorModel.create({
...fields,
agentId: agentId ?? null,
identifier: input.identifier,
@@ -353,6 +357,7 @@ export const connectorRouter = router({
sourceType: input.sourceType,
status: ConnectorStatus.disconnected,
});
+ return { id: created.id, isNew: true };
}),
/**
@@ -820,6 +825,48 @@ export const connectorRouter = router({
return { connectorId, toolCount: syncInputs.length };
}),
+ /**
+ * Sync a client-fetched tool list into an EXISTING connector row. This is the
+ * install/refresh path for connectors the cloud server cannot reach itself:
+ * stdio MCP (the binary lives on the user's machine) and local/private-network
+ * HTTP endpoints. The desktop client connects locally, lists the tools, and
+ * reports them here β€” the server-side `syncTools` counterpart would otherwise
+ * try (and fail) to connect from the cloud (#16533).
+ *
+ * Also promotes the connector to `connected`, mirroring what
+ * `syncConnectorToolsById` does after a successful server-side sync.
+ */
+ syncToolsFromClientById: connectorWriteProcedure
+ .input(
+ z.object({
+ id: z.string().uuid(),
+ tools: z.array(
+ z.object({
+ description: z.string().optional(),
+ inputSchema: z.record(z.string(), z.unknown()).optional(),
+ toolName: z.string(),
+ }),
+ ),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const target = await ctx.connectorModel.findById(input.id);
+ if (!target) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
+ // Same edit-class gate as `syncTools` β€” rewrites the connector's tool rows.
+ assertWorkspaceRowManageable(ctx, target.userId, 'connector');
+
+ const syncInputs = input.tools.map((t) => ({
+ crudType: inferCrudType(t.toolName),
+ description: t.description,
+ inputSchema: t.inputSchema,
+ toolName: t.toolName,
+ }));
+
+ await ctx.connectorToolModel.upsertMany(input.id, syncInputs);
+ await ctx.connectorModel.updateStatus(input.id, ConnectorStatus.connected);
+ return { toolCount: syncInputs.length };
+ }),
+
/**
* Bootstrap a connector entry for a builtin tool (lobe-creds, lobe-local-system, etc.)
* by reading its manifest from @lobechat/builtin-tools.
diff --git a/apps/server/src/services/connector/exec.test.ts b/apps/server/src/services/connector/exec.test.ts
index 05b3e6c2728..d26e012397b 100644
--- a/apps/server/src/services/connector/exec.test.ts
+++ b/apps/server/src/services/connector/exec.test.ts
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ConnectorToolPermission } from '@/database/schemas';
+import { deviceGateway } from '@/server/services/deviceGateway';
import { mcpService } from '@/server/services/mcp';
import { callConnectorToolById } from './exec';
@@ -8,6 +9,7 @@ import { scheduleStaleConnectorToolsRefresh } from './refresh';
import { ensureFreshConnectorToken } from './tokens';
vi.mock('@/server/services/mcp', () => ({ mcpService: { callTool: vi.fn() } }));
+vi.mock('@/server/services/deviceGateway', () => ({ deviceGateway: { isConfigured: false } }));
vi.mock('./tokens', () => ({ ensureFreshConnectorToken: vi.fn(async (c) => c) }));
// The background tool-list refresh is exercised in refresh.test.ts. Here we only
// verify the call site wires it up and stays isolated from it.
@@ -43,6 +45,7 @@ const makeCtx = (connectors: any[], tools: any[]) =>
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(ensureFreshConnectorToken).mockImplementation(async (c: any) => c);
+ (deviceGateway as any).isConfigured = false;
});
describe('callConnectorToolById', () => {
@@ -137,6 +140,61 @@ describe('callConnectorToolById', () => {
);
});
+ // On a cloud deployment (device gateway configured) the server can never
+ // reach a stdio binary or a localhost/LAN endpoint β€” those calls must fail
+ // fast with an actionable message instead of a cryptic spawn/fetch error
+ // (#16533). Self-hosted servers (no gateway) may share a LAN with the
+ // endpoint, so the guard must NOT fire there.
+ describe('device-only endpoints on a cloud deployment', () => {
+ it('rejects a stdio connector when the device gateway is configured', async () => {
+ (deviceGateway as any).isConfigured = true;
+ const stdioConnector = {
+ ...connector,
+ mcpConnectionType: 'stdio',
+ mcpServerUrl: null,
+ mcpStdioConfig: { args: [], command: 'npx' },
+ };
+ const ctx = makeCtx([stdioConnector], [tool()]);
+
+ await expect(
+ callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx),
+ ).rejects.toHaveProperty('code', 'BAD_REQUEST');
+ expect(mcpService.callTool).not.toHaveBeenCalled();
+ });
+
+ it('rejects a local/private-network HTTP connector when the device gateway is configured', async () => {
+ (deviceGateway as any).isConfigured = true;
+ const localConnector = { ...connector, mcpServerUrl: 'http://192.168.1.10:8080/mcp' };
+ const ctx = makeCtx([localConnector], [tool()]);
+
+ await expect(
+ callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx),
+ ).rejects.toHaveProperty('code', 'BAD_REQUEST');
+ expect(mcpService.callTool).not.toHaveBeenCalled();
+ });
+
+ it('still calls a local endpoint when no device gateway is configured (self-host)', async () => {
+ vi.mocked(mcpService.callTool).mockResolvedValue({ success: true });
+ const localConnector = { ...connector, mcpServerUrl: 'http://192.168.1.10:8080/mcp' };
+ const ctx = makeCtx([localConnector], [tool()]);
+
+ const res = await callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx);
+
+ expect(res).toEqual({ success: true });
+ expect(mcpService.callTool).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps calling public endpoints when the device gateway is configured', async () => {
+ (deviceGateway as any).isConfigured = true;
+ vi.mocked(mcpService.callTool).mockResolvedValue({ success: true });
+ const ctx = makeCtx([connector], [tool()]);
+
+ const res = await callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx);
+
+ expect(res).toEqual({ success: true });
+ });
+ });
+
it('still returns the tool result when the background refresh scheduler throws', async () => {
// The refresh is a pure optimization; a failure in it must never break the
// tool call the user actually asked for.
diff --git a/apps/server/src/services/connector/exec.ts b/apps/server/src/services/connector/exec.ts
index 56b45e55d4b..0065da3044f 100644
--- a/apps/server/src/services/connector/exec.ts
+++ b/apps/server/src/services/connector/exec.ts
@@ -1,4 +1,7 @@
-import { ConnectorToolPermission } from '@/database/schemas';
+import { isLocalOrPrivateUrl } from '@lobechat/utils';
+
+import { ConnectorMcpConnectionType, ConnectorToolPermission } from '@/database/schemas';
+import { deviceGateway } from '@/server/services/deviceGateway';
import { mcpService } from '@/server/services/mcp';
import { buildLastSyncedAtMap, scheduleStaleConnectorToolsRefresh } from './refresh';
@@ -80,6 +83,23 @@ export const callConnectorToolById = async (
// Background tool-list refresh is best-effort β€” never fail the tool call.
}
+ // Fail fast with an actionable message instead of a cryptic spawn/fetch
+ // error: on a cloud deployment (device gateway configured) the server can
+ // never reach a stdio binary or a localhost/LAN endpoint. Those calls run on
+ // the user's device via the gateway-mode tunnel β€” this path is only hit when
+ // the user manually turned gateway mode off. Gated so a self-hosted server
+ // that shares a LAN with the endpoint keeps working.
+ const isDeviceOnlyEndpoint =
+ connector.mcpConnectionType === ConnectorMcpConnectionType.stdio ||
+ (!!connector.mcpServerUrl && isLocalOrPrivateUrl(connector.mcpServerUrl));
+ if (deviceGateway.isConfigured && isDeviceOnlyEndpoint) {
+ throw new ConnectorToolCallError(
+ 'BAD_REQUEST',
+ `Connector '${connector.name}' points at an MCP endpoint that only your machine can reach (stdio or local network). ` +
+ 'These tools run through the agent gateway on desktop β€” please re-enable gateway mode in settings.',
+ );
+ }
+
const fresh = await ensureFreshConnectorToken(connector, ctx.connectorModel);
return mcpService.callTool({
diff --git a/apps/server/src/services/connector/refresh.test.ts b/apps/server/src/services/connector/refresh.test.ts
index 2c817376f49..5c3166ae1a2 100644
--- a/apps/server/src/services/connector/refresh.test.ts
+++ b/apps/server/src/services/connector/refresh.test.ts
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { deviceGateway } from '@/server/services/deviceGateway';
import { after } from '@/server/utils/scheduleAfterResponse';
import {
@@ -18,6 +19,7 @@ vi.mock('@/server/utils/scheduleAfterResponse', () => ({
}),
}));
vi.mock('./sync', () => ({ syncConnectorToolsById: vi.fn().mockResolvedValue({ toolCount: 3 }) }));
+vi.mock('@/server/services/deviceGateway', () => ({ deviceGateway: { isConfigured: false } }));
const ctx = {} as any;
const NOW = 1_000_000_000_000;
@@ -43,6 +45,7 @@ beforeEach(() => {
vi.clearAllMocks();
deferred.length = 0;
vi.mocked(syncConnectorToolsById).mockResolvedValue({ toolCount: 3 });
+ (deviceGateway as any).isConfigured = false;
});
describe('buildLastSyncedAtMap', () => {
@@ -118,6 +121,33 @@ describe('scheduleStaleConnectorToolsRefresh β€” eligibility', () => {
expect(syncConnectorToolsById).not.toHaveBeenCalled();
});
+ it('skips local/private-network endpoints on a cloud deployment (device gateway configured)', async () => {
+ (deviceGateway as any).isConfigured = true;
+ const id = nextId();
+ scheduleStaleConnectorToolsRefresh(
+ [{ id, mcpConnectionType: 'http', mcpServerUrl: 'http://192.168.1.10:8080/mcp' }],
+ new Map(),
+ ctx,
+ NOW,
+ );
+ await flushDeferred();
+ expect(syncConnectorToolsById).not.toHaveBeenCalled();
+ });
+
+ it('still refreshes local endpoints when self-hosted (no device gateway)', async () => {
+ // A self-hosted server may share a LAN with the endpoint β€” the cloud-only
+ // skip must not fire there.
+ const id = nextId();
+ scheduleStaleConnectorToolsRefresh(
+ [{ id, mcpConnectionType: 'http', mcpServerUrl: 'http://192.168.1.10:8080/mcp' }],
+ new Map(),
+ ctx,
+ NOW,
+ );
+ await flushDeferred();
+ expect(syncConnectorToolsById).toHaveBeenCalledWith(id, ctx);
+ });
+
it('throttles a second call for the same connector at the same instant', async () => {
const id = nextId();
scheduleStaleConnectorToolsRefresh([httpConnector(id)], new Map(), ctx, NOW);
diff --git a/apps/server/src/services/connector/refresh.ts b/apps/server/src/services/connector/refresh.ts
index 1790506ca34..321a8361b97 100644
--- a/apps/server/src/services/connector/refresh.ts
+++ b/apps/server/src/services/connector/refresh.ts
@@ -1,6 +1,8 @@
+import { isLocalOrPrivateUrl } from '@lobechat/utils';
import debug from 'debug';
import { ConnectorMcpConnectionType } from '@/database/schemas';
+import { deviceGateway } from '@/server/services/deviceGateway';
import { after } from '@/server/utils/scheduleAfterResponse';
import { type ConnectorToolSyncContext, syncConnectorToolsById } from './sync';
@@ -102,6 +104,12 @@ export const scheduleStaleConnectorToolsRefresh = (
// machine); skip anything without an HTTP endpoint.
if (connector.mcpConnectionType === ConnectorMcpConnectionType.stdio) continue;
if (!connector.mcpServerUrl) continue;
+ // Localhost / private-network endpoints are unreachable from the CLOUD
+ // server β€” their tool list is synced by the desktop client instead
+ // (`syncToolsFromClientById`). Gate on the device gateway being
+ // configured: a self-hosted server may share a LAN with the endpoint
+ // and can legitimately refresh it.
+ if (deviceGateway.isConfigured && isLocalOrPrivateUrl(connector.mcpServerUrl)) continue;
const { id } = connector;
// Throttle on whichever is more recent: the DB tool marker or the last
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index 2fc69509ba9..2b0c0daa8a1 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -7,7 +7,7 @@ import {
type DeviceSystemInfo,
type DeviceToolCallResult,
GatewayHttpClient,
- type GatewayMcpStdioParams,
+ type GatewayMcpParams,
} from '@lobechat/device-gateway-client';
import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
import type {
@@ -1308,9 +1308,10 @@ export class DeviceGateway {
}
/**
- * 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.
+ * Tunnel an MCP tool call to a connected device, for MCP servers only the
+ * device can reach: stdio (the cloud can't spawn the user's local binary)
+ * and localhost / LAN HTTP endpoints (the cloud's fetch can't reach them).
+ * The connection params are forwarded so the device runs the call locally.
*/
async executeMcpCall(
mcpCall: {
@@ -1318,7 +1319,7 @@ export class DeviceGateway {
arguments: string;
deviceId: string;
identifier: string;
- params: GatewayMcpStdioParams;
+ params: GatewayMcpParams;
userId: string;
workspaceId?: string;
},
diff --git a/apps/server/src/services/toolExecution/__tests__/index.test.ts b/apps/server/src/services/toolExecution/__tests__/index.test.ts
index c28378c5bcb..e7bc72c5bf6 100644
--- a/apps/server/src/services/toolExecution/__tests__/index.test.ts
+++ b/apps/server/src/services/toolExecution/__tests__/index.test.ts
@@ -1,8 +1,24 @@
// @vitest-environment node
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { deviceGateway } from '@/server/services/deviceGateway';
+import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
import { ToolExecutionService } from '../index';
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ executeMcpCall: vi.fn(),
+ isConfigured: false,
+ queryDeviceList: vi.fn().mockResolvedValue([]),
+ },
+}));
+// The tunnel fallback must use the visibility-aware scoped helper, never the
+// raw (visibility-blind) gateway pool β€” see resolveMcpTunnelTarget.
+vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({
+ getScopedOnlineDevices: vi.fn().mockResolvedValue([]),
+}));
+
describe('ToolExecutionService', () => {
it('can skip low-level result truncation for AgentRuntime archival', async () => {
const builtinToolsExecutor = {
@@ -63,4 +79,253 @@ describe('ToolExecutionService', () => {
expect(result.content).toContain('01234');
expect(result.content).toContain('Content truncated');
});
+
+ // Device-only MCP servers (stdio / localhost / LAN) can't be called from the
+ // cloud β€” with a device gateway configured, those calls must tunnel to the
+ // user's device instead of failing with a spawn/fetch error (#16533).
+ describe('device-only MCP tunneling', () => {
+ const makeService = (mcpService: any = { callTool: vi.fn() }) =>
+ new ToolExecutionService({
+ builtinToolsExecutor: { execute: vi.fn() } as any,
+ mcpService,
+ });
+
+ const mcpPayload = {
+ apiName: 'do_thing',
+ arguments: '{}',
+ id: 'tool-call-1',
+ identifier: 'my-mcp',
+ type: 'mcp',
+ } as any;
+
+ const contextWith = (mcpParams: Record<string, unknown>, over: Record<string, unknown> = {}) =>
+ ({
+ serverDB: {},
+ toolManifestMap: { 'my-mcp': { mcpParams } },
+ userId: 'user-1',
+ ...over,
+ }) as any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (deviceGateway as any).isConfigured = true;
+ vi.mocked(deviceGateway.executeMcpCall).mockResolvedValue({
+ content: 'ok',
+ success: true,
+ } as any);
+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([]);
+ });
+
+ it('tunnels a stdio MCP call to the plan-routed device', async () => {
+ const service = makeService();
+ const result = await service.executeTool(
+ mcpPayload,
+ contextWith(
+ { args: ['-y', 'mcp-server'], command: 'npx', name: 'my-mcp', type: 'stdio' },
+ { activeDeviceId: 'device-1' },
+ ),
+ );
+
+ expect(result.success).toBe(true);
+ expect(deviceGateway.executeMcpCall).toHaveBeenCalledWith(
+ expect.objectContaining({
+ deviceId: 'device-1',
+ params: expect.objectContaining({ command: 'npx', type: 'stdio' }),
+ }),
+ undefined,
+ );
+ });
+
+ it('tunnels a local-network HTTP MCP call and narrows the auth payload', async () => {
+ const service = makeService();
+ await service.executeTool(
+ mcpPayload,
+ contextWith(
+ {
+ auth: {
+ accessToken: 'at',
+ clientSecret: 'SECRET',
+ refreshToken: 'REFRESH',
+ type: 'oauth2',
+ },
+ name: 'my-mcp',
+ type: 'http',
+ url: 'http://192.168.1.10:8080/mcp',
+ },
+ { activeDeviceId: 'device-1' },
+ ),
+ );
+
+ const call = vi.mocked(deviceGateway.executeMcpCall).mock.calls[0][0];
+ expect(call.params).toEqual({
+ auth: { accessToken: 'at', token: undefined, type: 'oauth2' },
+ headers: undefined,
+ name: 'my-mcp',
+ type: 'http',
+ url: 'http://192.168.1.10:8080/mcp',
+ });
+ });
+
+ it('falls back to the first online scoped personal device for chat-mode runs (no plan device)', async () => {
+ // getScopedOnlineDevices returns online-first / most-recently-active
+ // 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.
+ { channels: [{ channel: 'cli' }], deviceId: 'cli-only', online: true },
+ {
+ channels: [{ channel: 'cli' }, { channel: 'desktop' }],
+ deviceId: 'newest',
+ online: true,
+ },
+ { channels: [{ channel: 'desktop' }], deviceId: 'older', online: true },
+ ] as any);
+ const service = makeService();
+ const context = contextWith({ args: [], command: 'npx', name: 'my-mcp', type: 'stdio' });
+
+ await service.executeTool(mcpPayload, context);
+
+ expect(getScopedOnlineDevices).toHaveBeenCalledWith(context.serverDB, 'user-1', undefined);
+ expect(deviceGateway.queryDeviceList).not.toHaveBeenCalled();
+ expect(deviceGateway.executeMcpCall).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'newest' }),
+ undefined,
+ );
+ });
+
+ it('addresses the workspace pool for a plan-routed device in a workspace run', async () => {
+ // Workspace devices live under the `workspace:<id>` principal in the
+ // gateway β€” the tunneled call must carry the scope or an online
+ // workspace device would be missed.
+ const service = makeService();
+
+ await service.executeTool(
+ mcpPayload,
+ contextWith(
+ { args: [], command: 'npx', name: 'my-mcp', type: 'stdio' },
+ { activeDeviceId: 'ws-device', workspaceId: 'ws-1' },
+ ),
+ );
+
+ expect(deviceGateway.executeMcpCall).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'ws-device', workspaceId: 'ws-1' }),
+ undefined,
+ );
+ });
+
+ it('fails closed for a workspace run with no plan-routed device', async () => {
+ // The connector may have been authorized by ANOTHER member β€” tunneling
+ // its credentials to the caller's own newest device would leak them to a
+ // machine the authorizer never approved. No implicit fallback in
+ // workspace scope.
+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([
+ { deviceId: 'caller-device', online: true },
+ ] as any);
+ const service = makeService();
+
+ const result = await service.executeTool(
+ mcpPayload,
+ contextWith(
+ { args: [], command: 'npx', name: 'my-mcp', type: 'stdio' },
+ { workspaceId: 'ws-1' },
+ ),
+ );
+
+ expect(getScopedOnlineDevices).not.toHaveBeenCalled();
+ expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();
+ expect(result.success).toBe(false);
+ expect((result.error as any)?.code).toBe('MCP_DEVICE_UNAVAILABLE');
+ });
+
+ it('addresses the personal pool for a personal-scope active device in a workspace run', async () => {
+ // LOBE-11689: a workspace agent routed to the caller's own machine has no
+ // connection under the workspace principal β€” a workspace-addressed call
+ // would miss it.
+ const service = makeService();
+
+ await service.executeTool(
+ mcpPayload,
+ contextWith(
+ { args: [], command: 'npx', name: 'my-mcp', type: 'stdio' },
+ { activeDeviceId: 'device-1', activeDeviceScope: 'personal', workspaceId: 'ws-1' },
+ ),
+ );
+
+ expect(deviceGateway.executeMcpCall).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'device-1', workspaceId: undefined }),
+ undefined,
+ );
+ });
+
+ it('keeps public HTTP MCP calls in-process on the server', async () => {
+ const callTool = vi.fn().mockResolvedValue({ ok: true });
+ const service = makeService({ callTool });
+
+ await service.executeTool(
+ mcpPayload,
+ contextWith(
+ { name: 'my-mcp', type: 'http', url: 'https://mcp.example.com' },
+ { activeDeviceId: 'device-1' },
+ ),
+ );
+
+ expect(callTool).toHaveBeenCalledTimes(1);
+ expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();
+ });
+
+ it('fails fast when no device is reachable instead of executing on the server', async () => {
+ // With a gateway configured (cloud), a device-only endpoint must never
+ // run in-process β€” that would spawn the command / fetch the private URL
+ // on the cloud server, bypassing the classic-path device-only guard.
+ const callTool = vi.fn().mockResolvedValue({ ok: true });
+ const service = makeService({ callTool });
+
+ const result = await service.executeTool(
+ mcpPayload,
+ contextWith({ name: 'my-mcp', type: 'http', url: 'http://localhost:8080/mcp' }),
+ );
+
+ expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();
+ expect(callTool).not.toHaveBeenCalled();
+ expect(result.success).toBe(false);
+ expect((result.error as any)?.code).toBe('MCP_DEVICE_UNAVAILABLE');
+ });
+
+ it('fails closed when no serverDB is available to apply device visibility', async () => {
+ // Without a DB the scoped helper cannot apply device visibility β€” never
+ // fall back to a raw gateway lookup.
+ const service = makeService();
+
+ const result = await service.executeTool(
+ mcpPayload,
+ contextWith(
+ { args: [], command: 'npx', name: 'my-mcp', type: 'stdio' },
+ { serverDB: undefined },
+ ),
+ );
+
+ expect(getScopedOnlineDevices).not.toHaveBeenCalled();
+ expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();
+ expect(result.success).toBe(false);
+ expect((result.error as any)?.code).toBe('MCP_DEVICE_UNAVAILABLE');
+ });
+
+ it('runs stdio in-process when no gateway is configured (standalone Electron)', async () => {
+ (deviceGateway as any).isConfigured = false;
+ const callTool = vi.fn().mockResolvedValue({ ok: true });
+ const service = makeService({ callTool });
+
+ await service.executeTool(
+ mcpPayload,
+ contextWith(
+ { args: [], command: 'npx', name: 'my-mcp', type: 'stdio' },
+ { activeDeviceId: 'device-1' },
+ ),
+ );
+
+ expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();
+ expect(callTool).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.ts
index 09df02a8c38..f54830fde29 100644
--- a/apps/server/src/services/toolExecution/index.ts
+++ b/apps/server/src/services/toolExecution/index.ts
@@ -1,14 +1,20 @@
import { type ChatToolPayload } from '@lobechat/types';
-import { safeParseJSON } from '@lobechat/utils';
+import { isLocalOrPrivateUrl, safeParseJSON } from '@lobechat/utils';
import debug from 'debug';
import { ConnectorToolPermission } from '@/database/schemas';
-import { type CloudMCPParams, type StdioMCPParams, type ToolCallContent } from '@/libs/mcp';
+import {
+ type CloudMCPParams,
+ type HttpMCPClientParams,
+ type StdioMCPParams,
+ type ToolCallContent,
+} from '@/libs/mcp';
import {
buildBlockedToolResponse,
getConnectorToolPermission,
} from '@/libs/mcp/connectorPermissionCheck';
import { deviceGateway } from '@/server/services/deviceGateway';
+import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
import { contentBlocksToString } from '@/server/services/mcp/contentProcessor';
import {
DEFAULT_TOOL_RESULT_MAX_LENGTH,
@@ -19,6 +25,7 @@ import { DiscoverService } from '../discover';
import { type MCPService } from '../mcp';
import { type BuiltinToolsExecutor } from './builtin';
import { classifyToolError } from './errorClassification';
+import { resolveRunWorkspaceId } from './serverRuntimes/resolveWorkspaceScope';
import {
type ToolExecutionContext,
type ToolExecutionResult,
@@ -220,18 +227,33 @@ export class ToolExecutionService {
return await this.executeCloudMCPTool(payload, context, mcpParams);
}
- // 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' &&
- deviceGateway.isConfigured &&
- context.activeDeviceId &&
- context.userId
- ) {
- return await this.executeMcpViaDevice(payload, context, mcpParams);
+ // MCP servers only the user's machine can reach must not be called from
+ // the cloud: stdio (the binary lives on the user's machine) and
+ // localhost / private-network HTTP endpoints (the cloud's fetch can't
+ // reach them, #16533). When a device gateway is configured (cloud
+ // deployment), such calls MUST tunnel to a device β€” with no reachable
+ // device, fail fast with an actionable error instead of spawning the
+ // command / fetching the private URL on the server (the same rule the
+ // classic-path guard in connector exec enforces). Standalone Electron /
+ // self-host (no gateway) falls through to the in-process MCP service
+ // below, which legitimately runs on the user's machine or LAN.
+ const isDeviceOnlyMcp =
+ mcpParams.type === 'stdio' ||
+ (mcpParams.type === 'http' && isLocalOrPrivateUrl(mcpParams.url));
+ if (isDeviceOnlyMcp && deviceGateway.isConfigured) {
+ const tunnelTarget = context.userId
+ ? await this.resolveMcpTunnelTarget(context)
+ : 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 device was found to run it β€” open the LobeHub desktop app on the machine that hosts this MCP server, then retry.`;
+ return {
+ content: message,
+ error: { code: 'MCP_DEVICE_UNAVAILABLE', message },
+ success: false,
+ };
+ }
+ return await this.executeMcpViaDevice(payload, context, mcpParams, tunnelTarget);
}
// For stdio (in-process) / http/sse types, use standard MCP service
@@ -262,39 +284,121 @@ 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.
+ * Resolve which device a device-only MCP call should tunnel to.
+ *
+ * Prefer the run's plan-routed device. Chat-mode runs, however, carry no
+ * device execution plan (`resolveExecutionPlan` returns `kind: 'none'` for
+ * chat) even though the user's MCP connectors are still enabled β€” without a
+ * fallback every stdio / local-HTTP tool call in a plain chat would fail.
+ * Fall back to the user's most recently active online PERSONAL device β€”
+ * workspace runs get no implicit fallback (see inline comment).
+ *
+ * Deliberately NOT gated on `context.deviceCapable`: that flag governs the
+ * device-TOOL surface (local-system shell/file access). Tunneling an MCP
+ * connection the user explicitly installed grants the model no machine
+ * access beyond the MCP server itself, so it is treated as connection
+ * routing, not device capability.
+ */
+ private async resolveMcpTunnelTarget(
+ context: ToolExecutionContext,
+ ): Promise<{ deviceId: string; workspaceId?: string } | 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
+ // do (respects a personal-scope active device, recovers the agent's
+ // workspace when the run context lost it).
+ const workspaceId = await resolveRunWorkspaceId(context);
+ if (context.activeDeviceId) return { deviceId: context.activeDeviceId, workspaceId };
+ // The implicit fallback is PERSONAL-scope only. In a workspace run the
+ // connector may have been authorized by ANOTHER member, and tunneling its
+ // params (stdio env / HTTP auth) to the caller's own newest device would
+ // hand that member's credentials to a machine they never authorized. With
+ // no plan-routed device and no connector→device ownership tie, fail closed
+ // (caller surfaces MCP_DEVICE_UNAVAILABLE).
+ if (workspaceId) return undefined;
+ // The scoped helper (not the raw gateway pool) is mandatory here: it
+ // applies device visibility and merges DB state. No serverDB β†’ can't
+ // apply visibility β†’ fail closed.
+ if (!context.userId || !context.serverDB) return undefined;
+ try {
+ const devices = await getScopedOnlineDevices(context.serverDB, context.userId, undefined);
+ // Already sorted online-first / most-recently-active; 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;
+ } catch {
+ return undefined;
+ }
+ }
+
+ /**
+ * Execute an MCP tool call on the user's device via the device gateway.
+ * Forwards the connection params so the device can reach the MCP server β€”
+ * something the cloud server cannot do: stdio spawns the local binary,
+ * http covers localhost / LAN endpoints only the device's network sees.
+ * Credentials for http are decrypted server-side and forwarded verbatim
+ * (narrowed to the token fields β€” never the OAuth client secret / refresh
+ * token). Callers must ensure `userId` is set and pass a resolved tunnel
+ * target (device + workspace scope).
*/
private async executeMcpViaDevice(
payload: ChatToolPayload,
context: ToolExecutionContext,
- mcpParams: StdioMCPParams,
+ mcpParams: StdioMCPParams | HttpMCPClientParams,
+ target: { deviceId: string; workspaceId?: string },
): Promise<ToolExecutionResult> {
const { identifier, apiName, arguments: args } = payload;
log(
- 'Executing stdio MCP tool via device: %s:%s (device=%s)',
+ 'Executing %s MCP tool via device: %s:%s (device=%s, workspace=%s)',
+ mcpParams.type,
identifier,
apiName,
- context.activeDeviceId,
+ target.deviceId,
+ target.workspaceId ?? 'personal',
);
const result = await deviceGateway.executeMcpCall(
{
apiName,
arguments: args,
- deviceId: context.activeDeviceId!,
+ deviceId: target.deviceId,
identifier,
- params: {
- args: mcpParams.args ?? [],
- command: mcpParams.command,
- env: mcpParams.env,
- name: mcpParams.name,
- type: 'stdio',
- },
+ params:
+ mcpParams.type === 'stdio'
+ ? {
+ args: mcpParams.args ?? [],
+ command: mcpParams.command,
+ env: mcpParams.env,
+ name: mcpParams.name,
+ type: 'stdio',
+ }
+ : {
+ // AuthConfig also carries OAuth client secrets / refresh tokens β€”
+ // forward only what the device's MCP client needs to authenticate.
+ auth: mcpParams.auth
+ ? {
+ accessToken: mcpParams.auth.accessToken,
+ token: mcpParams.auth.token,
+ type: mcpParams.auth.type,
+ }
+ : undefined,
+ headers: mcpParams.headers,
+ name: mcpParams.name,
+ type: 'http',
+ url: mcpParams.url,
+ },
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
+ // online workspace-shared device.
+ workspaceId: target.workspaceId,
},
context.executionTimeoutMs,
);
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index 09238a9e625..c18721e2b3e 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -1,7 +1,7 @@
import type {
DeviceSystemInfo,
GatewayDevice,
- GatewayMcpStdioParams,
+ GatewayMcpParams,
GatewayToolCallType,
} from './types';
@@ -79,20 +79,20 @@ export class GatewayHttpClient {
}
/**
- * Tunnel a stdio MCP tool call to the device. Rides the same
+ * Tunnel an 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.
+ * forwards `toolCall` opaquely β€” but carries `params` (the MCP connection
+ * params) so the device routes it to its local MCP client rather than the
+ * builtin local-system tool switch. Used when only the device can reach the
+ * MCP server: stdio (the cloud can't spawn the user's binary) and
+ * localhost / LAN HTTP endpoints (the cloud's fetch can't reach them).
*/
async executeMcpCall(mcpCall: {
apiName: string;
arguments: string;
deviceId?: string;
identifier: string;
- params: GatewayMcpStdioParams;
+ params: GatewayMcpParams;
timeout?: number;
userId: string;
workspaceId?: string;
@@ -116,7 +116,7 @@ export class GatewayHttpClient {
apiName: string;
arguments: string;
identifier: string;
- params?: GatewayMcpStdioParams;
+ params?: GatewayMcpParams;
type?: GatewayToolCallType;
},
): Promise<DeviceToolCallResult> {
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index 28b3b927589..326a1b63068 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -103,6 +103,23 @@ export interface GatewayMcpStdioParams {
type: 'stdio';
}
+/**
+ * HTTP MCP connection params forwarded to the device for a tunneled MCP tool
+ * call. Used for endpoints only the device's network can reach (localhost /
+ * LAN MCP servers) β€” the cloud server's fetch would fail. Credentials are
+ * decrypted server-side and forwarded verbatim; the device stores nothing.
+ */
+export interface GatewayMcpHttpParams {
+ auth?: { accessToken?: string; token?: string; type: 'none' | 'bearer' | 'oauth2' };
+ headers?: Record<string, string>;
+ name: string;
+ type: 'http';
+ url: string;
+}
+
+/** MCP connection params for a tunneled call β€” discriminated on `type`. */
+export type GatewayMcpParams = GatewayMcpStdioParams | GatewayMcpHttpParams;
+
/**
* How the device should execute a tunneled tool call. Explicit so routing never
* depends on structural sniffing (e.g. "does `params` exist?") β€” the gateway
@@ -124,8 +141,8 @@ export interface ToolCallRequestMessage {
apiName: string;
arguments: string;
identifier: string;
- /** Stdio MCP connection params β€” present only when `type === 'mcp'`. */
- params?: GatewayMcpStdioParams;
+ /** MCP connection params (stdio or http) β€” present only when `type === 'mcp'`. */
+ params?: GatewayMcpParams;
/**
* Routing discriminator. `'mcp'` β†’ the device's local MCP client (spawns
* the stdio server); `'tool'` (or omitted, for back-compat with older
@@ -254,11 +271,7 @@ export type ServerMessage =
// ─── Client Types ───
export type ConnectionStatus =
- | 'authenticating'
- | 'connected'
- | 'connecting'
- | 'disconnected'
- | 'reconnecting';
+ 'authenticating' | 'connected' | 'connecting' | 'disconnected' | 'reconnecting';
export interface GatewayClientEvents {
agent_run_request: (request: AgentRunRequestMessage) => void;
diff --git a/src/features/Connectors/AddConnectorModal/index.tsx b/src/features/Connectors/AddConnectorModal/index.tsx
index 88a22af86fb..ab8f4050528 100644
--- a/src/features/Connectors/AddConnectorModal/index.tsx
+++ b/src/features/Connectors/AddConnectorModal/index.tsx
@@ -148,7 +148,7 @@ const AddConnectorModal = memo<AddConnectorModalProps>(({ open, onClose, connect
// client_id present β†’ pre-registration; absent β†’ dynamic client registration (DCR).
const scheme = trimmedClientId ? 'pre_registration' : 'dcr';
- const newConnectorId = await createConnector({
+ const { id: newConnectorId } = await createConnector({
identifier: name.toLowerCase().replaceAll(/\s+/g, '-'),
mcpConnectionType: 'http',
mcpServerUrl: url.trim(),
diff --git a/src/features/Connectors/CustomConnectorModal/index.tsx b/src/features/Connectors/CustomConnectorModal/index.tsx
index 55fb3c59f13..4f752716e19 100644
--- a/src/features/Connectors/CustomConnectorModal/index.tsx
+++ b/src/features/Connectors/CustomConnectorModal/index.tsx
@@ -222,7 +222,9 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
// `legacyPlugin` via `editValue`, so anything the user edited (or left
// alone) is already inside `value`. Hand it to the orchestrator.
const result = await executeLegacyMigrationSave(legacyPlugin, value, {
- createConnector,
+ // The migration orchestrator predates the server-reported `isNew`
+ // and still keys its rollback on `hasExistingConnector` below.
+ createConnector: async (payload) => (await createConnector(payload)).id,
deleteConnector,
// Read fresh so the rollback only deletes a connector this migration
// created, never one the idempotent upsert merely updated.
@@ -351,7 +353,7 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
const clientId = mcp.auth?.clientId?.trim();
try {
- const newConnectorId = await createConnector({
+ const { id: newConnectorId } = await createConnector({
...base,
oidcConfig: {
clientId: clientId || undefined,
@@ -388,12 +390,26 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
: undefined;
const headers = cleanRecord(mcp.headers);
- const newConnectorId = await createConnector({
+ // `connector.create` is an idempotent upsert on (user, identifier);
+ // `isNew` is the server's verdict on whether this row was freshly
+ // created. A client-cache lookup is NOT a safe substitute: before
+ // `fetchConnectors` completes it reports "absent" for a connector the
+ // server already has, and the rollback below must never delete a
+ // connector the user already had.
+ const { id: newConnectorId, isNew } = await createConnector({
...base,
credentials,
metadata: headers ? { customHeaders: headers } : undefined,
});
- await syncConnectorTools(newConnectorId);
+ try {
+ await syncConnectorTools(newConnectorId);
+ } catch (e) {
+ // Tool sync failed (MCP server unreachable, bad command, …): roll the
+ // freshly created row back so the user isn't left with an "installed"
+ // connector that has 0 tools and an empty permissions page (#16533).
+ if (isNew) await deleteConnector(newConnectorId);
+ throw e;
+ }
};
// In migration mode the Delete button must actually uninstall the legacy
diff --git a/src/libs/mcp/types.ts b/src/libs/mcp/types.ts
index 24a3849b738..0fc722be18d 100644
--- a/src/libs/mcp/types.ts
+++ b/src/libs/mcp/types.ts
@@ -131,7 +131,7 @@ export interface AuthConfig {
type: 'none' | 'bearer' | 'oauth2'; // Expiration timestamp of accessToken
}
-interface HttpMCPClientParams {
+export interface HttpMCPClientParams {
auth?: AuthConfig;
headers?: Record<string, string>;
name: string;
diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.ts
index eceedf73763..00d196c9f7e 100644
--- a/src/store/tool/slices/connector/action.ts
+++ b/src/store/tool/slices/connector/action.ts
@@ -1,5 +1,9 @@
+import { isDesktop } from '@lobechat/const';
+import { isLocalOrPrivateUrl } from '@lobechat/utils';
+
import type { ConnectorToolPermission } from '@/database/schemas';
import { lambdaClient } from '@/libs/trpc/client';
+import { mcpService } from '@/services/mcp';
import type { StoreSetter } from '@/store/types';
import type { ToolStore } from '../../store';
@@ -104,14 +108,20 @@ export class ConnectorActionImpl {
return lambdaClient.connector.getForEdit.query({ id });
};
+ /**
+ * Create (or idempotently update) a connector. `isNew` is the server's
+ * knowledge of whether the row was freshly created β€” callers that roll back
+ * on a later sync failure must use it instead of a client-side cache check,
+ * which is unreliable before `fetchConnectors` has completed.
+ */
createConnector = async (
params: Parameters<typeof lambdaClient.connector.create.mutate>[0],
- ): Promise<string> => {
+ ): Promise<{ id: string; isNew: boolean }> => {
this.#set({ connectorCreating: true }, false, 'createConnector/start');
try {
const created = await lambdaClient.connector.create.mutate(params);
await this.fetchConnectors();
- return created.id;
+ return { id: created.id, isNew: created.isNew };
} finally {
this.#set({ connectorCreating: false }, false, 'createConnector/end');
}
@@ -161,7 +171,8 @@ export class ConnectorActionImpl {
'syncConnectorTools/start',
);
try {
- await lambdaClient.connector.syncTools.mutate({ id });
+ const syncedLocally = await this.#syncLocalConnectorTools(id);
+ if (!syncedLocally) await lambdaClient.connector.syncTools.mutate({ id });
await this.#refreshConnectorLists();
} finally {
this.#set(
@@ -172,6 +183,75 @@ export class ConnectorActionImpl {
}
};
+ /**
+ * Desktop-only install/refresh path for connectors the cloud server cannot
+ * reach itself: stdio MCP (must spawn on this machine) and local/private
+ * network HTTP endpoints. The server-side `syncTools` would try to connect
+ * FROM the cloud and fail with "Failed to start MCP service process" /
+ * "fetch failed" (#16533), so the client lists the tools locally (via the
+ * Electron main process, same path Test Connection uses) and reports them
+ * through `syncToolsFromClientById`.
+ *
+ * Returns false when the connector is server-reachable (public HTTP) or when
+ * not running in desktop β€” the caller falls back to the server-side sync.
+ */
+ #syncLocalConnectorTools = async (id: string): Promise<boolean> => {
+ if (!isDesktop) return false;
+
+ // `getForEdit` returns the decrypted user-set credentials (bearer/apikey/
+ // header) needed to connect locally. OAuth2 tokens are machine-managed and
+ // never leave the server β€” but OAuth against a localhost endpoint would be
+ // server-unreachable anyway, so that combination stays on the server path.
+ const detail = await lambdaClient.connector.getForEdit.query({ id });
+ const isStdio = detail.mcpConnectionType === 'stdio';
+ const isLocalHttp = !!detail.mcpServerUrl && isLocalOrPrivateUrl(detail.mcpServerUrl);
+ if (!isStdio && !isLocalHttp) return false;
+
+ let api: Array<{ description?: string; name: string; parameters?: Record<string, unknown> }>;
+ if (isStdio) {
+ if (!detail.mcpStdioConfig?.command) throw new Error('Connector is missing stdio config');
+ const manifest = await mcpService.getStdioMcpServerManifest({
+ args: detail.mcpStdioConfig.args ?? [],
+ command: detail.mcpStdioConfig.command,
+ env: detail.mcpStdioConfig.env ?? undefined,
+ name: detail.identifier,
+ });
+ api = manifest.api ?? [];
+ } else {
+ const credentials = detail.credentials;
+ const auth =
+ credentials?.type === 'bearer'
+ ? { token: credentials.token, type: 'bearer' as const }
+ : credentials?.type === 'apikey'
+ ? { token: credentials.apiKey, type: 'bearer' as const }
+ : undefined;
+ // Custom headers live in metadata.customHeaders; legacy rows stored them
+ // as a 'header' credential β€” merge both, mirroring the server-side
+ // buildConnectorMcpParams.
+ const headerCreds = credentials?.type === 'header' ? credentials.headers : undefined;
+ const customHeaders = detail.metadata?.customHeaders as Record<string, string> | undefined;
+ const headers =
+ headerCreds || customHeaders ? { ...headerCreds, ...customHeaders } : undefined;
+ const manifest = await mcpService.getStreamableMcpServerManifest({
+ auth,
+ headers,
+ identifier: detail.identifier,
+ url: detail.mcpServerUrl!,
+ });
+ api = manifest.api ?? [];
+ }
+
+ await lambdaClient.connector.syncToolsFromClientById.mutate({
+ id,
+ tools: api.map((a) => ({
+ description: a.description,
+ inputSchema: a.parameters,
+ toolName: a.name,
+ })),
+ });
+ return true;
+ };
+
disconnectConnector = async (id: string): Promise<void> => {
await lambdaClient.connector.update.mutate({
id,