Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(mcp): support configurable handshake timeout for user MCP servers
Totopo27b21289ba7a4c
diff --git a/apps/desktop/electron/main/user-mcp.ts b/apps/desktop/electron/main/user-mcp.tsindex 5a7186d31..e798a2321 100644--- a/apps/desktop/electron/main/user-mcp.ts+++ b/apps/desktop/electron/main/user-mcp.ts@@ -421,6 +421,10 @@ export class UserMcpRuntime {...(record.headers ?? {}),...(oauthToken ? { Authorization: `Bearer ${oauthToken}` } : {}),};+ const customTimeoutMs =+ typeof record.timeoutSeconds === "number" && record.timeoutSeconds > 0+ ? record.timeoutSeconds * 1000+ : undefined;const client = this.options.createClient({// No plugin owns this server; `rootPath` is only the child's cwd, and the// user's own command may live anywhere on the machine.@@ -439,9 +443,9 @@ export class UserMcpRuntime {values: record.transport === "stdio" ? (record.env ?? {}) : headers,audit: this.options.audit,auditScope: "mcp",- connectTimeoutMs: this.options.connectTimeoutMs,- callTimeoutMs: this.options.callTimeoutMs,- discoveryTimeoutMs: this.options.discoveryTimeoutMs,+ connectTimeoutMs: customTimeoutMs ?? this.options.connectTimeoutMs,+ callTimeoutMs: customTimeoutMs ? Math.max(customTimeoutMs, this.options.callTimeoutMs ?? 0) : this.options.callTimeoutMs,+ discoveryTimeoutMs: customTimeoutMs ? Math.max(customTimeoutMs, this.options.discoveryTimeoutMs ?? 0) : this.options.discoveryTimeoutMs,});const entry: Entry = {record,@@ -471,6 +475,7 @@ export function configurationChanged(before: McpServerRecord, after: McpServerReJSON.stringify(before.args ?? []) !== JSON.stringify(after.args ?? []) ||JSON.stringify(before.env ?? {}) !== JSON.stringify(after.env ?? {}) ||before.url !== after.url ||- JSON.stringify(before.headers ?? {}) !== JSON.stringify(after.headers ?? {})+ JSON.stringify(before.headers ?? {}) !== JSON.stringify(after.headers ?? {}) ||+ before.timeoutSeconds !== after.timeoutSeconds);}diff --git a/apps/desktop/src/components/extensions/McpEditorSheet.tsx b/apps/desktop/src/components/extensions/McpEditorSheet.tsxindex 9e3114284..12e513766 100644--- a/apps/desktop/src/components/extensions/McpEditorSheet.tsx+++ b/apps/desktop/src/components/extensions/McpEditorSheet.tsx@@ -49,6 +49,7 @@ export type McpDraft = {headers: KeyValuePair[];enabled: boolean;scope: ActivationScope;+ timeoutSeconds: string;};export function emptyMcpDraft(): McpDraft {@@ -64,6 +65,7 @@ export function emptyMcpDraft(): McpDraft {headers: [],enabled: true,scope: GLOBAL_SCOPE,+ timeoutSeconds: "",};}@@ -80,6 +82,7 @@ export function draftFromRecord(record: McpServerRecord): McpDraft {headers: recordToPairs(record.headers),enabled: record.enabled,scope: resolveScope(record.scope),+ timeoutSeconds: record.timeoutSeconds !== undefined ? String(record.timeoutSeconds) : "",};}@@ -132,12 +135,18 @@ export function draftToInput(draft: McpDraft,context?: { level?: AgentCapabilityLevel; projectPath?: string },): McpServerInput {+ const parsedTimeout = draft.timeoutSeconds.trim()+ ? Number.parseInt(draft.timeoutSeconds.trim(), 10)+ : undefined;const base = {id: draft.id.trim(),...(context?.level ? { level: context.level } : {}),...(context?.projectPath ? { projectPath: context.projectPath } : {}),label: draft.label.trim() || draft.id.trim(),description: draft.description.trim() || undefined,+ ...(typeof parsedTimeout === "number" && !Number.isNaN(parsedTimeout)+ ? { timeoutSeconds: parsedTimeout }+ : {}),enabled: draft.enabled,scope: draft.scope,};@@ -203,6 +212,12 @@ function ManagementScope({export function mcpDraftError(draft: McpDraft): string | null {if (!draft.id.trim()) return "extensions.mcp.errorId";if (!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(draft.id.trim())) return "extensions.mcp.errorIdShape";+ if (draft.timeoutSeconds.trim()) {+ const parsed = Number(draft.timeoutSeconds.trim());+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 600) {+ return "extensions.mcp.errorTimeoutRange";+ }+ }if (draft.transport === "stdio") {if (!draft.command.trim()) return "extensions.mcp.errorCommand";if (draft.command.includes("..")) return "extensions.mcp.errorCommandDots";@@ -493,6 +508,17 @@ export function McpEditorSheet({/></Field>+ <Field label={t("extensions.mcp.timeout")} hint={t("extensions.mcp.timeoutHint")}>+ <Input+ type="number"+ min={1}+ max={600}+ value={draft.timeoutSeconds}+ placeholder={t("extensions.mcp.timeoutPlaceholder")}+ onChange={(event) => set("timeoutSeconds", event.target.value)}+ />+ </Field>+<div className="ext-field-group"><div className="ext-field-label">{managementLevel ? t("settings.scope") : t("extensions.scope.title")}diff --git a/apps/desktop/test/extensions-page.test.mjs b/apps/desktop/test/extensions-page.test.mjsindex 6978db831..9ba1758ad 100644--- a/apps/desktop/test/extensions-page.test.mjs+++ b/apps/desktop/test/extensions-page.test.mjs@@ -183,6 +183,8 @@ test("MCP management reuses the modal and validates its locked id and transportassert.match(page, /sameLevel/);assert.match(sheet, /disabled=\{!!editing\}/);assert.match(sheet, /mcpDraftError/);+ assert.match(sheet, /draft\.timeoutSeconds/);+ assert.match(sheet, /errorTimeoutRange/);assert.match(sheet, /command\.includes\("\.\."\)/);assert.match(sheet, /isNonLoopbackHttpMcpUrl/);assert.match(sheet, /role="dialog" aria-modal/);diff --git a/apps/desktop/test/user-mcp.test.mjs b/apps/desktop/test/user-mcp.test.mjsindex 576dcd389..4f8b01a71 100644--- a/apps/desktop/test/user-mcp.test.mjs+++ b/apps/desktop/test/user-mcp.test.mjs@@ -523,6 +523,7 @@ test("configurationChanged separates what a server is from who may use it", () =assert.equal(configurationChanged(base, { ...base, args: ["b.mjs"] }), true);assert.equal(configurationChanged(base, { ...base, env: { A: "2" } }), true);assert.equal(configurationChanged(base, { ...base, transport: "http", url: "https://x" }), true);+ assert.equal(configurationChanged(base, { ...base, timeoutSeconds: 30 }), true);assert.equal(configurationChanged(base, { ...base, enabled: false }), true);// Re-enabling does not invalidate anything: nothing was running.assert.equal(configurationChanged({ ...base, enabled: false }, base), false);@@ -545,3 +546,43 @@ test("a server whose catalog cannot be listed lands as failed with the reason",assert.deepEqual(await rt.toolsForProject("/repo"), []);assert.equal(rt.statusFor("stub").state, "failed");});++test("custom timeoutSeconds overrides default connect and call timeouts on client creation", () => {+ let createdConfig = null;+ const rt = new UserMcpRuntime({+ createClient: (config) => {+ createdConfig = config;+ return {+ connect: async () => [],+ callTool: async () => ({}),+ getTools: () => [],+ isConnected: () => false,+ close: () => {},+ ping: async () => {},+ };+ },+ connectTimeoutMs: 10_000,+ callTimeoutMs: 100_000,+ discoveryTimeoutMs: 30_000,+ });++ rt.setRecords([+ {+ id: "slow-server",+ label: "Slow Server",+ transport: "stdio",+ command: "node",+ args: ["slow.mjs"],+ enabled: true,+ timeoutSeconds: 45,+ createdAt: "",+ updatedAt: "",+ },+ ]);++ void rt.connect(rt.listRecords()[0]);+ assert.ok(createdConfig);+ assert.equal(createdConfig.connectTimeoutMs, 45_000);+ assert.equal(createdConfig.callTimeoutMs, 100_000);+ assert.equal(createdConfig.discoveryTimeoutMs, 45_000);+});diff --git a/crates/host-core/src/mcp_servers.rs b/crates/host-core/src/mcp_servers.rsindex 03da468ca..2b17006ac 100644--- a/crates/host-core/src/mcp_servers.rs+++ b/crates/host-core/src/mcp_servers.rs@@ -41,6 +41,8 @@ pub struct McpServerRecord {pub url: Option<String>,#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]pub headers: BTreeMap<String, String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub timeout_seconds: Option<u64>,pub enabled: bool,#[serde(default)]pub scope: ActivationScope,@@ -68,6 +70,8 @@ struct McpConfig {url: Option<String>,#[serde(default)]headers: BTreeMap<String, String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ timeout_seconds: Option<u64>,}#[derive(Debug, Clone, Default, Deserialize)]@@ -84,6 +88,7 @@ pub struct McpServerInput {pub env: Option<BTreeMap<String, String>>,pub url: Option<String>,pub headers: Option<BTreeMap<String, String>>,+ pub timeout_seconds: Option<u64>,pub enabled: Option<bool>,/// Kept for protocol compatibility; capability state is app-local instead.#[allow(dead_code)]@@ -242,6 +247,7 @@ impl McpServerRegistry {env: config.env,url: config.url,headers: config.headers,+ timeout_seconds: config.timeout_seconds,enabled,scope: scope_for(level, owner_project_path.as_deref()),created_at: updated_at.clone(),@@ -319,6 +325,11 @@ impl McpServerRegistry {if let Some(description) = &config.description {check_len("description", description)?;}+ if let Some(timeout) = config.timeout_seconds {+ if !(1..=600).contains(&timeout) {+ bail!("MCP_INVALID: timeoutSeconds must be between 1 and 600");+ }+ }match config.transport.as_str() {"stdio" => {let command = config@@ -411,6 +422,9 @@ impl McpServerRegistry {.filter(|value| !value.is_empty()).or_else(|| current.and_then(|record| record.description.clone())),transport,+ timeout_seconds: input+ .timeout_seconds+ .or_else(|| current.and_then(|record| record.timeout_seconds)),..Default::default()};if config.transport == "stdio" {diff --git a/crates/host-core/src/mcp_servers/tests.rs b/crates/host-core/src/mcp_servers/tests.rsindex 907eb46a1..164c14bb1 100644--- a/crates/host-core/src/mcp_servers/tests.rs+++ b/crates/host-core/src/mcp_servers/tests.rs@@ -34,6 +34,12 @@ fn validation_accepts_http_endpoints_and_rejects_bad_ids() {assert!(McpServerRegistry::validate_config(&config).is_err());config.command = Some("node".into());assert!(McpServerRegistry::validate_config(&config).is_ok());+ config.timeout_seconds = Some(0);+ assert!(McpServerRegistry::validate_config(&config).is_err());+ config.timeout_seconds = Some(601);+ assert!(McpServerRegistry::validate_config(&config).is_err());+ config.timeout_seconds = Some(60);+ assert!(McpServerRegistry::validate_config(&config).is_ok());}#[test]@@ -65,6 +71,7 @@ fn disabled_project_server_shadows_global_server() {env: BTreeMap::new(),url: None,headers: BTreeMap::new(),+ timeout_seconds: None,enabled: true,scope: ActivationScope::default(),created_at: String::new(),diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 4ac094496..f14f48384 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -2337,7 +2337,11 @@ sklm: {"errorCommandDots": "Der Befehl darf „..\" nicht enthalten.","errorUrl": "Eine URL ist erforderlich.","errorUrlShape": "Das ist keine gültige URL.",- "errorUrlScheme": "Verwenden Sie eine http- oder https-URL."+ "errorUrlScheme": "Verwenden Sie eine http- oder https-URL.",+ "timeout": "Verbindungs-Timeout",+ "timeoutHint": "Timeout in Sekunden für Verbindung und Tool-Erkennung (Standard: 10s, max: 600s).",+ "timeoutPlaceholder": "10",+ "errorTimeoutRange": "Das Timeout muss zwischen 1 und 600 Sekunden liegen."},"skills": {"add": "Neue Fertigkeit",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 3fbb662d0..8d123dda7 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -2382,6 +2382,10 @@ importConfirm: "Imported extensions run inside the agent process with the same aerrorUrl: "A URL is required.",errorUrlShape: "That isn't a valid URL.",errorUrlScheme: "Use an http or https URL.",+ timeout: "Connection timeout",+ timeoutHint: "Timeout in seconds for connecting and discovering tools (default: 10s, max: 600s).",+ timeoutPlaceholder: "10",+ errorTimeoutRange: "Timeout must be between 1 and 600 seconds.",},skills: {add: "New skill",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex ca0c3a2fa..81cbc51bb 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -2337,7 +2337,11 @@ sklm: {"errorCommandDots": "El comando no puede contener '..'.","errorUrl": "Se requiere una URL.","errorUrlShape": "Esa no es una URL válida.",- "errorUrlScheme": "Utilice una URL http o https."+ "errorUrlScheme": "Utilice una URL http o https.",+ "timeout": "Tiempo de espera de conexión",+ "timeoutHint": "Tiempo de espera en segundos para conectar y descubrir herramientas (predeterminado: 10s, máx: 600s).",+ "timeoutPlaceholder": "10",+ "errorTimeoutRange": "El tiempo de espera debe estar entre 1 y 600 segundos."},"skills": {"add": "Nueva habilidad",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 1c6a32753..cb91f62ec 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -2337,7 +2337,11 @@ sklm: {"errorCommandDots": "La commande ne peut pas contenir '..'.","errorUrl": "Une URL est requise.","errorUrlShape": "Ce n'est pas une URL valide.",- "errorUrlScheme": "Utilisez une URL http ou https."+ "errorUrlScheme": "Utilisez une URL http ou https.",+ "timeout": "Délai de connexion",+ "timeoutHint": "Délai en secondes pour la connexion et la détection des outils (défaut : 10s, max : 600s).",+ "timeoutPlaceholder": "10",+ "errorTimeoutRange": "Le délai doit être compris entre 1 et 600 secondes."},"skills": {"add": "Nouvelle compétence",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex f2a38bcee..bf1ea7e18 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -2372,6 +2372,10 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이errorUrl: "URL을 입력하세요.",errorUrlShape: "올바른 URL이 아닙니다.",errorUrlScheme: "http 또는 https URL을 사용하세요.",+ timeout: "연결 타임아웃",+ timeoutHint: "연결 및 도구 검색 제한 시간(초 단위, 기본값: 10초, 최대: 600초).",+ timeoutPlaceholder: "10",+ errorTimeoutRange: "타임아웃은 1초에서 600초 사이여야 합니다.",},skills: {add: "새 스킬",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 1a3e60627..65e1cd06b 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -2287,7 +2287,11 @@ export const ptBR = {errorCommandDots: "O comando não pode conter '..'.",errorUrl: "Uma URL é obrigatória.",errorUrlShape: "Esta não é uma URL válida.",- errorUrlScheme: "Use uma URL http ou https."+ errorUrlScheme: "Use uma URL http ou https.",+ timeout: "Tempo limite de conexão",+ timeoutHint: "Tempo limite em segundos para conectar e listar ferramentas (padrão: 10s, máx: 600s).",+ timeoutPlaceholder: "10",+ errorTimeoutRange: "O tempo limite deve ser entre 1 e 600 segundos.",},skills: {add: "Nova habilidade",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex bbca80d00..74f43501e 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -2362,6 +2362,10 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araçerrorUrl: "Bir URL gerekli.",errorUrlShape: "Bu geçerli bir URL değil.",errorUrlScheme: "http veya https URL kullanın.",+ timeout: "Bağlantı zaman aşımı",+ timeoutHint: "Bağlantı ve araç keşfi için saniye cinsinden zaman aşımı (varsayılan: 10s, maks: 600s).",+ timeoutPlaceholder: "10",+ errorTimeoutRange: "Zaman aşımı 1 ile 600 saniye arasında olmalıdır.",},skills: {add: "Yeni beceri",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 8bdff779b..6694eec00 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -2326,6 +2326,10 @@ sklm: {errorUrl: "地址不能为空。",errorUrlShape: "这不是一个有效的 URL。",errorUrlScheme: "请使用 http 或 https 地址。",+ timeout: "连接超时",+ timeoutHint: "连接与发现工具的超时时间(秒,默认 10 秒,最大 600 秒)。",+ timeoutPlaceholder: "10",+ errorTimeoutRange: "超时时间必须在 1 到 600 秒之间。",},skills: {add: "新建技能",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 7d4fa5fa4..7eb837603 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -2325,6 +2325,10 @@ sklm: {errorUrl: "地址不能為空。",errorUrlShape: "這不是一個有效的 URL。",errorUrlScheme: "請使用 http 或 https 地址。",+ timeout: "連線逾時",+ timeoutHint: "連線與發現工具的逾時時間(秒,預設 10 秒,最大 600 秒)。",+ timeoutPlaceholder: "10",+ errorTimeoutRange: "逾時時間必須在 1 到 600 秒之間。",},skills: {add: "新建技能",diff --git a/packages/shared/src/types/capabilities.ts b/packages/shared/src/types/capabilities.tsindex f1af2a7b5..358c771fc 100644--- a/packages/shared/src/types/capabilities.ts+++ b/packages/shared/src/types/capabilities.ts@@ -62,6 +62,8 @@ export type McpServerRecord = {/** http: absolute endpoint; HTTP is allowed for local and LAN servers. */url?: string;headers?: Record<string, string>;+ /** Handshake/connection timeout in seconds (optional override). */+ timeoutSeconds?: number;enabled: boolean;scope?: ActivationScope;createdAt: string;@@ -81,6 +83,7 @@ export type McpServerInput = {env?: Record<string, string>;url?: string;headers?: Record<string, string>;+ timeoutSeconds?: number;enabled?: boolean;scope?: ActivationScope;};