π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
fix(mcp): keep stdio execution on desktop devices (#21253)
Bryanfbed5609a96f
diff --git a/apps/server/src/globalConfig/getServerGlobalConfig.test.ts b/apps/server/src/globalConfig/getServerGlobalConfig.test.tsindex 037b81d7352..84700de5c96 100644--- a/apps/server/src/globalConfig/getServerGlobalConfig.test.ts+++ b/apps/server/src/globalConfig/getServerGlobalConfig.test.ts@@ -287,6 +287,18 @@ describe('getServerGlobalConfig', () => {).resolves.toHaveProperty('oidcIssuer', 'https://chat.example.com/oidc');});+ it('reports internal device gateway configuration independently of its public URL', async () => {+ vi.stubEnv('DEVICE_GATEWAY_URL', undefined);+ vi.stubEnv('DEVICE_GATEWAY_PUBLIC_URL', 'https://public-gateway.example.com');+ await expect(loadServerConfig(false)).resolves.toHaveProperty('deviceGatewayConfigured', false);++ vi.stubEnv('DEVICE_GATEWAY_URL', 'https://internal-gateway.example.com');+ vi.stubEnv('DEVICE_GATEWAY_PUBLIC_URL', undefined);+ const config = await loadServerConfig(false);+ expect(config.deviceGatewayConfigured).toBe(true);+ expect(config.deviceGatewayUrl).toBeUndefined();+ });+it('should omit the OIDC issuer when APP_URL is not configured', async () => {await expect(loadServerConfig(false)).resolves.not.toHaveProperty('oidcIssuer');});diff --git a/apps/server/src/globalConfig/index.ts b/apps/server/src/globalConfig/index.tsindex 0b7c0fffe70..88bcb67feed 100644--- a/apps/server/src/globalConfig/index.ts+++ b/apps/server/src/globalConfig/index.ts@@ -151,6 +151,7 @@ export const getServerGlobalConfig = async () => {defaultAgent: {config: parseAgentConfig(DEFAULT_AGENT_CONFIG),},+ deviceGatewayConfigured: !!gatewayEnv.DEVICE_GATEWAY_URL,// Never fall back to the server-internal DEVICE_GATEWAY_URL....(gatewayEnv.DEVICE_GATEWAY_PUBLIC_URL? { deviceGatewayUrl: gatewayEnv.DEVICE_GATEWAY_PUBLIC_URL }diff --git a/apps/server/src/routers/lambda/connector.getForEdit.test.ts b/apps/server/src/routers/lambda/connector.getForEdit.test.tsnew file mode 100644index 00000000000..0a72f3e4188--- /dev/null+++ b/apps/server/src/routers/lambda/connector.getForEdit.test.ts@@ -0,0 +1,75 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { ConnectorModel } from '@/database/models/connector';+import { ConnectorToolModel } from '@/database/models/connectorTool';++import { connectorRouter } from './connector';++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 { trpc } = await import('@/libs/trpc/lambda/init');+ return {+ requireWorkspaceRoleWhenScoped: () => trpc.middleware((opts) => opts.next()),+ wsCompatProcedure: trpc.procedure,+ };+});+vi.mock('@/libs/trpc/lambda/middleware', async () => {+ const { trpc } = await import('@/libs/trpc/lambda/init');+ return {+ serverDatabase: trpc.middleware((opts) =>+ opts.next({ ctx: { ...opts.ctx, serverDB: {} as never } }),+ ),+ };+});++const connector = {+ id: '9f1f6f30-0000-4000-8000-000000000001',+ identifier: 'local-mcp',+ isEnabled: true,+ mcpConnectionType: 'stdio',+ mcpStdioConfig: { command: 'node', env: { TOKEN: 'fresh-secret' } },+ userId: 'creator',+};+const tools = [{ toolName: 'read_file', permission: 'disabled' }];+const queryByConnector = vi.fn();++describe('connectorRouter.getForEdit', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(ConnectorModel).mockImplementation(function () {+ return { findById: vi.fn().mockResolvedValue(connector) } as never;+ });+ vi.mocked(ConnectorToolModel).mockImplementation(function () {+ return { queryByConnector } as never;+ });+ queryByConnector.mockResolvedValue(tools);+ });++ const caller = (userId: string) =>+ connectorRouter.createCaller({+ userId,+ workspaceId: 'workspace',+ workspaceRole: 'member',+ } as never);++ it('returns current tool permissions with the protected stdio configuration', async () => {+ await expect(caller('creator').getForEdit({ id: connector.id })).resolves.toMatchObject({+ mcpStdioConfig: connector.mcpStdioConfig,+ tools,+ });+ });++ it('keeps credentials and tool reads behind the creator gate', async () => {+ await expect(caller('another-member').getForEdit({ id: connector.id })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect(queryByConnector).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.tsindex 750b9de07e1..2bfa63fa1f2 100644--- a/apps/server/src/routers/lambda/connector.ts+++ b/apps/server/src/routers/lambda/connector.ts@@ -276,7 +276,8 @@ export const connectorRouter = router({// to know an OAuth flow is configured (reflected via oidcConfig presence).const safeCredentials = credentials?.type === 'oauth2' ? null : credentials;- return { ...rest, credentials: safeCredentials, oidcConfig: safeOidcConfig };+ const tools = await ctx.connectorToolModel.queryByConnector(connector.id);+ return { ...rest, credentials: safeCredentials, oidcConfig: safeOidcConfig, tools };}),/**diff --git a/apps/server/src/services/connector/exec.test.ts b/apps/server/src/services/connector/exec.test.tsindex d26e012397b..2b170263ca1 100644--- a/apps/server/src/services/connector/exec.test.ts+++ b/apps/server/src/services/connector/exec.test.ts@@ -140,27 +140,27 @@ 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();- });+ // Stdio is always device-only. Private HTTP is device-only when a gateway+ // is configured; self-hosted servers without one can still access their LAN.+ describe('device-only endpoints', () => {+ it.each([false, true])(+ 'rejects a stdio connector with gateway configured: %s',+ async (configured) => {+ (deviceGateway as any).isConfigured = configured;+ 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;diff --git a/apps/server/src/services/connector/exec.ts b/apps/server/src/services/connector/exec.tsindex 0065da3044f..25357eb01f6 100644--- a/apps/server/src/services/connector/exec.ts+++ b/apps/server/src/services/connector/exec.ts@@ -83,20 +83,19 @@ 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 =+ // Stdio runs on a desktop device, never in the server process. Private HTTP+ // endpoints also require a device when a gateway is configured; self-hosted+ // servers without a gateway can still connect to their own LAN over HTTP.+ const requiresDevice =connector.mcpConnectionType === ConnectorMcpConnectionType.stdio ||- (!!connector.mcpServerUrl && isLocalOrPrivateUrl(connector.mcpServerUrl));- if (deviceGateway.isConfigured && isDeviceOnlyEndpoint) {+ (deviceGateway.isConfigured &&+ !!connector.mcpServerUrl &&+ isLocalOrPrivateUrl(connector.mcpServerUrl));+ if (requiresDevice) {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.',+ 'Run these tools in the desktop app through a configured device gateway.',);}diff --git a/apps/server/src/services/toolExecution/__tests__/index.test.ts b/apps/server/src/services/toolExecution/__tests__/index.test.tsindex 1bdf4b7d7ac..c8c00e5a8b5 100644--- a/apps/server/src/services/toolExecution/__tests__/index.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/index.test.ts@@ -471,9 +471,8 @@ describe('ToolExecutionService', () => {});});- // 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).+ // Stdio always runs on a desktop device. Private HTTP uses the device when+ // a gateway is configured; public HTTP can run directly on the server.describe('device-only MCP tunneling', () => {const makeService = (mcpService: any = { callTool: vi.fn() }) =>new ToolExecutionService({@@ -719,38 +718,40 @@ describe('ToolExecutionService', () => {);});- it('keeps public HTTP MCP calls in-process on the server', async () => {+ it.each([+ [true, 'https://mcp.example.com'],+ [false, 'http://192.168.1.10:8080/mcp'],+ ])('keeps HTTP MCP calls on the server (gateway: %s, URL: %s)', async (configured, url) => {+ (deviceGateway as any).isConfigured = configured;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' },- ),+ contextWith({ name: 'my-mcp', type: 'http', url }, { 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 () => {+ it.each([+ { name: 'my-mcp', type: 'http', url: 'http://localhost:8080/mcp' },+ { args: [], command: 'npx', name: 'my-mcp', type: 'stdio' },+ ])('fails fast when no device is reachable for $type MCP', async (mcpParams) => {// 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' }),- );+ const result = await service.executeTool(mcpPayload, contextWith(mcpParams));expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();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');});it('fails closed when no serverDB is available to apply device visibility', async () => {@@ -823,12 +824,12 @@ describe('ToolExecutionService', () => {});});- it('runs stdio in-process when no gateway is configured (standalone Electron)', async () => {+ it('rejects stdio when no gateway is configured instead of executing on the server', async () => {(deviceGateway as any).isConfigured = false;const callTool = vi.fn().mockResolvedValue({ ok: true });const service = makeService({ callTool });- await service.executeTool(+ const result = await service.executeTool(mcpPayload,contextWith({ args: [], command: 'npx', name: 'my-mcp', type: 'stdio' },@@ -837,7 +838,11 @@ describe('ToolExecutionService', () => {);expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();- expect(callTool).toHaveBeenCalledTimes(1);+ expect(result.success).toBe(false);+ expect(result.error).toMatchObject({ code: 'MCP_GATEWAY_NOT_CONFIGURED' });+ expect(result.content).toContain('device gateway is not configured');+ expect(result.content).toContain('Configure a device gateway');+ expect(callTool).not.toHaveBeenCalled();});});});diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.tsindex 33c9b0716bc..0e56cce5513 100644--- a/apps/server/src/services/toolExecution/index.ts+++ b/apps/server/src/services/toolExecution/index.ts@@ -287,8 +287,8 @@ export class ToolExecutionService {const isDeviceOnlyMcp = isDeviceOnlyMcpEndpoint(mcpParams);// Agent Share visitor runs execute with the CREATOR's identity, so a- // device-only MCP would tunnel to (or, without a gateway, spawn on) the- // creator's machine on a visitor's behalf. The tool-set gate already drops+ // device-only MCP would access the creator's device or private network+ // on a visitor's behalf. The tool-set gate already drops// these manifests (`applyShareGateToToolSet`); this is the unbypassable// dispatch-site check, mirroring `isShareBlockedBuiltinDispatch`.if (context.agentShareVisitor && isDeviceOnlyMcp) {@@ -307,17 +307,20 @@ export class ToolExecutionService {return await this.executeCloudMCPTool(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.- if (isDeviceOnlyMcp && deviceGateway.isConfigured) {+ // Stdio must run on a desktop 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.`;+ return {+ content: message,+ error: { code: 'MCP_GATEWAY_NOT_CONFIGURED', message },+ success: false,+ };+ }+const tunnelTarget = context.userId? await this.resolveMcpTunnelTarget(context): undefined;@@ -333,7 +336,7 @@ export class ToolExecutionService {return await this.executeMcpViaDevice(payload, context, mcpParams, tunnelTarget);}- // For stdio (in-process) / http/sse types, use standard MCP service+ // HTTP MCP endpoints can execute through the server-side MCP service.const result = await this.mcpService.callTool({argsStr: args,clientParams: mcpParams,diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.tsindex 3ac5a21d141..01e40458984 100644--- a/packages/types/src/serverConfig.ts+++ b/packages/types/src/serverConfig.ts@@ -132,6 +132,8 @@ export interface GlobalServerConfig {agentGatewayUrl?: string;aiProvider: ServerLanguageModel;defaultAgent?: PartialDeep<UserDefaultAgent>;+ /** Whether the server has DEVICE_GATEWAY_URL configured, independent of its public URL. */+ deviceGatewayConfigured?: boolean;/*** Public Device Gateway base URL (`DEVICE_GATEWAY_PUBLIC_URL`). Absent when not* configured; clients then keep the address they manage themselves.diff --git a/src/services/mcp.test.ts b/src/services/mcp.test.tsindex b514db4ed35..709b2abaac1 100644--- a/src/services/mcp.test.ts+++ b/src/services/mcp.test.ts@@ -13,13 +13,26 @@ const mockElectronIpc = {},};+const environment = vi.hoisted(() => ({+ isDesktop: false,+ deviceGatewayConfigured: undefined as boolean | undefined,+}));++vi.mock('@/store/serverConfig/store', () => ({+ getServerConfigStoreState: () => ({+ serverConfig: { deviceGatewayConfigured: environment.deviceGatewayConfigured },+ }),+}));+// Mock dependencies. Spread the real module: the connector slice this service// pulls in lazily now reaches the user store chain, which reads `DEFAULT_AGENT`// from `@lobechat/const` β a partial factory would break on that missing export.vi.mock('@lobechat/const', async (importOriginal) => ({...((await importOriginal()) as Record<string, unknown>),CURRENT_VERSION: '1.0.0',- isDesktop: false,+ get isDesktop() {+ return environment.isDesktop;+ },}));vi.mock('@lobechat/utils', () => ({@@ -36,6 +49,12 @@ vi.mock('@lobechat/utils', () => ({}));vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ connector: {+ callTool: { mutate: vi.fn() },+ getForEdit: { query: vi.fn() },+ },+ },toolsClient: {market: {callCloudMcpEndpoint: {@@ -83,10 +102,106 @@ describe('MCPService', () => {beforeEach(() => {vi.clearAllMocks();vi.resetModules();+ environment.isDesktop = false;+ environment.deviceGatewayConfigured = undefined;mockGetToolStoreState.mockReturnValue({});});describe('invokeMcpToolCall', () => {+ describe('stdio connectors', () => {+ const payload: ChatToolPayload = {+ id: 'local-call',+ identifier: 'local-connector',+ apiName: 'read_file',+ arguments: '{"path":"test.txt"}',+ type: 'standalone',+ };+ const connector = {+ id: 'connector-id',+ identifier: payload.identifier,+ isEnabled: true,+ mcpConnectionType: 'stdio',+ };+ const detail = {+ ...connector,+ mcpStdioConfig: { command: 'node', args: ['mcp.js'], env: { TOKEN: 'fresh-secret' } },+ tools: [{ toolName: 'read_file', permission: 'auto' }],+ };++ beforeEach(async () => {+ environment.isDesktop = true;+ environment.deviceGatewayConfigured = false;+ mockGetToolStoreState.mockReturnValue({ connectors: [connector] });+ const { lambdaClient } = await import('@/libs/trpc/client');+ vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue(detail as never);+ });++ it('executes through local IPC with fresh configuration when no gateway is configured', async () => {+ const { lambdaClient } = await import('@/libs/trpc/client');+ const result = {+ content: 'local result',+ state: { content: [{ type: 'text', text: 'local result' }] },+ success: true,+ };+ mockElectronIpc.mcp.callTool.mockResolvedValue(superjson.serialize(result));++ await expect(mcpService.invokeMcpToolCall(payload, {})).resolves.toEqual(result);+ expect(superjson.deserialize(mockElectronIpc.mcp.callTool.mock.calls[0][0])).toEqual({+ args: { path: 'test.txt' },+ env: detail.mcpStdioConfig.env,+ params: { command: 'node', args: ['mcp.js'], name: payload.identifier, type: 'stdio' },+ toolName: 'read_file',+ });+ expect(lambdaClient.connector.callTool.mutate).not.toHaveBeenCalled();+ });++ it.each([+ { desktop: true, gateway: true },+ { desktop: true, gateway: undefined },+ { desktop: false, gateway: false },+ ])(+ 'preserves the server route for desktop=$desktop gateway=$gateway',+ async ({ desktop, gateway }) => {+ environment.isDesktop = desktop;+ environment.deviceGatewayConfigured = gateway;+ const { lambdaClient } = await import('@/libs/trpc/client');+ const result = {+ content: 'server result',+ state: { content: [{ type: 'text', text: 'server result' }] },+ success: true,+ };+ vi.mocked(lambdaClient.connector.callTool.mutate).mockResolvedValue(result as never);++ await expect(mcpService.invokeMcpToolCall(payload, {})).resolves.toEqual(result);+ expect(lambdaClient.connector.getForEdit.query).not.toHaveBeenCalled();+ expect(mockElectronIpc.mcp.callTool).not.toHaveBeenCalled();+ },+ );++ it.each([+ { ...detail, isEnabled: false },+ { ...detail, tools: [] },+ { ...detail, tools: [{ toolName: 'read_file', permission: 'disabled' }] },+ ])('rejects a newly disabled connector or unavailable tool before IPC', async (current) => {+ const { lambdaClient } = await import('@/libs/trpc/client');+ vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue(current as never);++ await expect(mcpService.invokeMcpToolCall(payload, {})).rejects.toThrow();+ expect(mockElectronIpc.mcp.callTool).not.toHaveBeenCalled();+ expect(lambdaClient.connector.callTool.mutate).not.toHaveBeenCalled();+ });++ it('does not execute when the protected configuration read is denied', async () => {+ const { lambdaClient } = await import('@/libs/trpc/client');+ vi.mocked(lambdaClient.connector.getForEdit.query).mockRejectedValue(+ new Error('FORBIDDEN'),+ );++ await expect(mcpService.invokeMcpToolCall(payload, {})).rejects.toThrow('FORBIDDEN');+ expect(mockElectronIpc.mcp.callTool).not.toHaveBeenCalled();+ });+ });+it('should invoke tool call with installed plugin', async () => {const { toolsClient } = await import('@/libs/trpc/client');const { discoverService } = await import('./discover');diff --git a/src/services/mcp.ts b/src/services/mcp.tsindex 2bbf1e6bb11..9e507e25b1e 100644--- a/src/services/mcp.ts+++ b/src/services/mcp.ts@@ -11,6 +11,7 @@ import { type CallReportRequest } from '@lobehub/market-types';import { type MCPToolCallResult } from '@/libs/mcp';import { toolsClient } from '@/libs/trpc/client';+import { getServerConfigStoreState } from '@/store/serverConfig/store';import { ensureElectronIpc } from '@/utils/electron/ipc';import { discoverService } from './discover';@@ -43,13 +44,13 @@ class MCPService {const s = getToolStoreState();const { identifier, arguments: args, apiName } = payload;- // Connector-first: custom connectors execute server-side with their stored- // (encrypted) OAuth token, so route them before the plugin path. The client- // has no credentials, hence the dedicated `connector.callTool` endpoint.+ // Connector-first: HTTP connectors use their server-held credentials.+ // Standalone desktop stdio connectors use local IPC; configured device+ // gateways keep the existing server route.// Only connectors with a real MCP endpoint are routed here β Lobehub/Composio// skills synced into the connector store have no mcpServerUrl and keep their// original executor path.- const { connectorSelectors } = await import('@/store/tool/slices/connector');+ const { connectorSelectors } = await import('@/store/tool/slices/connector/selectors');const connector = connectorSelectors.connectorByIdentifier(identifier)(s);if (connector &&@@ -57,6 +58,38 @@ class MCPService {(connector.mcpServerUrl || connector.mcpConnectionType === 'stdio')) {const { lambdaClient } = await import('@/libs/trpc/client');+ if (+ isDesktop &&+ connector.mcpConnectionType === 'stdio' &&+ getServerConfigStoreState()?.serverConfig.deviceGatewayConfigured === false+ ) {+ // Persisted connector projections omit env secrets and may be stale.+ // This protected read retains the connector's credential ownership gate.+ const detail = await lambdaClient.connector.getForEdit.query({ id: connector.id });+ if (!detail.isEnabled) throw new Error('Connector is disabled');+ const tool = detail.tools.find((item) => item.toolName === apiName);+ if (!tool || tool.permission === 'disabled') {+ throw new Error(`Tool '${apiName}' is unavailable or disabled for this connector`);+ }+ const config = detail.mcpStdioConfig;+ if (detail.mcpConnectionType !== 'stdio' || !config?.command) {+ throw new Error('Connector does not have a stdio command configured');+ }+ const result = await ensureElectronIpc().mcp.callTool(+ serializeMcpIpcPayload({+ args: safeParseJSON(args) ?? {},+ env: config.env,+ params: {+ args: config.args ?? [],+ command: config.command,+ name: detail.identifier,+ type: 'stdio',+ },+ toolName: apiName,+ }),+ );+ return deserializeMcpIpcPayload<MCPToolCallResult>(result);+ }return (await lambdaClient.connector.callTool.mutate({ args, identifier, toolName: apiName },{ signal },