π€― 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 MCP sessions alive across tool calls (#21031)
Arvin Xua34a28159ca3
diff --git a/apps/desktop/src/main/controllers/McpCtr.ts b/apps/desktop/src/main/controllers/McpCtr.tsindex 002aa9aedb4..36d7a6fb3f5 100644--- a/apps/desktop/src/main/controllers/McpCtr.ts+++ b/apps/desktop/src/main/controllers/McpCtr.ts@@ -1,7 +1,5 @@-import { exec } from 'node:child_process';import { createHash, randomUUID } from 'node:crypto';import path from 'node:path';-import { promisify } from 'node:util';import {deserializeMcpIpcPayload,@@ -13,6 +11,11 @@ import FileService from '@/services/fileSrv';import { createLogger } from '@/utils/logger';import type { MCPClient } from '../libs/mcp/client';+import {+ isDeadTransportError,+ isStaleSessionError,+ serializeMcpClientParams,+} from '../libs/mcp/sessionGuards';import type {AudioContent,ImageContent,@@ -22,8 +25,8 @@ import type {ToolCallResult,} from '../libs/mcp/types';import { ControllerModule, IpcMethod } from './index';+import { checkDeployOption } from './mcpInstallCheck';-const execPromise = promisify(exec);const logger = createLogger('controllers:McpCtr');const loadMcpClient = () => import('../libs/mcp/client');@@ -32,8 +35,7 @@ const loadMcpClient = () => import('../libs/mcp/client');** We intentionally keep it local to avoid pulling the web app's path-alias* expectations (e.g. `@/config/*`) into the desktop `tsgo` typecheck.- */-interface CheckMcpInstallResult {+ */ interface CheckMcpInstallResult {allDependenciesMet?: boolean;allOptions?: Array<{allDependenciesMet?: boolean;@@ -219,10 +221,204 @@ const toMarkdown = async (export default class McpCtr extends ControllerModule {static override readonly groupName = 'mcp';+ /**+ * Long-lived MCP client pool keyed by serialized connection params.+ *+ * Stateful stdio MCP servers (e.g. IDA's `ida-mcp`: `open_database` sets a+ * current database that later `execute_python` calls depend on) lose their+ * in-process state when the session is torn down between tool calls. The+ * cloud-side MCPService already caches clients; the desktop / device-tunnel+ * path used to spawn a fresh process per call and kill it right after+ * (`finally disconnect()`), silently dropping all server-side state. We now+ * reuse one session per unique connection params, and only rebuild it when+ * a call fails.+ */+ private mcpClientPool = new Map<string, MCPClient>();+ private mcpClientInitialization?: Map<string, Promise<MCPClient>>;++ /**+ * Idle-reap policy for the pool: sessions untouched for longer than this+ * are disconnected and dropped at the next acquire/dispose sweep.+ *+ * Rationale: stdio subprocesses are cheap to respawn but leak when kept+ * forever β a changed token/env/command produces a NEW cache key while the+ * old entry stays connected for the life of the desktop process, so a+ * long-running session could accumulate every obsolete client. The TTL is+ * deliberately long (30 min β« any realistic think-turn between tool calls)+ * so actively used stateful sessions are never reaped mid-workflow: every+ * acquire refreshes lastUsedAt.+ */+ private static readonly MCP_POOL_IDLE_TTL_MS = 30 * 60 * 1000;++ private mcpClientLastUsedAt = new Map<string, number>();++ // In-flight call tracking: eviction and idle reaping are deferred while a+ // client holds any lease; release performs a pending eviction disconnect.+ private mcpClientLeases = new Map<MCPClient, number>();+ private mcpClientPendingDisconnect = new Set<MCPClient>();++ /**+ * App shutdown hook: disconnect every pooled stdio session so no MCP+ * subprocess outlives the desktop process. Electron does not await+ * Promise-returning listeners: every disconnect is initiated+ * synchronously before the first await (never throws).+ */+ async beforeAppReady() {+ const { app } = await import('electron');+ app.once('will-quit', () => {+ void this.disposeAllPooledClients();+ });+ }++ private async disposeAllPooledClients(): Promise<void> {+ const entries = [...this.mcpClientPool.entries()];+ this.mcpClientPool.clear();+ this.mcpClientLastUsedAt.clear();+ const teardowns = entries.map(([, client]) =>+ client.disconnect().catch((error: unknown) => {+ logger.warn('Failed to disconnect MCP client on dispose:', error);+ }),+ );+ await Promise.all(teardowns);+ }+private get fileService() {return this.app.getService(FileService);}+ /**+ * Disconnect and drop every pooled session that has been idle for longer+ * than the TTL. Never throws.+ */+ private async reapIdleClients(): Promise<void> {+ const now = Date.now();+ for (const [key, client] of this.mcpClientPool) {+ const lastUsed = this.mcpClientLastUsedAt.get(key) ?? 0;+ if (now - lastUsed < McpCtr.MCP_POOL_IDLE_TTL_MS) continue;+ // A session with active in-flight calls is still working: disconnecting+ // it mid-call would kill a valid long-running tool invocation (the+ // idle clock only refreshes at acquisition, not during the call).+ if (this.mcpClientLeases.has(client)) continue;+ this.mcpClientPool.delete(key);+ this.mcpClientLastUsedAt.delete(key);+ try {+ await client.disconnect();+ } catch (error) {+ logger.warn('Failed to reap idle MCP client:', error);+ }+ }+ }++ /**+ * Return a pooled client for the given params, creating (and caching) a new+ * one when the pool has no healthy entry. Callers must NOT disconnect the+ * returned client β pooled sessions outlive a single tool call.+ */+ private async acquireClient(params: MCPClientParams): Promise<MCPClient> {+ const key = serializeMcpClientParams(params);++ // Every acquire refreshes the session's idle clock (fire-and-forget β+ // reaping must never delay or fail the tool call it runs alongside).+ this.mcpClientLastUsedAt.set(key, Date.now());+ void this.reapIdleClients().catch(() => {});++ const cached = this.mcpClientPool.get(key);+ if (cached) return cached;++ // Single-flight per key: concurrent manifest discovery + tool call on the+ // same uncached params must share one initialization, not spawn two+ // processes where the later map write silently replaces the first+ // (stranding whatever state the losing client had established).+ const inFlight = this.mcpClientInitialization?.get(key);+ if (inFlight) return inFlight;++ const creating = this.createClient(params)+ .then((client) => {+ this.mcpClientPool.set(key, client);+ this.mcpClientLastUsedAt.set(key, Date.now());+ return client;+ })+ .catch((error) => {+ // The acquire-time clock is an orphan when creation fails: failed+ // configs (serialized keys contain env values) must not accumulate.+ this.mcpClientLastUsedAt.delete(key);+ throw error;+ })+ .finally(() => {+ this.mcpClientInitialization?.delete(key);+ });+ (this.mcpClientInitialization ??= new Map()).set(key, creating);+ return creating;+ }++ /**+ * Run `fn` while holding a lease: eviction and idle reaping are deferred+ * while any lease is active. The last release refreshes the idle clock+ * (a call may outlast the TTL β the session is fresh the moment its work+ * ends, not when it started) and then performs any pending disconnect.+ */+ private async withClientLease<T>(client: MCPClient, fn: () => Promise<T>): Promise<T> {+ this.mcpClientLeases.set(client, (this.mcpClientLeases.get(client) ?? 0) + 1);+ try {+ return await fn();+ } finally {+ const remaining = (this.mcpClientLeases.get(client) ?? 1) - 1;+ if (remaining > 0) this.mcpClientLeases.set(client, remaining);+ else {+ this.mcpClientLeases.delete(client);+ // The idle clock must reflect when the LAST lease ended, not when+ // the call started: an invocation longer than the TTL would+ // otherwise release an already-expired timestamp and an unrelated+ // same-key sweep would disconnect this just-used session.+ for (const [key, pooled] of this.mcpClientPool) {+ if (pooled === client) this.mcpClientLastUsedAt.set(key, Date.now());+ }+ if (this.mcpClientPendingDisconnect.delete(client)) {+ try {+ await client.disconnect();+ } catch (error) {+ logger.warn('Failed to disconnect evicted MCP client:', error);+ }+ }+ }+ }+ }++ /**+ * Drop a pooled session after a failed call so the next attempt starts+ * fresh. Never throws β the original call error matters more than cleanup.+ *+ * Requires the exact client the failed call ran on: without that identity+ * we must not disconnect anything, or a concurrent same-key recreate (call+ * B installing its replacement while call A's initialization fails) would+ * get its live session killed while the pool keeps pointing at it β a+ * permanently dead pooled entry until restart.+ */+ private async evictClient(params: MCPClientParams, client?: MCPClient): Promise<void> {+ if (!client) return;+ const key = serializeMcpClientParams(params);+ const pooled = this.mcpClientPool.get(key);+ // Only evict when the failing call ran on the pooled instance β+ // a concurrent recreate may have already replaced it.+ if (pooled && pooled === client) {+ this.mcpClientPool.delete(key);+ this.mcpClientLastUsedAt.delete(key);+ }+ // Defer the disconnect while the client still has in-flight calls:+ // manifest discovery and tool execution share one pooled session, so an+ // eviction triggered by one of them must not abort the other mid-call.+ // The last lease release performs the deferred disconnect.+ if (this.mcpClientLeases.has(client)) {+ this.mcpClientPendingDisconnect.add(client);+ return;+ }+ try {+ await client.disconnect();+ } catch (error) {+ logger.warn('Failed to disconnect evicted MCP client:', error);+ }+ }+private async createClient(params: MCPClientParams) {const { MCPClient } = await loadMcpClient();const client = new MCPClient(params);@@ -297,8 +493,10 @@ export default class McpCtr extends ControllerModule {let client: MCPClient | undefined;try {- client = await this.createClient(params);- const manifest = await client.listManifests();+ client = await this.acquireClient(params);+ // Lease for the manifest refresh too: a concurrent stale-session+ // eviction must not disconnect underneath this pending request.+ const manifest = await this.withClientLease(client, () => client!.listManifests());const identifier = input.name;const tools = manifest.tools || [];@@ -326,6 +524,11 @@ export default class McpCtr extends ControllerModule {type: 'mcp' as any,});} catch (error) {+ // The pooled session this manifest refresh ran on is stale/broken β+ // evict it so the next refresh starts fresh instead of reacquiring+ // the same dead session forever. Identity-guarded: a concurrent+ // recreate must not be disconnected.+ await this.evictClient(params, client);// If it's an MCPConnectionError with stderr logs, enhance the error messageconst { MCPConnectionError } = await loadMcpClient();if (error instanceof MCPConnectionError && error.stderrLogs.length > 0) {@@ -342,9 +545,7 @@ export default class McpCtr extends ControllerModule {}throw error;} finally {- if (client) {- await client.disconnect();- }+ // Manifest listing shares the pooled session; nothing to clean up here.}}@@ -450,21 +651,85 @@ export default class McpCtr extends ControllerModule {toolName: string,rawArgs: unknown,): Promise<{ content: string; state: unknown; success: boolean }> {- let client: MCPClient | undefined;try {- client = await this.createClient(params);const args = safeParseToRecord(rawArgs);- 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));+ // Reuse the pooled session (stateful stdio servers keep per-process+ // state such as a selected database). Retry once on a fresh session β+ // but only for confirmed stale-session / transport failures that+ // happen before a tool result was produced. App-level failures (tool+ // rejected the args, media post-processing failed, β¦) are surfaced+ // as-is: re-running a mutating tool on a generic catch could apply+ // its side effect a second time. The failing client is tagged onto+ // the error so eviction carries an identity guard.+ const runOn = (client: MCPClient) =>+ this.withClientLease(client, async () => {+ try {+ 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),+ );+ return { content, state: { ...raw, content: processed }, success: true };+ } catch (error) {+ throw Object.assign(error instanceof Error ? error : new Error(String(error)), {+ ranOnClient: client,+ });+ }+ });- return {- content,- state: { ...raw, content: processed },- success: true,- };+ try {+ return await runOn(await this.acquireClient(params));+ } catch (firstError) {+ const failedClient = (firstError as { ranOnClient?: MCPClient })?.ranOnClient;+ if (!isStaleSessionError(firstError)) {+ // A dead stdio subprocess must still be evicted even though the+ // failed call is NOT replayed: the request may have reached the+ // server before the pipe died, so re-running a mutating tool+ // could apply its side effect twice. Without eviction the dead+ // client stays pooled and every later same-key acquisition+ // refreshes and returns the same unusable session until restart.+ if (isDeadTransportError(firstError)) {+ logger.warn('MCP tool call failed on a dead transport, evicting pooled session:', {+ message: (firstError as Error).message,+ toolName,+ });+ await this.evictClient(params, failedClient);+ } else {+ logger.warn('MCP tool call failed (no retry for app-level error):', {+ message: (firstError as Error).message,+ toolName,+ });+ }+ throw firstError;+ }+ logger.warn('MCP tool call failed on pooled session, retrying with a fresh one:', {+ message: (firstError as Error).message,+ toolName,+ });+ await this.evictClient(params, failedClient);+ // Route replacement creation through acquireClient: it single-flights+ // per key, so two concurrent calls that shared the same stale client+ // and both failed build ONE replacement process β not two racing+ // create/set writes that strand the loser (and its established state).+ const retryClient = await this.acquireClient(params);+ try {+ return await runOn(retryClient);+ } catch (retryError) {+ // Evict the replacement on a transport-level failure β stale+ // errors authorize a further retry, dead transports prove the+ // replacement dead: neither is handed to the next call. A+ // post-processing failure after a SUCCESSFUL tool call is not a+ // session problem β the tool already ran, so the healthy+ // replacement stays pooled.+ if (isStaleSessionError(retryError) || isDeadTransportError(retryError)) {+ await this.evictClient(params, retryClient);+ }+ throw retryError;+ }+ }} catch (error) {// If it's an MCPConnectionError with stderr logs, enhance the error messageconst { MCPConnectionError } = await loadMcpClient();@@ -482,209 +747,9 @@ export default class McpCtr extends ControllerModule {}logger.error('callTool failed:', error);throw error;- } finally {- if (client) {- await client.disconnect();- }- }- }-- // ---------- MCP Install Check (local system) ------------ private getInstallInstructions(installInstructions: any) {- if (!installInstructions) return undefined;-- let current: string | undefined;-- switch (process.platform) {- case 'darwin': {- current = installInstructions.macos;- break;- }- case 'linux': {- current = installInstructions.linux_debian || installInstructions.linux;- break;- }- case 'win32': {- current = installInstructions.windows;- break;- }- }-- return { current, manual: installInstructions.manual };- }-- private async checkSystemDependency(dependency: any) {- const checkCommand = dependency.checkCommand || `${dependency.name} --version`;-- try {- const { stdout, stderr } = await execPromise(checkCommand);-- if (stderr && !stdout) {- return {- error: stderr,- installInstructions: this.getInstallInstructions(dependency.installInstructions),- installed: false,- meetRequirement: false,- name: dependency.name,- requiredVersion: dependency.requiredVersion,- };- }-- const output = String(stdout || '').trim();- let version = output;-- if (dependency.versionParsingRequired) {- const versionMatch = output.match(/V?(\d+(\.\d+)*)/i);- if (versionMatch) version = versionMatch[0];- }-- let meetRequirement = true;-- if (dependency.requiredVersion) {- const currentVersion = String(version).replace(/^V/i, '');- const currentNum = Number.parseFloat(currentVersion);-- const requirementMatch = String(dependency.requiredVersion).match(/([<=>]+)?(\d+(\.\d+)*)/);- if (requirementMatch) {- const [, operator = '=', requiredVersion] = requirementMatch;- const requiredNum = Number.parseFloat(requiredVersion);- switch (operator) {- case '>=': {- meetRequirement = currentNum >= requiredNum;- break;- }- case '>': {- meetRequirement = currentNum > requiredNum;- break;- }- case '<=': {- meetRequirement = currentNum <= requiredNum;- break;- }- case '<': {- meetRequirement = currentNum < requiredNum;- break;- }- default: {- meetRequirement = currentNum === requiredNum;- break;- }- }- }- }-- return {- installInstructions: this.getInstallInstructions(dependency.installInstructions),- installed: true,- meetRequirement,- name: dependency.name,- requiredVersion: dependency.requiredVersion,- version,- };- } catch (error) {- return {- error: error instanceof Error ? error.message : 'Unknown error',- installInstructions: this.getInstallInstructions(dependency.installInstructions),- installed: false,- meetRequirement: false,- name: dependency.name,- requiredVersion: dependency.requiredVersion,- };}}- private async checkPackageInstalled(installationMethod: string, details: any) {- if (installationMethod === 'npm') {- const packageName = details?.packageName;- if (!packageName) return { installed: false };-- // Only check global npm list - do NOT use npx as it may download packages- try {- const { stdout } = await execPromise(`npm list -g ${packageName} --depth=0`);- if (!stdout.includes('(empty)') && stdout.includes(packageName)) {- return { installed: true };- }- } catch {- // ignore - package not found in global list- }-- // For npm packages, we don't require pre-installation- // npx will handle downloading and running on-demand during actual MCP connection- return { installed: false };- }-- if (installationMethod === 'python') {- const packageName = details?.packageName;- if (!packageName) return { installed: false };-- const pythonCommand = details?.pythonCommand || 'python';-- try {- const command = `${pythonCommand} -m pip list | grep -i "${packageName}"`;- const { stdout } = await execPromise(command);- if (stdout.trim() && stdout.toLowerCase().includes(String(packageName).toLowerCase())) {- return { installed: true };- }- } catch {- // ignore- }-- try {- const importCommand = `${pythonCommand} -c "import ${String(packageName).replace('-', '_')}; print('Package installed')"`;- const { stdout } = await execPromise(importCommand);- if (stdout.includes('Package installed')) return { installed: true };- } catch {- // ignore- }-- return { installed: false };- }-- // manual or unknown- return { installed: false };- }-- private async checkDeployOption(option: any) {- const systemDependenciesResults = [];-- if (Array.isArray(option.systemDependencies) && option.systemDependencies.length > 0) {- for (const dep of option.systemDependencies) {- systemDependenciesResults.push(await this.checkSystemDependency(dep));- }- }-- const packageResult = await this.checkPackageInstalled(- option.installationMethod,- option.installationDetails,- );- const packageInstalled = Boolean((packageResult as any).installed);-- const allDependenciesMet = systemDependenciesResults.every((dep: any) => dep.meetRequirement);-- const configSchema = option.connection?.configSchema;- const needsConfig = Boolean(- configSchema &&- ((Array.isArray(configSchema.required) && configSchema.required.length > 0) ||- (configSchema.properties &&- Object.values(configSchema.properties).some((prop: any) => prop.required === true))),- );-- const connection = option.connection?.url- ? { ...option.connection, type: 'http' }- : { ...option.connection, type: 'stdio' };-- return {- allDependenciesMet,- configSchema,- connection,- isRecommended: option.isRecommended,- needsConfig,- packageInstalled,- systemDependencies: systemDependenciesResults,- };- }-@IpcMethod()async validMcpServerInstallable(payload: SuperJSONSerialized<{@@ -697,7 +762,7 @@ export default class McpCtr extends ControllerModule {const results = [];for (const option of options) {- results.push(await this.checkDeployOption(option));+ results.push(await checkDeployOption(option));}const recommendedResult = results.find((r: any) => r.isRecommended && r.allDependenciesMet);diff --git a/apps/desktop/src/main/controllers/__tests__/McpCtr.session-reuse.test.ts b/apps/desktop/src/main/controllers/__tests__/McpCtr.session-reuse.test.tsnew file mode 100644index 00000000000..e9430f42cde--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/McpCtr.session-reuse.test.ts@@ -0,0 +1,718 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import McpCtr from '../McpCtr';++const { mcpClientMocks } = vi.hoisted(() => ({+ mcpClientMocks: vi.fn(),+}));++// The controller lazily imports the MCP client module; mock the module so no+// real stdio process is ever spawned. The specifier must mirror the+// controller's own dynamic import (`../libs/mcp/client` relative to McpCtr.ts).+vi.mock('../../libs/mcp/client', () => ({+ MCPClient: class {+ constructor(public params: unknown) {+ return mcpClientMocks();+ }+ },+ MCPConnectionError: class extends Error {+ name = 'MCPConnectionError';+ stderrLogs: string[] = [];+ },+}));++const mockApp = {+ getService: vi.fn(() => null),+} as unknown as App;++const makeClientInstance = (label: string) => ({+ callTool: vi.fn().mockImplementation(async () => ({+ content: [{ text: `${label}-result`, type: 'text' }],+ isError: false,+ })),+ disconnect: vi.fn().mockResolvedValue(undefined),+ initialize: vi.fn().mockResolvedValue(undefined),+ listManifests: vi.fn().mockResolvedValue({ tools: [] }),+});++describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {+ let ctr: McpCtr;++ beforeEach(() => {+ vi.clearAllMocks();+ vi.resetAllMocks();+ mcpClientMocks.mockReset();+ ctr = new McpCtr(mockApp);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('reuses one stdio session across consecutive tool calls (state survives)', async () => {+ const instance = makeClientInstance('first');+ mcpClientMocks.mockReturnValue(instance);++ await ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'open_database',+ } as any);+ await ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'execute_python',+ } as any);++ // Exactly ONE MCPClient was constructed for both calls: the stdio+ // process is NOT respawned per call, so server-side state survives.+ expect(mcpClientMocks).toHaveBeenCalledTimes(1);+ expect(instance.callTool).toHaveBeenCalledTimes(2);+ // Pooled sessions are never disconnected between calls.+ expect(instance.disconnect).not.toHaveBeenCalled();+ // Second call actually ran (result produced).+ expect(instance.callTool).toHaveBeenLastCalledWith('execute_python', {});+ });++ it('spawns separate sessions for different connection params', async () => {+ const first = makeClientInstance('a');+ const second = makeClientInstance('b');+ mcpClientMocks.mockReturnValueOnce(first).mockReturnValueOnce(second);++ await ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'open_database',+ } as any);+ await ctr.runStdioMcpTool({+ args: '',+ env: { IDB_PATH: '/other' },+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'open_database',+ } as any);++ expect(mcpClientMocks).toHaveBeenCalledTimes(2);+ });++ it('retries on a fresh session after a stale pooled session fails, then keeps pooling', async () => {+ const stale = makeClientInstance('stale');+ stale.callTool.mockRejectedValue(new Error('No valid session ID provided'));+ const fresh = makeClientInstance('fresh');+ mcpClientMocks.mockReturnValueOnce(stale).mockReturnValueOnce(fresh).mockReturnValue(fresh);++ const result = await ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'execute_python',+ } as any);++ // The stale session was evicted + disconnected, the retry succeeded.+ expect(stale.disconnect).toHaveBeenCalledTimes(1);+ expect(fresh.callTool).toHaveBeenCalledTimes(1);+ expect(result.success).toBe(true);++ // Next call reuses the replacement session (pool stays warm).+ await ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'execute_python',+ } as any);+ expect(mcpClientMocks).toHaveBeenCalledTimes(2);+ });++ it('propagates the failure when the fresh retry also fails', async () => {+ mcpClientMocks.mockImplementation(() => {+ const failing = makeClientInstance('failing');+ failing.callTool.mockRejectedValue(new Error('No valid session ID provided'));+ return failing;+ });++ await expect(+ ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'execute_python',+ } as any),+ ).rejects.toThrow('No valid session ID provided');+ });++ it('does NOT retry when the tool itself failed at app level (no double-apply of side effects)', async () => {+ const pooled = makeClientInstance('pooled');+ pooled.callTool.mockRejectedValue(+ new Error('no open database instance; call open_database() first'),+ );+ mcpClientMocks.mockReturnValue(pooled);++ await expect(+ ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'execute_python',+ } as any),+ ).rejects.toThrow('no open database instance');++ // App-level failure: no eviction, no disconnect, no second invocation.+ expect(pooled.callTool).toHaveBeenCalledTimes(1);+ expect(pooled.disconnect).not.toHaveBeenCalled();+ expect(mcpClientMocks).toHaveBeenCalledTimes(1);+ });++ it('does NOT retry when post-processing (media upload) fails after a successful tool run', async () => {+ const pooled = makeClientInstance('pooled');+ // Return an image block so processContentBlocks runs the media upload.+ pooled.callTool.mockResolvedValue({+ content: [{ data: 'aW1hZ2U=', mimeType: 'image/png', type: 'image' }],+ isError: false,+ });+ mcpClientMocks.mockReturnValue(pooled);+ // Simulate media upload failure inside processContentBlocks.+ (ctr as any).app.getService = vi.fn(() => ({+ getFileHTTPURL: vi.fn(),+ uploadFile: vi.fn().mockRejectedValue(new Error('upload unavailable')),+ }));++ await expect(+ ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'render_screenshot',+ } as any),+ ).rejects.toThrow('upload unavailable');++ // The tool ran exactly once β its side effect must not be re-applied.+ expect(pooled.callTool).toHaveBeenCalledTimes(1);+ expect(pooled.disconnect).not.toHaveBeenCalled();+ });++ it('preserves CLI argument order in pool keys (reordered argv must not share a session)', async () => {+ mcpClientMocks.mockImplementation(() => makeClientInstance('x'));++ await ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['--port', '8080', 'serve'], command: 'svc', name: 'svc' },+ toolName: 'ping',+ } as any);+ await ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['serve', '--port', '8080'], command: 'svc', name: 'svc' },+ toolName: 'ping',+ } as any);++ // Same tokens, different order β distinct sessions, never reused.+ expect(mcpClientMocks).toHaveBeenCalledTimes(2);+ });++ it('evicts the pooled client when listManifests fails on a stale session', async () => {+ const seeded = makeClientInstance('seeded');+ seeded.listManifests.mockRejectedValue(new Error('Connection closed'));+ mcpClientMocks.mockReturnValue(seeded);++ await expect(+ ctr.getStdioMcpServerManifest({+ args: ['--stdio'],+ command: 'ida-mcp',+ name: 'ida-mcp',+ } as any),+ ).rejects.toThrow('Connection closed');++ // Broken session evicted + disconnected, so the next refresh starts fresh.+ expect(seeded.disconnect).toHaveBeenCalledTimes(1);+ });++ it('does NOT retry on a generic JSON-RPC -32000 app-level error (no double side effects)', async () => {+ const pooled = makeClientInstance('pooled');+ // Generic -32000 is the server-side application error range β a mutating+ // tool may have already applied its effect, so retrying is forbidden.+ pooled.callTool.mockRejectedValue(+ Object.assign(new Error('tool execution failed'), { code: -32000 }),+ );+ mcpClientMocks.mockReturnValue(pooled);++ await expect(+ ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'delete_record',+ } as any),+ ).rejects.toThrow('tool execution failed');++ // Exactly one invocation, no eviction, no disconnect.+ expect(pooled.callTool).toHaveBeenCalledTimes(1);+ expect(pooled.disconnect).not.toHaveBeenCalled();+ expect(mcpClientMocks).toHaveBeenCalledTimes(1);+ });++ it('single-flights concurrent same-key initialization (no duplicate stdio processes)', async () => {+ let releaseGate: () => void = () => {};+ const gate = new Promise<void>((resolve) => {+ releaseGate = resolve;+ });+ let created = 0;+ mcpClientMocks.mockImplementation(() => {+ created += 1;+ const instance = makeClientInstance(`c${created}`);+ // Block inside initialize(): the constructor returns synchronously,+ // initialization is where the (slow) stdio handshake would happen.+ instance.initialize.mockImplementation(async () => {+ await gate;+ });+ return instance;+ });++ const params = {+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'open_database',+ } as any;++ const first = ctr.runStdioMcpTool(params);+ // Let the first call reach its pending initialize() before the second.+ await vi.waitFor(() => expect(mcpClientMocks).toHaveBeenCalledTimes(1));+ const second = ctr.runStdioMcpTool(params);++ // Release the gate; both calls must share the one client.+ releaseGate();+ await Promise.all([first, second]);++ // Only one MCPClient was ever constructed for both concurrent calls.+ expect(mcpClientMocks).toHaveBeenCalledTimes(1);+ });++ it('evicts the replacement session when its retry also fails (pool never serves a dead client)', async () => {+ const stale = makeClientInstance('stale');+ stale.callTool.mockRejectedValue(new Error('No valid session ID provided'));+ const replacement = makeClientInstance('replacement');+ replacement.callTool.mockRejectedValue(new Error('No valid session ID provided'));+ mcpClientMocks+ .mockReturnValueOnce(stale)+ .mockReturnValueOnce(replacement)+ .mockReturnValue(replacement);++ await expect(+ ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'execute_python',+ } as any),+ ).rejects.toThrow('No valid session ID provided');++ // Both the stale session and the proven-dead replacement were evicted.+ expect(stale.disconnect).toHaveBeenCalledTimes(1);+ expect(replacement.disconnect).toHaveBeenCalledTimes(1);+ });++ it('single-flights the replacement when two concurrent calls share a stale session', async () => {+ const shared = makeClientInstance('stale-shared');+ shared.callTool.mockRejectedValue(new Error('No valid session ID provided'));+ const replacement = makeClientInstance('replacement');+ mcpClientMocks+ .mockReturnValueOnce(shared) // both concurrent calls pool-acquire this+ .mockReturnValueOnce(replacement) // single-flight creates ONE replacement+ .mockReturnValue(replacement);++ const params = {+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'execute_python',+ } as any;++ // Two concurrent calls share the stale session; both fail stale and both+ // enter the retry path.+ const [r1, r2] = await Promise.allSettled([+ ctr.runStdioMcpTool(params),+ ctr.runStdioMcpTool(params),+ ]);++ // Replacement creation went through the single-flight path: exactly one+ // replacement client was ever constructed (no racing duplicate process).+ expect(mcpClientMocks).toHaveBeenCalledTimes(2);++ // The winner returns success through the shared replacement.+ const fulfilled = [r1, r2].filter((r) => r.status === 'fulfilled');+ expect(fulfilled.length).toBeGreaterThanOrEqual(1);+ void replacement;+ });++ it('keeps the healthy replacement pooled when its post-processing fails after a successful tool run', async () => {+ const stale = makeClientInstance('stale');+ stale.callTool.mockRejectedValue(new Error('No valid session ID provided'));+ const fresh = makeClientInstance('fresh');+ fresh.callTool.mockResolvedValue({+ content: [+ { data: 'aGVsbG8=', mimeType: 'image/png', type: 'image' },+ { text: 'tool ran fine', type: 'text' },+ ],+ isError: false,+ });+ mcpClientMocks.mockReturnValueOnce(stale).mockReturnValueOnce(fresh).mockReturnValue(fresh);++ // Post-processing (media upload) fails AFTER the tool succeeded.+ const uploadSpy = vi+ .spyOn(ctr as any, 'uploadMcpMediaBlock')+ .mockRejectedValue(new Error('upload failed'));++ await expect(+ ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'render_chart',+ } as any),+ ).rejects.toThrow('upload failed');++ uploadSpy.mockRestore();++ // The tool DID run on the replacement (state established server-side).+ expect(fresh.callTool).toHaveBeenCalledTimes(1);+ // A post-processing error is not a session problem β the healthy+ // replacement stays pooled, never disconnected.+ expect(fresh.disconnect).not.toHaveBeenCalled();+ });++ it('reaps idle sessions past the TTL but keeps actively used ones (config change cleanup)', async () => {+ vi.useFakeTimers();+ try {+ const oldSession = makeClientInstance('old');+ const activeSession = makeClientInstance('active');+ const freshSession = makeClientInstance('fresh');+ mcpClientMocks+ .mockReturnValueOnce(oldSession)+ .mockReturnValueOnce(activeSession)+ .mockReturnValue(freshSession);++ const oldParams = {+ args: '',+ env: { TOKEN: 'v1' },+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'open_database',+ } as any;+ await ctr.runStdioMcpTool(oldParams);++ // User rotates the token β new cache key, new session; the old entry+ // (now obsolete) stays connected until the idle reaper collects it.+ const newParams = {+ args: '',+ env: { TOKEN: 'v2' },+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'open_database',+ } as any;+ await ctr.runStdioMcpTool(newParams);+ expect(mcpClientMocks).toHaveBeenCalledTimes(2);++ // The v2 session is actively used again within the TTL window.+ await ctr.runStdioMcpTool(newParams);+ expect(activeSession.disconnect).not.toHaveBeenCalled();++ // Advance past the TTL: the untouched v1 entry is reaped, the+ // refreshed v2 entry survives.+ await vi.advanceTimersByTimeAsync(31 * 60 * 1000);+ await ctr.runStdioMcpTool(newParams);++ expect(oldSession.disconnect).toHaveBeenCalledTimes(1);+ expect(activeSession.disconnect).not.toHaveBeenCalled();+ // v2 was still pooled (not rebuilt after reaping).+ expect(mcpClientMocks).toHaveBeenCalledTimes(2);+ void freshSession;+ } finally {+ vi.useRealTimers();+ }+ });++ it('dispose-all disconnects every pooled session (app shutdown path)', async () => {+ const a = makeClientInstance('a');+ const b = makeClientInstance('b');+ mcpClientMocks.mockReturnValueOnce(a).mockReturnValueOnce(b);++ await ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 't',+ } as any);+ await ctr.runStdioMcpTool({+ args: '',+ env: { TOKEN: 'x' },+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 't',+ } as any);++ await (ctr as any).disposeAllPooledClients();++ expect(a.disconnect).toHaveBeenCalledTimes(1);+ expect(b.disconnect).toHaveBeenCalledTimes(1);+ });++ it('defers eviction disconnect until in-flight calls release the shared client (concurrent manifest + stale tool call)', async () => {+ // Manifest discovery holds a pending listManifests while concurrent tool+ // calls on the same pooled session fail with stale-session errors. The+ // eviction must leave the pool immediately but NOT disconnect the shared+ // client while the manifest request still holds its lease.+ const shared = makeClientInstance('shared');+ shared.callTool.mockRejectedValue(new Error('No valid session ID provided'));+ mcpClientMocks.mockImplementation(() => shared);++ let releaseManifest!: () => void;+ shared.listManifests.mockImplementation(+ () =>+ new Promise<void>((resolve) => {+ releaseManifest = resolve;+ }),+ );++ const params = {+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 't',+ } as any;++ const manifestPromise = ctr.getStdioMcpServerManifest(params);+ await vi.waitFor(() => {+ expect(shared.listManifests).toHaveBeenCalled();+ });++ // First tool call: stale error β evicts the shared client β retry on+ // the replacement (same mocked instance) β stale again β propagates.+ await expect(ctr.runStdioMcpTool({ ...params, toolName: 'explode' } as any)).rejects.toThrow(+ 'No valid session ID provided',+ );+ // Eviction happened (client left the pool) but the disconnect is+ // deferred while the manifest call still holds its lease.+ expect(shared.disconnect).not.toHaveBeenCalled();++ void manifestPromise.catch(() => {});+ releaseManifest!();+ await manifestPromise.catch(() => {});+ // Once the last lease is released, the deferred evictions land. The+ // retry eviction may add a second disconnect on the same mocked+ // instance; the contract under test is "no disconnect while a manifest+ // request is pending", not the exact eviction count.+ await vi.waitFor(() => {+ expect(shared.disconnect.mock.calls.length).toBeGreaterThanOrEqual(1);+ });+ });++ it('idle reaper skips sessions with active leases (long call past TTL)', async () => {+ vi.useFakeTimers();+ try {+ const longCall = makeClientInstance('long');+ mcpClientMocks.mockReturnValue(longCall);+ longCall.callTool.mockImplementation(+ () =>+ new Promise((resolve) => {+ setTimeout(+ () =>+ resolve({+ content: [{ text: 'done', type: 'text' }],+ isError: false,+ }),+ 40 * 60 * 1000,+ );+ }),+ );++ const params = {+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 't',+ } as any;++ const callPromise = ctr.runStdioMcpTool(params);+ await vi.advanceTimersByTimeAsync(31 * 60 * 1000);++ // Still inside the 40-minute call: the idle sweep (TTL 30 min) must+ // not reap the session mid-call even though lastUsedAt is stale.+ expect(longCall.disconnect).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(40 * 60 * 1000);+ await callPromise;+ } finally {+ vi.useRealTimers();+ }+ });++ it('drops the idle-clock entry when client initialization fails (no credential-keyed leak)', async () => {+ const failing = makeClientInstance('failing');+ failing.initialize.mockRejectedValue(new Error('spawn failed'));+ mcpClientMocks.mockReturnValue(failing);++ await expect(+ ctr.runStdioMcpTool({+ args: '',+ env: { TOKEN: 'secret-v1' },+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 't',+ } as any),+ ).rejects.toThrow('spawn failed');++ const clocks = (ctr as any).mcpClientLastUsedAt as Map<string, number>;+ expect(clocks.size).toBe(0);+ });++ it('evicts a dead stdio subprocess WITHOUT replaying the call (P1: dead transport)', async () => {+ // SDK surfaces an exited subprocess as "Connection closed" (in-flight+ // request) or "Not connected" (request issued after close). Neither+ // may be retried blindly (a mutating tool could double-apply), but the+ // dead client MUST leave the pool β otherwise every later call+ // refreshes and reuses the corpse.+ const dead = makeClientInstance('dead');+ dead.callTool.mockRejectedValue(new Error('Connection closed'));+ const replacement = makeClientInstance('replacement');+ mcpClientMocks.mockReturnValueOnce(dead).mockReturnValue(replacement);++ await expect(+ ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'delete_record',+ } as any),+ ).rejects.toThrow('Connection closed');++ // Dead session evicted + disconnected; the failure was still surfaced+ // (no silent replay of the mutating call).+ expect(dead.disconnect).toHaveBeenCalledTimes(1);+ expect(dead.callTool).toHaveBeenCalledTimes(1);+ expect(replacement.callTool).not.toHaveBeenCalled();+ expect(mcpClientMocks).toHaveBeenCalledTimes(1);++ // The next call builds a FRESH session instead of reusing the corpse.+ await ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 'open_database',+ } as any);+ expect(mcpClientMocks).toHaveBeenCalledTimes(2);+ expect(replacement.callTool).toHaveBeenCalledTimes(1);+ });++ it('does NOT evict on a server-side app error that merely mentions "Connection closed"', async () => {+ // Exact-match guard: only the SDK's exact transport-failure messages+ // qualify; a server application error containing the words must not+ // kill a healthy pooled session.+ const pooled = makeClientInstance('pooled');+ pooled.callTool.mockRejectedValue(+ Object.assign(new Error('Connection closed by tool sandbox'), { code: -32000 }),+ );+ mcpClientMocks.mockReturnValue(pooled);++ await expect(+ ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 't',+ } as any),+ ).rejects.toThrow('Connection closed by tool sandbox');++ expect(pooled.disconnect).not.toHaveBeenCalled();+ expect(mcpClientMocks).toHaveBeenCalledTimes(1);+ });++ it('refreshes the idle clock when the last lease is released (long call past TTL)', async () => {+ vi.useFakeTimers();+ try {+ const longCall = makeClientInstance('long');+ const unrelated = makeClientInstance('unrelated');+ mcpClientMocks+ .mockReturnValueOnce(longCall)+ .mockReturnValueOnce(unrelated)+ .mockReturnValue(unrelated);++ longCall.callTool.mockImplementation(+ () =>+ new Promise((resolve) => {+ setTimeout(+ () =>+ resolve({+ content: [{ text: 'done', type: 'text' }],+ isError: false,+ }),+ 40 * 60 * 1000,+ );+ }),+ );++ const longParams = {+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 't',+ } as any;+ const callPromise = ctr.runStdioMcpTool(longParams);+ await vi.advanceTimersByTimeAsync(40 * 60 * 1000);+ await callPromise;++ // The long call ended NOW. A different MCP key acquiring afterwards+ // triggers a sweep: the just-finished session must survive because+ // its clock was refreshed at lease release, not at acquisition.+ await ctr.runStdioMcpTool({+ args: '',+ env: { TOKEN: 'other' },+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 't',+ } as any);++ expect(longCall.disconnect).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it('will-quit disposal initiates every disconnect synchronously (Electron cannot await listeners)', async () => {+ const a = makeClientInstance('a');+ const b = makeClientInstance('b');+ let releaseA: () => void = () => {};+ const gateA = new Promise<void>((resolve) => {+ releaseA = resolve;+ });+ a.disconnect.mockImplementation(async () => {+ await gateA;+ });+ mcpClientMocks.mockReturnValueOnce(a).mockReturnValueOnce(b);++ await ctr.runStdioMcpTool({+ args: '',+ env: undefined,+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 't',+ } as any);+ await ctr.runStdioMcpTool({+ args: '',+ env: { TOKEN: 'x' },+ params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },+ toolName: 't',+ } as any);++ // The disposal promise resolves only after BOTH teardowns settle, and+ // both were initiated up front (b's disconnect is called before a's+ // gated one resolves) β so Electron's non-awaiting will-quit still+ // reaches every stdio child.+ const disposal = (ctr as any).disposeAllPooledClients();+ await vi.waitFor(() => expect(b.disconnect).toHaveBeenCalledTimes(1));+ expect(a.disconnect).toHaveBeenCalledTimes(1);+ releaseA();+ await disposal;++ expect(a.disconnect).toHaveBeenCalledTimes(1);+ expect(b.disconnect).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/desktop/src/main/controllers/mcpInstallCheck.ts b/apps/desktop/src/main/controllers/mcpInstallCheck.tsnew file mode 100644index 00000000000..44ea036241b--- /dev/null+++ b/apps/desktop/src/main/controllers/mcpInstallCheck.ts@@ -0,0 +1,206 @@+import { exec } from 'node:child_process';+import { promisify } from 'node:util';++const execPromise = promisify(exec);++/**+ * MCP Install Check (local system) β extracted from McpCtr so the controller+ * stays under the 800-line source-layout limit. Pure dependency probing with+ * no controller state; same behavior as before the extraction.+ */++// ---------- MCP Install Check (local system) ----------++export const getInstallInstructions = (installInstructions: any) => {+ if (!installInstructions) return undefined;++ let current: string | undefined;++ switch (process.platform) {+ case 'darwin': {+ current = installInstructions.macos;+ break;+ }+ case 'linux': {+ current = installInstructions.linux_debian || installInstructions.linux;+ break;+ }+ case 'win32': {+ current = installInstructions.windows;+ break;+ }+ }++ return { current, manual: installInstructions.manual };+};++export const checkSystemDependency = async (dependency: any) => {+ const checkCommand = dependency.checkCommand || `${dependency.name} --version`;++ try {+ const { stdout, stderr } = await execPromise(checkCommand);++ if (stderr && !stdout) {+ return {+ error: stderr,+ installInstructions: getInstallInstructions(dependency.installInstructions),+ installed: false,+ meetRequirement: false,+ name: dependency.name,+ requiredVersion: dependency.requiredVersion,+ };+ }++ const output = String(stdout || '').trim();+ let version = output;++ if (dependency.versionParsingRequired) {+ const versionMatch = output.match(/V?(\d+(\.\d+)*)/i);+ if (versionMatch) version = versionMatch[0];+ }++ let meetRequirement = true;++ if (dependency.requiredVersion) {+ const currentVersion = String(version).replace(/^V/i, '');+ const currentNum = Number.parseFloat(currentVersion);++ const requirementMatch = String(dependency.requiredVersion).match(/([<=>]+)?(\d+(\.\d+)*)/);+ if (requirementMatch) {+ const [, operator = '=', requiredVersion] = requirementMatch;+ const requiredNum = Number.parseFloat(requiredVersion);+ switch (operator) {+ case '>=': {+ meetRequirement = currentNum >= requiredNum;+ break;+ }+ case '>': {+ meetRequirement = currentNum > requiredNum;+ break;+ }+ case '<=': {+ meetRequirement = currentNum <= requiredNum;+ break;+ }+ case '<': {+ meetRequirement = currentNum < requiredNum;+ break;+ }+ default: {+ meetRequirement = currentNum === requiredNum;+ break;+ }+ }+ }+ }++ return {+ installInstructions: getInstallInstructions(dependency.installInstructions),+ installed: true,+ meetRequirement,+ name: dependency.name,+ requiredVersion: dependency.requiredVersion,+ version,+ };+ } catch (error) {+ return {+ error: error instanceof Error ? error.message : 'Unknown error',+ installInstructions: getInstallInstructions(dependency.installInstructions),+ installed: false,+ meetRequirement: false,+ name: dependency.name,+ requiredVersion: dependency.requiredVersion,+ };+ }+};++export const checkPackageInstalled = async (installationMethod: string, details: any) => {+ if (installationMethod === 'npm') {+ const packageName = details?.packageName;+ if (!packageName) return { installed: false };++ // Only check global npm list - do NOT use npx as it may download packages+ try {+ const { stdout } = await execPromise(`npm list -g ${packageName} --depth=0`);+ if (!stdout.includes('(empty)') && stdout.includes(packageName)) {+ return { installed: true };+ }+ } catch {+ // ignore - package not found in global list+ }++ // For npm packages, we don't require pre-installation+ // npx will handle downloading and running on-demand during actual MCP connection+ return { installed: false };+ }++ if (installationMethod === 'python') {+ const packageName = details?.packageName;+ if (!packageName) return { installed: false };++ const pythonCommand = details?.pythonCommand || 'python';++ try {+ const command = `${pythonCommand} -m pip list | grep -i "${packageName}"`;+ const { stdout } = await execPromise(command);+ if (stdout.trim() && stdout.toLowerCase().includes(String(packageName).toLowerCase())) {+ return { installed: true };+ }+ } catch {+ // ignore+ }++ try {+ const importCommand = `${pythonCommand} -c "import ${String(packageName).replace('-', '_')}; print('Package installed')"`;+ const { stdout } = await execPromise(importCommand);+ if (stdout.includes('Package installed')) return { installed: true };+ } catch {+ // ignore+ }++ return { installed: false };+ }++ // manual or unknown+ return { installed: false };+};++export const checkDeployOption = async (option: any) => {+ const systemDependenciesResults = [];++ if (Array.isArray(option.systemDependencies) && option.systemDependencies.length > 0) {+ for (const dep of option.systemDependencies) {+ systemDependenciesResults.push(await checkSystemDependency(dep));+ }+ }++ const packageResult = await checkPackageInstalled(+ option.installationMethod,+ option.installationDetails,+ );+ const packageInstalled = Boolean((packageResult as any).installed);++ const allDependenciesMet = systemDependenciesResults.every((dep: any) => dep.meetRequirement);++ const configSchema = option.connection?.configSchema;+ const needsConfig = Boolean(+ configSchema &&+ ((Array.isArray(configSchema.required) && configSchema.required.length > 0) ||+ (configSchema.properties &&+ Object.values(configSchema.properties).some((prop: any) => prop.required === true))),+ );++ const connection = option.connection?.url+ ? { ...option.connection, type: 'http' }+ : { ...option.connection, type: 'stdio' };++ return {+ allDependenciesMet,+ configSchema,+ connection,+ isRecommended: option.isRecommended,+ needsConfig,+ packageInstalled,+ systemDependencies: systemDependenciesResults,+ };+};diff --git a/apps/desktop/src/main/libs/mcp/__tests__/client.stderr.test.ts b/apps/desktop/src/main/libs/mcp/__tests__/client.stderr.test.tsnew file mode 100644index 00000000000..e6882e86b68--- /dev/null+++ b/apps/desktop/src/main/libs/mcp/__tests__/client.stderr.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it, vi } from 'vitest';++import { MCPClient } from '../client';++/**+ * Focused test for the bounded stderr tail: only the stderr listener+ * wiring is exercised through a stubbed transport β no real stdio process+ * is spawned (the SDK Client/transport created in the constructor are+ * never connected).+ */+describe('MCPClient stderr tail cap (P2: bounded memory for pooled clients)', () => {+ it('keeps only the most recent 200 stderr lines', () => {+ const client = new MCPClient({+ args: [],+ command: 'verbose-mcp',+ name: 'verbose',+ type: 'stdio',+ });++ const listeners = new Map<string, (chunk: Buffer) => void>();+ const transport = {+ stderr: {+ on: vi.fn((event: string, handler: (chunk: Buffer) => void) => {+ listeners.set(event, handler);+ }),+ },+ };+ const emit = (chunk: Buffer) => listeners.get('data')?.(chunk);++ (client as any).setupStderrListener(transport as any);++ // Push 450 lines across batches; retention must cap at 200 (the tail).+ for (let batch = 0; batch < 45; batch++) {+ const lines = Array.from({ length: 10 }, (_, k) => `line-${batch * 10 + k}`);+ emit(Buffer.from(lines.join('\n')));+ }++ const logs = client.getStderrLogs();+ expect(logs.length).toBe(200);+ expect(logs[0]).toBe('line-250');+ expect(logs[199]).toBe('line-449');+ });+});diff --git a/apps/desktop/src/main/libs/mcp/client.ts b/apps/desktop/src/main/libs/mcp/client.tsindex 2ee50d7fe4d..2a59616a7d9 100644--- a/apps/desktop/src/main/libs/mcp/client.ts+++ b/apps/desktop/src/main/libs/mcp/client.ts@@ -27,6 +27,14 @@ export class MCPConnectionError extends Error {}export class MCPClient {+ /**+ * Upper bound on retained stderr lines. Pooled clients can live for the+ * whole desktop session; without a cap a verbose long-lived MCP server+ * would grow `stderrLogs` (and every enhanced error built from it)+ * without limit. Only the most recent tail is kept for diagnostics.+ */+ private static readonly STDERR_LOG_LIMIT = 200;+private readonly mcp: Client;private transport: Transport;@@ -77,7 +85,7 @@ export class MCPClient {default: {// Exhaustive check-+const _never: never = params;throw new Error(`Unsupported MCP connection type: ${(params as any).type}`);}@@ -92,6 +100,11 @@ export class MCPClient {// Split by newlines and filter empty linesconst lines = text.split('\n').filter((line) => line.trim());this.stderrLogs.push(...lines);+ // Keep only the most recent tail: a pooled, long-lived stdio+ // server must not grow desktop memory without bound.+ if (this.stderrLogs.length > MCPClient.STDERR_LOG_LIMIT) {+ this.stderrLogs.splice(0, this.stderrLogs.length - MCPClient.STDERR_LOG_LIMIT);+ }});}}@@ -106,7 +119,7 @@ export class MCPClient {private isMethodNotFoundError(error: unknown) {const err = error as any;if (!err) return false;-+if (err.code === -32601) return true;if (typeof err.message === 'string' && err.message.includes('Method not found')) return true;return false;diff --git a/apps/desktop/src/main/libs/mcp/sessionGuards.ts b/apps/desktop/src/main/libs/mcp/sessionGuards.tsnew file mode 100644index 00000000000..d61d66ce449--- /dev/null+++ b/apps/desktop/src/main/libs/mcp/sessionGuards.ts@@ -0,0 +1,68 @@+import type { MCPClientParams } from './types';++/**+ * Serialize MCP client params into a stable cache key. Object keys are+ * canonicalized (sorted) so that key order in the manifest does not defeat+ * reuse, while array order is preserved: CLI argv is positional, and sorting+ * `args` would let distinct invocations made of the same tokens (reordered+ * flags / positional arguments) silently share a session launched with the+ * previous command line. `env` participates in the key: a changed+ * secret/config must spawn a fresh session rather than reuse one+ * authenticated with the old values.+ */+const canonicalizeForCacheKey = (value: unknown): unknown => {+ if (Array.isArray(value)) return value.map((item) => canonicalizeForCacheKey(item));+ if (value !== null && typeof value === 'object') {+ const source = value as Record<string, unknown>;+ const sorted: Record<string, unknown> = {};+ for (const key of Object.keys(source).sort()) {+ sorted[key] = canonicalizeForCacheKey(source[key]);+ }+ return sorted;+ }+ return value;+};++export const serializeMcpClientParams = (params: MCPClientParams): string =>+ JSON.stringify(canonicalizeForCacheKey(params as unknown as Record<string, unknown>));++/**+ * Whether a failed `callTool` is a confirmed stale-session / transport-level+ * failure, i.e. safe to retry on a fresh session. App-level tool failures+ * (the tool ran and rejected the arguments, the server returned an error+ * result, post-processing failed, β¦) must NOT be retried: a mutating tool+ * could apply its side effect (write / delete / send) a second time.+ *+ * The signal set is deliberately narrow and mirrors the server-side+ * `MCPClient.isNoValidSessionError` (src/libs/mcp/client.ts): only the+ * `MCPConnectionError` transport wrapper and the SDK's exact+ * "No valid session ID provided" message qualify. Generic JSON-RPC `-32000`+ * errors are server-side application errors and do NOT trigger a retry.+ */+export const isStaleSessionError = (error: unknown): boolean => {+ if (!error) return false;+ if (error instanceof Error && error.name === 'MCPConnectionError') return true;+ const message = error instanceof Error ? error.message : String(error);+ return message.includes('No valid session ID provided');+};++/**+ * Whether the failure means the pooled stdio subprocess is gone. The MCP+ * SDK surfaces a dead transport as `McpError(ErrorCode.ConnectionClosed)`+ * for requests that were in flight when the process exited, and as plain+ * "Connection closed" / "Not connected" errors for requests issued after+ * the transport closed (shared/protocol.js `_onclose` / `request`).+ *+ * Unlike `isStaleSessionError` this does NOT authorize a replay β the+ * request may have reached the server before the pipe died β but the dead+ * client must still be evicted from the pool, or every later same-key+ * acquisition would refresh and return the same unusable session forever.+ * Message matches are exact on purpose: a server-side application error+ * that merely contains those words must not get a healthy pooled session+ * killed.+ */+export const isDeadTransportError = (error: unknown): boolean => {+ if (!error) return false;+ const message = error instanceof Error ? error.message : String(error);+ return message === 'Connection closed' || message === 'Not connected';+};