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(desktop): resolve Windows npx stdio MCP via node and fnm
vastsa57191c712e07
diff --git a/apps/desktop/electron/main/mcp-stdio-launch.ts b/apps/desktop/electron/main/mcp-stdio-launch.tsnew file mode 100644index 000000000..c0d0a863a--- /dev/null+++ b/apps/desktop/electron/main/mcp-stdio-launch.ts@@ -0,0 +1,527 @@+import { realpathSync, statSync } from "node:fs";+import { homedir as osHomedir } from "node:os";+import nodePath from "node:path";++/**+ * Host env keys a stdio MCP child may inherit. Provider keys and shell secrets+ * stay out (D018). Profile / toolchain locations are required so `npx` and+ * `uvx` can find `node` / `uv` the way a terminal would.+ */+export const MCP_STDIO_HOST_ENV_KEYS = [+ "PATH",+ "Path",+ "SystemRoot",+ "SYSTEMROOT",+ "windir",+ "TEMP",+ "TMP",+ "TMPDIR",+ "LANG",+ "LC_ALL",+ "HOME",+ "USER",+ "LOGNAME",+ "USERPROFILE",+ "HOMEDRIVE",+ "HOMEPATH",+ "APPDATA",+ "LOCALAPPDATA",+ "ProgramData",+ "ProgramFiles",+ "ProgramFiles(x86)",+ "ProgramW6432",+ "PATHEXT",+ "ComSpec",+ "COMSPEC",+ "FNM_DIR",+ "FNM_ARCH",+ "NVM_HOME",+ "NVM_SYMLINK",+ "VOLTA_HOME",+ "CARGO_HOME",+ "XDG_DATA_HOME",+ "XDG_CACHE_HOME",+ "XDG_CONFIG_HOME",+] as const;++const DEFAULT_WIN_PATHEXT = ".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC";++const NODE_LAUNCHERS: Record<string, true> = {+ node: true,+ npm: true,+ npx: true,+ pnpm: true,+ yarn: true,+};+const UV_LAUNCHERS: Record<string, true> = { uv: true, uvx: true };++export type McpLaunchFs = {+ isFile: (path: string) => boolean;+ realpath: (path: string) => string;+};++export type McpStdioLaunch = {+ command: string;+ args: string[];+ env: Record<string, string>;+ windowsHide?: boolean;+ windowsVerbatimArguments?: boolean;+};++export type McpStdioLaunchOptions = {+ command: string;+ args: string[];+ env: Record<string, string>;+ platform?: NodeJS.Platform;+ hostEnv?: NodeJS.ProcessEnv;+ home?: string;+ fs?: McpLaunchFs;+};++function pathFor(platform: string): nodePath.PlatformPath {+ return platform === "win32" ? nodePath.win32 : nodePath.posix;+}++function defaultFs(): McpLaunchFs {+ return {+ isFile: (target) => {+ try {+ return statSync(target).isFile();+ } catch {+ return false;+ }+ },+ realpath: (target) => {+ try {+ return realpathSync(target);+ } catch {+ return target;+ }+ },+ };+}++function hostValue(+ hostEnv: NodeJS.ProcessEnv,+ key: string,+ win32: boolean,+): string | undefined {+ const direct = hostEnv[key];+ if (typeof direct === "string" && direct.length > 0) return direct;+ if (!win32) return undefined;+ const found = Object.keys(hostEnv).find((entry) => entry.toLowerCase() === key.toLowerCase());+ const value = found ? hostEnv[found] : undefined;+ return typeof value === "string" && value.length > 0 ? value : undefined;+}++function hostPath(hostEnv: NodeJS.ProcessEnv, win32: boolean): string {+ return hostValue(hostEnv, "PATH", win32) ?? hostValue(hostEnv, "Path", win32) ?? "";+}++function launcherName(command: string, paths: nodePath.PlatformPath): string {+ return paths+ .basename(command)+ .toLowerCase()+ .replace(/\.(cmd|bat|exe|ps1)$/i, "");+}++function pathextList(hostEnv: NodeJS.ProcessEnv, win32: boolean): string[] {+ if (!win32) return [""];+ const raw = hostValue(hostEnv, "PATHEXT", win32) ?? DEFAULT_WIN_PATHEXT;+ const exts = raw+ .split(";")+ .map((entry) => entry.trim())+ .filter(Boolean);+ // Official Node ships an extensionless Git-Bash `npx` next to `npx.cmd`.+ // Windows PATHEXT order must win so spawn never picks the shell script.+ return [...exts, ""];+}++function lookOnPath(+ name: string,+ pathValue: string,+ paths: nodePath.PlatformPath,+ exts: string[],+ isFile: (path: string) => boolean,+): string | undefined {+ for (const dir of pathValue.split(paths.delimiter)) {+ if (!dir) continue;+ for (const ext of exts) {+ const variants = ext+ ? [...new Set([ext.toLowerCase(), ext, ext.toUpperCase()])]+ : [""];+ for (const variant of variants) {+ const candidate = paths.join(dir, `${name}${variant}`);+ if (isFile(candidate)) return candidate;+ }+ }+ }+ return undefined;+}++function firstFile(candidates: string[], isFile: (path: string) => boolean): string | undefined {+ return candidates.find(isFile);+}++function discoverFnmNode(+ hostEnv: NodeJS.ProcessEnv,+ home: string,+ paths: nodePath.PlatformPath,+ fs: McpLaunchFs,+ win32: boolean,+): string | undefined {+ const localApp = hostValue(hostEnv, "LOCALAPPDATA", win32) ?? paths.join(home, "AppData", "Local");+ const dataHome = hostValue(hostEnv, "XDG_DATA_HOME", win32) ?? paths.join(home, ".local", "share");+ const roots = [+ hostValue(hostEnv, "FNM_DIR", win32),+ paths.join(localApp, "fnm"),+ paths.join(home, ".fnm"),+ paths.join(dataHome, "fnm"),+ paths.join(home, "Library", "Application Support", "fnm"),+ ].filter((root): root is string => Boolean(root));+ const binaries = win32+ ? (versionDir: string) => [+ paths.join(versionDir, "installation", "node.exe"),+ paths.join(versionDir, "node.exe"),+ paths.join(versionDir, "installation", "bin", "node.exe"),+ ]+ : (versionDir: string) => [+ paths.join(versionDir, "installation", "bin", "node"),+ paths.join(versionDir, "bin", "node"),+ paths.join(versionDir, "installation", "node"),+ ];+ for (const root of roots) {+ const versionDir = fs.realpath(paths.join(root, "aliases", "default"));+ const found = firstFile(binaries(versionDir), fs.isFile);+ if (found) return found;+ }+ return undefined;+}++function discoverNvmWindowsNode(+ hostEnv: NodeJS.ProcessEnv,+ paths: nodePath.PlatformPath,+ isFile: (path: string) => boolean,+): string | undefined {+ const symlink = hostValue(hostEnv, "NVM_SYMLINK", true);+ const programFiles = hostValue(hostEnv, "ProgramFiles", true) ?? paths.join("C:", "Program Files");+ return firstFile(+ [+ ...(symlink ? [paths.join(symlink, "node.exe")] : []),+ paths.join(programFiles, "nodejs", "node.exe"),+ ],+ isFile,+ );+}++function discoverVoltaNode(+ hostEnv: NodeJS.ProcessEnv,+ home: string,+ paths: nodePath.PlatformPath,+ isFile: (path: string) => boolean,+ win32: boolean,+): string | undefined {+ const volta = hostValue(hostEnv, "VOLTA_HOME", win32) ?? paths.join(home, ".volta");+ return firstFile(+ [paths.join(volta, "bin", win32 ? "node.exe" : "node")],+ isFile,+ );+}++function discoverUnixNode(+ home: string,+ paths: nodePath.PlatformPath,+ isFile: (path: string) => boolean,+): string | undefined {+ return firstFile(+ [+ paths.join(home, ".local", "share", "fnm", "aliases", "default", "bin", "node"),+ "/opt/homebrew/bin/node",+ "/usr/local/bin/node",+ ],+ isFile,+ );+}++export function discoverNodeExecutable(+ options: Pick<McpStdioLaunchOptions, "platform" | "hostEnv" | "home" | "fs">,+): string | undefined {+ const platform = options.platform ?? process.platform;+ const hostEnv = options.hostEnv ?? process.env;+ const home = options.home ?? osHomedir();+ const fs = options.fs ?? defaultFs();+ const paths = pathFor(platform);+ const win32 = platform === "win32";+ const onPath = lookOnPath("node", hostPath(hostEnv, win32), paths, pathextList(hostEnv, win32), fs.isFile);+ if (onPath) return onPath;+ return (+ discoverFnmNode(hostEnv, home, paths, fs, win32) ??+ (win32 ? discoverNvmWindowsNode(hostEnv, paths, fs.isFile) : undefined) ??+ discoverVoltaNode(hostEnv, home, paths, fs.isFile, win32) ??+ (win32 ? undefined : discoverUnixNode(home, paths, fs.isFile))+ );+}++export function discoverUvExecutable(+ options: Pick<McpStdioLaunchOptions, "platform" | "hostEnv" | "home" | "fs">,+): string | undefined {+ const platform = options.platform ?? process.platform;+ const hostEnv = options.hostEnv ?? process.env;+ const home = options.home ?? osHomedir();+ const fs = options.fs ?? defaultFs();+ const paths = pathFor(platform);+ const win32 = platform === "win32";+ const exts = pathextList(hostEnv, win32);+ const onPath = lookOnPath("uv", hostPath(hostEnv, win32), paths, exts, fs.isFile);+ if (onPath) return onPath;+ const cargo = hostValue(hostEnv, "CARGO_HOME", win32) ?? paths.join(home, ".cargo");+ const localBin = paths.join(home, ".local", "bin");+ return firstFile(+ win32+ ? [+ paths.join(localBin, "uv.exe"),+ paths.join(cargo, "bin", "uv.exe"),+ paths.join(home, "AppData", "Roaming", "uv", "uv.exe"),+ ]+ : [+ paths.join(localBin, "uv"),+ paths.join(cargo, "bin", "uv"),+ "/opt/homebrew/bin/uv",+ "/usr/local/bin/uv",+ ],+ fs.isFile,+ );+}++function siblingTool(+ executable: string,+ name: string,+ paths: nodePath.PlatformPath,+ isFile: (path: string) => boolean,+ win32: boolean,+): string | undefined {+ const dir = paths.dirname(executable);+ const candidates = win32+ ? [`${name}.exe`, `${name}.cmd`, name]+ : [name, `${name}.exe`];+ return firstFile(+ candidates.map((file) => paths.join(dir, file)),+ isFile,+ );+}++function npxCliFromNode(+ nodePath: string,+ paths: nodePath.PlatformPath,+ isFile: (path: string) => boolean,+): string | undefined {+ const dir = paths.dirname(nodePath);+ return firstFile(+ [+ paths.join(dir, "node_modules", "npm", "bin", "npx-cli.js"),+ paths.join(dir, "..", "lib", "node_modules", "npm", "bin", "npx-cli.js"),+ paths.join(dir, "..", "node_modules", "npm", "bin", "npx-cli.js"),+ ],+ isFile,+ );+}++function npmCliFromNode(+ nodePath: string,+ paths: nodePath.PlatformPath,+ isFile: (path: string) => boolean,+): string | undefined {+ const dir = paths.dirname(nodePath);+ return firstFile(+ [+ paths.join(dir, "node_modules", "npm", "bin", "npm-cli.js"),+ paths.join(dir, "..", "lib", "node_modules", "npm", "bin", "npm-cli.js"),+ paths.join(dir, "..", "node_modules", "npm", "bin", "npm-cli.js"),+ ],+ isFile,+ );+}++function isCmdShim(command: string): boolean {+ return /\.(cmd|bat)$/i.test(command);+}++/**+ * Quote one argument for `cmd.exe /d /s /c`. Arguments stay literal: `&` `|`+ * inside quotes are data, not a second command.+ */+export function quoteWindowsCmdArg(arg: string): string {+ if (arg.length === 0) return '""';+ if (!/[\s"]/.test(arg) && !/[&<>()^|%!]/.test(arg)) return arg;+ // Escape % so cmd.exe does not expand environment variables inside quotes,+ // then double internal quotes so they survive the cmd parser.+ return `"${arg.replace(/%/g, "%%").replace(/"/g, '""')}"`;+}++function wrapCmdShim(+ file: string,+ args: string[],+ hostEnv: NodeJS.ProcessEnv,+ paths: nodePath.PlatformPath,+): Pick<McpStdioLaunch, "command" | "args" | "windowsHide" | "windowsVerbatimArguments"> {+ const comspec =+ hostValue(hostEnv, "ComSpec", true) ??+ hostValue(hostEnv, "COMSPEC", true) ??+ paths.join(hostValue(hostEnv, "SystemRoot", true) ?? "C:\\Windows", "System32", "cmd.exe");+ const line = [file, ...args].map(quoteWindowsCmdArg).join(" ");+ // Outer quotes survive cmd.exe /s /c stripping — it removes the first and+ // last quote, keeping inner quoting intact even when the .cmd path has spaces.+ return {+ command: comspec,+ args: ["/d", "/s", "/c", `"${line}"`],+ windowsHide: true,+ windowsVerbatimArguments: true,+ };+}++function prependPath(+ pathValue: string,+ dirs: string[],+ delimiter: string,+ win32: boolean,+): string {+ const existing = pathValue.split(delimiter).filter(Boolean);+ const seen = new Set(existing.map((dir) => (win32 ? dir.toLowerCase() : dir)));+ const extra: string[] = [];+ for (const dir of dirs) {+ if (!dir) continue;+ const key = win32 ? dir.toLowerCase() : dir;+ if (seen.has(key)) continue;+ seen.add(key);+ extra.push(dir);+ }+ return [...extra, ...existing].join(delimiter);+}++function withToolPath(+ env: Record<string, string>,+ executable: string | undefined,+ paths: nodePath.PlatformPath,+ win32: boolean,+): Record<string, string> {+ if (!executable) return env;+ const dir = paths.dirname(executable);+ const current = env.PATH ?? env.Path ?? "";+ const next = prependPath(current, [dir], paths.delimiter, win32);+ const out = { ...env, PATH: next };+ if ("Path" in out && win32) out.Path = next;+ return out;+}++/**+ * Turn a configured stdio command into something `spawn({ shell: false })`+ * can actually start: resolve `npx`/`uvx` onto real binaries (fnm, uv,+ * nvm-windows, PATH), rewrite npm shims to `node` + `npx-cli.js`, and wrap+ * remaining Windows `.cmd` files with `cmd.exe` so arguments stay literal.+ */+export function resolveMcpStdioLaunch(options: McpStdioLaunchOptions): McpStdioLaunch {+ const platform = options.platform ?? process.platform;+ const hostEnv = options.hostEnv ?? process.env;+ const home = options.home ?? osHomedir();+ const fs = options.fs ?? defaultFs();+ const paths = pathFor(platform);+ const win32 = platform === "win32";+ const command = options.command.trim();+ const args = options.args;+ const name = launcherName(command, paths);+ const discoverOpts = { platform, hostEnv, home, fs };++ let env = options.env;+ let launchCommand = command;+ let launchArgs = args;+ let windowsHide: boolean | undefined;+ let windowsVerbatimArguments: boolean | undefined;++ if (NODE_LAUNCHERS[name]) {+ const node = discoverNodeExecutable(discoverOpts);+ env = withToolPath(env, node, paths, win32);+ if (node && (name === "npx" || name === "npm")) {+ const cli =+ name === "npx" ? npxCliFromNode(node, paths, fs.isFile) : npmCliFromNode(node, paths, fs.isFile);+ if (cli) {+ launchCommand = node;+ launchArgs = [cli, ...args];+ } else {+ const shim = siblingTool(node, name, paths, fs.isFile, win32);+ if (shim) launchCommand = shim;+ }+ } else if (node && name === "node") {+ launchCommand = node;+ } else if (node) {+ const shim = siblingTool(node, name, paths, fs.isFile, win32);+ if (shim) {+ launchCommand = shim;+ } else {+ const found = lookOnPath(name, hostPath(hostEnv, win32), paths, pathextList(hostEnv, win32), fs.isFile);+ if (found) launchCommand = found;+ }+ }+ if (launchCommand === command) {+ const found = lookOnPath(name, hostPath(hostEnv, win32), paths, pathextList(hostEnv, win32), fs.isFile);+ if (found) {+ launchCommand = found;+ env = withToolPath(env, found, paths, win32);+ }+ }+ } else if (UV_LAUNCHERS[name]) {+ const uv = discoverUvExecutable(discoverOpts);+ env = withToolPath(env, uv, paths, win32);+ if (uv && name === "uvx") {+ const uvx = siblingTool(uv, "uvx", paths, fs.isFile, win32);+ if (uvx && !isCmdShim(uvx)) {+ launchCommand = uvx;+ } else {+ launchCommand = uv;+ launchArgs = ["tool", "run", ...args];+ }+ } else if (uv) {+ launchCommand = uv;+ }+ } else if (paths.isAbsolute(command) && fs.isFile(command)) {+ env = withToolPath(env, command, paths, win32);+ } else {+ const found = lookOnPath(name, hostPath(hostEnv, win32), paths, pathextList(hostEnv, win32), fs.isFile);+ if (found) {+ launchCommand = found;+ env = withToolPath(env, found, paths, win32);+ }+ }++ if (win32 && isCmdShim(launchCommand)) {+ const wrapped = wrapCmdShim(launchCommand, launchArgs, hostEnv, paths);+ launchCommand = wrapped.command;+ launchArgs = wrapped.args;+ windowsHide = wrapped.windowsHide;+ windowsVerbatimArguments = wrapped.windowsVerbatimArguments;+ } else if (win32) {+ windowsHide = true;+ }++ return {+ command: launchCommand,+ args: launchArgs,+ env,+ windowsHide,+ windowsVerbatimArguments,+ };+}++/** Decode MCP child stderr; cmd.exe on Windows writes the ANSI/OEM code page. */+export function decodeMcpStderr(+ chunk: Buffer | string,+ platform: NodeJS.Platform = process.platform,+ oem = false,+): string {+ if (typeof chunk === "string") return chunk;+ if (platform !== "win32" || !oem) return chunk.toString("utf8");+ try {+ return new TextDecoder("gbk").decode(chunk);+ } catch {+ return chunk.toString("utf8");+ }+}diff --git a/apps/desktop/electron/main/plugin-mcp.ts b/apps/desktop/electron/main/plugin-mcp.tsindex fe96a7170..66d543ea1 100644--- a/apps/desktop/electron/main/plugin-mcp.ts+++ b/apps/desktop/electron/main/plugin-mcp.ts@@ -2,6 +2,11 @@ import { spawn as nodeSpawn, type ChildProcess } from "node:child_process";import { isAbsolute, resolve, sep } from "node:path";import type { PluginMcpServerContrib } from "@pi-desktop/plugin-sdk";import { minimalChildEnv } from "./child-process-env.ts";+import {+ MCP_STDIO_HOST_ENV_KEYS,+ decodeMcpStderr,+ resolveMcpStdioLaunch,+} from "./mcp-stdio-launch.ts";import { userLookupPath } from "./user-login-path.ts";/** MCP revision we advertise during the handshake. */@@ -74,19 +79,35 @@ function mcpError(code: string, message: string): McpError {* PATH is the login-shell PATH (ADR 0045 / D600), not the Finder/Dock GUI* PATH, so a market-installed `uvx`/`npx` server can spawn (issue #571). The* identity variables cross for the same reason the toolchain ones do: the child- * is third-party code that resolves `~` through `$HOME` (issue #717).+ * is third-party code that resolves `~` through `$HOME` (issue #717). Windows+ * also needs `PATHEXT` / `ComSpec` / `FNM_DIR` so official Node and fnm shims+ * resolve (issue #789).*/export function mcpProcessEnv(pluginId: string | undefined,values: Record<string, string>,+ hostEnv: NodeJS.ProcessEnv = process.env,): Record<string, string> {const env: Record<string, string> = {...(pluginId ? { PI_PLUGIN_ID: pluginId } : {}),- NODE_ENV: process.env.NODE_ENV ?? "production",- ...minimalChildEnv(),+ NODE_ENV: hostEnv.NODE_ENV ?? process.env.NODE_ENV ?? "production",};- const path = userLookupPath(process.env.PATH ?? "");- if (path) env.PATH = path;+ if (hostEnv === process.env) {+ Object.assign(env, minimalChildEnv());+ for (const key of MCP_STDIO_HOST_ENV_KEYS) {+ if (env[key]) continue;+ const value = process.env[key];+ if (value) env[key] = value;+ }+ const path = userLookupPath(process.env.PATH ?? "");+ if (path) env.PATH = path;+ } else {+ for (const key of MCP_STDIO_HOST_ENV_KEYS) {+ const value = hostEnv[key];+ if (value) env[key] = value;+ }+ if (!env.PATH && env.Path) env.PATH = env.Path;+ }return { ...env, ...values };}@@ -138,17 +159,26 @@ function createStdioTransport(handlers: McpTransportHandlers,): McpTransport {const spawnImpl = options.spawnImpl ?? nodeSpawn;- const child: ChildProcess = spawnImpl(- resolveMcpCommand(options.rootPath, options.command, options.commandPolicy),- options.args,- {- cwd: options.rootPath,- env: options.env,- stdio: ["pipe", "pipe", "pipe"],- // Never route through a shell: arguments stay literal.- shell: false,+ const resolved = resolveMcpCommand(options.rootPath, options.command, options.commandPolicy);+ const launch = resolveMcpStdioLaunch({+ command: resolved,+ args: options.args,+ env: options.env,+ hostEnv: {+ ...process.env,+ PATH: options.env.PATH ?? process.env.PATH,},- );+ });+ const child: ChildProcess = spawnImpl(launch.command, launch.args, {+ cwd: options.rootPath,+ env: launch.env,+ stdio: ["pipe", "pipe", "pipe"],+ // Arguments stay literal. Known launchers rewrite to a PE binary; remaining+ // Windows `.cmd` shims go through `cmd.exe /d /s /c` with quoted args.+ shell: false,+ windowsHide: launch.windowsHide,+ windowsVerbatimArguments: launch.windowsVerbatimArguments,+ });let closed = false;let buffer = "";@@ -178,9 +208,14 @@ function createStdioTransport(index = buffer.indexOf("\n");}});- child.stderr?.setEncoding("utf8");- child.stderr?.on("data", (chunk: string) => {- lastStderr = String(chunk).trimEnd().slice(-500);+ child.stderr?.on("data", (chunk: Buffer | string) => {+ lastStderr = decodeMcpStderr(+ chunk,+ process.platform,+ Boolean(launch.windowsVerbatimArguments),+ )+ .trimEnd()+ .slice(-500);});child.on("error", (error: Error) => {closed = true;diff --git a/apps/desktop/src/components/extensions/McpEditorSheet.tsx b/apps/desktop/src/components/extensions/McpEditorSheet.tsxindex 07da5316a..092e4823f 100644--- a/apps/desktop/src/components/extensions/McpEditorSheet.tsx+++ b/apps/desktop/src/components/extensions/McpEditorSheet.tsx@@ -16,6 +16,10 @@ import { Button, Field, HelpIcon, Input, SettingsToggle, TooltipButton, cx, portimport { IconPlay, IconServer, IconTerminal, IconX } from "../icons";import { ScopeControl } from "./ScopeControl";import { KeyValueRows, pairsToRecord, recordToPairs, type KeyValuePair } from "./KeyValueRows";+import {+ MCP_STDIO_LAUNCHER_PRESETS,+ mcpStdioLauncherChoice,+} from "./mcp-stdio-launcher";/*** Tool names shown beside a test result.@@ -53,7 +57,7 @@ export function emptyMcpDraft(): McpDraft {label: "",description: "",transport: "stdio",- command: "",+ command: "npx",args: "",env: [],url: "",@@ -249,6 +253,7 @@ export function McpEditorSheet({}) {const { t } = useTranslation();const [idTouched, setIdTouched] = useState(!!editing);+ const launcher = mcpStdioLauncherChoice(draft.command);const errorKey = mcpDraftError(draft);// A form the user has not started saying "an identifier is required" scolds// them for opening it. The message appears once there is something to correct.@@ -256,7 +261,7 @@ export function McpEditorSheet({!editing &&!draft.id.trim() &&!draft.label.trim() &&- !draft.command.trim() &&+ (draft.command.trim() === "" || draft.command.trim().toLowerCase() === "npx") &&!draft.url.trim();useEffect(() => {@@ -380,17 +385,59 @@ export function McpEditorSheet({{draft.transport === "stdio" ? (<>- <Field label={t("extensions.mcp.command")} hint={t("extensions.mcp.commandHint")}>- <Input- value={draft.command}- placeholder="npx"- onChange={(event) => set("command", event.target.value)}- />- </Field>+ <div className="ext-field-group">+ <div className="ext-field-label">+ {t("extensions.mcp.command")}+ <HelpIcon+ label={t(+ launcher === "npx"+ ? "extensions.mcp.commandHintNpx"+ : launcher === "uvx"+ ? "extensions.mcp.commandHintUvx"+ : "extensions.mcp.commandHint",+ )}+ />+ </div>+ <div className="ext-preset-pick" role="radiogroup" aria-label={t("extensions.mcp.command")}>+ {MCP_STDIO_LAUNCHER_PRESETS.map((id) => (+ <button+ key={id}+ type="button"+ role="radio"+ aria-checked={launcher === id}+ className={cx("ext-preset-chip", launcher === id && "is-selected")}+ onClick={() => set("command", id)}+ >+ <span className="ext-preset-chip-name">{id}</span>+ </button>+ ))}+ <button+ type="button"+ role="radio"+ aria-checked={launcher === "custom"}+ className={cx("ext-preset-chip", launcher === "custom" && "is-selected")}+ onClick={() => {+ if (launcher === "custom") return;+ set("command", "");+ }}+ >+ <span className="ext-preset-chip-name">{t("extensions.mcp.launcherCustom")}</span>+ </button>+ </div>+ </div>+ {launcher === "custom" ? (+ <Field label={t("extensions.mcp.commandPath")} hint={t("extensions.mcp.commandHint")}>+ <Input+ value={draft.command}+ placeholder={t("extensions.mcp.commandPlaceholder")}+ onChange={(event) => set("command", event.target.value)}+ />+ </Field>+ ) : null}<Field label={t("extensions.mcp.args")} hint={t("extensions.mcp.argsHint")}><Inputvalue={draft.args}- placeholder="-y @upstash/context7-mcp"+ placeholder={launcher === "uvx" ? "mcp-server-git" : "-y @upstash/context7-mcp"}onChange={(event) => set("args", event.target.value)}/></Field>diff --git a/apps/desktop/src/components/extensions/mcp-stdio-launcher.ts b/apps/desktop/src/components/extensions/mcp-stdio-launcher.tsnew file mode 100644index 000000000..d791ce13a--- /dev/null+++ b/apps/desktop/src/components/extensions/mcp-stdio-launcher.ts@@ -0,0 +1,9 @@+export const MCP_STDIO_LAUNCHER_PRESETS = ["npx", "uvx"] as const;+export type McpStdioLauncherPreset = (typeof MCP_STDIO_LAUNCHER_PRESETS)[number];+export type McpStdioLauncherChoice = McpStdioLauncherPreset | "custom";++export function mcpStdioLauncherChoice(command: string): McpStdioLauncherChoice {+ const name = command.trim().toLowerCase();+ if (name === "npx" || name === "uvx") return name;+ return "custom";+}diff --git a/apps/desktop/test/extensions-page.test.mjs b/apps/desktop/test/extensions-page.test.mjsindex 574478423..483413ddf 100644--- a/apps/desktop/test/extensions-page.test.mjs+++ b/apps/desktop/test/extensions-page.test.mjs@@ -186,6 +186,9 @@ test("MCP management reuses the modal and validates its locked id and transportassert.match(sheet, /command\.includes\("\.\."\)/);assert.match(sheet, /isNonLoopbackHttpMcpUrl/);assert.match(sheet, /role="dialog" aria-modal/);+ assert.match(sheet, /MCP_STDIO_LAUNCHER_PRESETS/);+ assert.match(sheet, /launcherCustom/);+ assert.match(sheet, /mcpStdioLauncherChoice/);// A server may advertise thousands of tools, so the name row renders a bounded// prefix and leaves the total to the count beside it.assert.match(sheet, /MCP_TEST_TOOL_NAME_LIMIT = 24/);diff --git a/apps/desktop/test/mcp-stdio-launch.test.mjs b/apps/desktop/test/mcp-stdio-launch.test.mjsnew file mode 100644index 000000000..d03622203--- /dev/null+++ b/apps/desktop/test/mcp-stdio-launch.test.mjs@@ -0,0 +1,301 @@+import assert from "node:assert/strict";+import test from "node:test";+import path from "node:path";++import {+ decodeMcpStderr,+ discoverNodeExecutable,+ quoteWindowsCmdArg,+ resolveMcpStdioLaunch,+} from "../electron/main/mcp-stdio-launch.ts";+import { mcpProcessEnv } from "../electron/main/plugin-mcp.ts";+import { mcpStdioLauncherChoice } from "../src/components/extensions/mcp-stdio-launcher.ts";++const win = path.win32;++function winFs(files, links = {}) {+ const fileSet = new Set(files.map((file) => file.toLowerCase()));+ const linkMap = Object.fromEntries(+ Object.entries(links).map(([from, to]) => [from.toLowerCase(), to]),+ );+ return {+ isFile: (target) => fileSet.has(target.toLowerCase()),+ realpath: (target) => linkMap[target.toLowerCase()] ?? target,+ };+}++test("npx and uvx are the preset launchers; anything else is custom", () => {+ assert.equal(mcpStdioLauncherChoice("npx"), "npx");+ assert.equal(mcpStdioLauncherChoice("UVX"), "uvx");+ assert.equal(mcpStdioLauncherChoice(""), "custom");+ assert.equal(mcpStdioLauncherChoice(win.join("C:", "tools", "node.exe")), "custom");+});++test("the stdio environment copies profile keys and still strips host secrets", () => {+ const env = mcpProcessEnv(+ "com.example.mcp",+ { TOKEN: "t0ken" },+ {+ PATH: "/usr/bin",+ HOME: "/Users/pi",+ USERPROFILE: "C:\\Users\\pi",+ LOCALAPPDATA: "C:\\Users\\pi\\AppData\\Local",+ PATHEXT: ".EXE;.CMD",+ ComSpec: "C:\\Windows\\System32\\cmd.exe",+ PI_LEAKED_SECRET: "must-not-cross",+ OPENAI_API_KEY: "sk-no",+ },+ );+ assert.equal(env.PI_PLUGIN_ID, "com.example.mcp");+ assert.equal(env.TOKEN, "t0ken");+ assert.equal(env.PATH, "/usr/bin");+ assert.equal(env.HOME, "/Users/pi");+ assert.equal(env.USERPROFILE, "C:\\Users\\pi");+ assert.equal(env.LOCALAPPDATA, "C:\\Users\\pi\\AppData\\Local");+ assert.equal(env.PATHEXT, ".EXE;.CMD");+ assert.equal(env.ComSpec, "C:\\Windows\\System32\\cmd.exe");+ assert.equal(env.PI_LEAKED_SECRET, undefined);+ assert.equal(env.OPENAI_API_KEY, undefined);+});++test("fnm default node is discovered off PATH on Windows", () => {+ const local = win.join("C:", "Users", "zhao", "AppData", "Local");+ const version = win.join(local, "fnm", "node-versions", "v22.14.0");+ const installation = win.join(version, "installation");+ const node = win.join(installation, "node.exe");+ const found = discoverNodeExecutable({+ platform: "win32",+ home: win.join("C:", "Users", "zhao"),+ hostEnv: { LOCALAPPDATA: local, PATH: win.join("C:", "Windows", "System32") },+ fs: winFs(+ [node],+ { [win.join(local, "fnm", "aliases", "default")]: version },+ ),+ });+ assert.equal(found, node);+});++test("PATH node wins over an fnm install", () => {+ const local = win.join("C:", "Users", "zhao", "AppData", "Local");+ const pathNode = win.join("C:", "Program Files", "nodejs", "node.exe");+ const version = win.join(local, "fnm", "node-versions", "v22.14.0");+ const fnmNode = win.join(version, "installation", "node.exe");+ const found = discoverNodeExecutable({+ platform: "win32",+ home: win.join("C:", "Users", "zhao"),+ hostEnv: {+ LOCALAPPDATA: local,+ PATH: win.join("C:", "Program Files", "nodejs"),+ PATHEXT: ".EXE;.CMD",+ },+ fs: winFs(+ [pathNode, fnmNode],+ { [win.join(local, "fnm", "aliases", "default")]: version },+ ),+ });+ assert.equal(found.toLowerCase(), pathNode.toLowerCase());+});++test("npx rewrites to node plus npx-cli.js on macOS fnm", () => {+ const posix = path.posix;+ const home = "/Users/zhao";+ const version = posix.join(home, ".local", "share", "fnm", "node-versions", "v22.14.0");+ const node = posix.join(version, "installation", "bin", "node");+ const cli = posix.join(version, "installation", "lib", "node_modules", "npm", "bin", "npx-cli.js");+ const alias = posix.join(home, ".local", "share", "fnm", "aliases", "default");+ const launch = resolveMcpStdioLaunch({+ command: "npx",+ args: ["-y", "pkg"],+ env: { PATH: "/usr/bin" },+ platform: "darwin",+ home,+ hostEnv: { PATH: "/usr/bin", XDG_DATA_HOME: posix.join(home, ".local", "share") },+ fs: {+ isFile: (target) => target === node || target === cli,+ realpath: (target) => (target === alias ? version : target),+ },+ });+ assert.equal(launch.command, node);+ assert.deepEqual(launch.args, [cli, "-y", "pkg"]);+ assert.equal(launch.windowsHide, undefined);+});++test("npx rewrites to node plus npx-cli.js and prepends the install dir", () => {+ const local = win.join("C:", "Users", "zhao", "AppData", "Local");+ const version = win.join(local, "fnm", "node-versions", "v22.14.0");+ const installation = win.join(version, "installation");+ const node = win.join(installation, "node.exe");+ const cli = win.join(installation, "node_modules", "npm", "bin", "npx-cli.js");+ const launch = resolveMcpStdioLaunch({+ command: "npx",+ args: ["-y", "@upstash/context7-mcp"],+ env: { PATH: win.join("C:", "Windows", "System32") },+ platform: "win32",+ home: win.join("C:", "Users", "zhao"),+ hostEnv: { LOCALAPPDATA: local, PATH: win.join("C:", "Windows", "System32") },+ fs: winFs(+ [node, cli],+ { [win.join(local, "fnm", "aliases", "default")]: version },+ ),+ });+ assert.equal(launch.command, node);+ assert.deepEqual(launch.args, [cli, "-y", "@upstash/context7-mcp"]);+ assert.ok(launch.env.PATH.startsWith(`${installation}${win.delimiter}`));+ assert.equal(launch.windowsHide, true);+ assert.equal(launch.windowsVerbatimArguments, undefined);+});++test("official Windows Node rewrites npx to node.exe plus npx-cli.js", () => {+ const root = win.join("C:", "Program Files", "nodejs");+ const node = win.join(root, "node.exe");+ const cli = win.join(root, "node_modules", "npm", "bin", "npx-cli.js");+ const npxCmd = win.join(root, "npx.cmd");+ const npxSh = win.join(root, "npx");+ const launch = resolveMcpStdioLaunch({+ command: "npx",+ args: ["-y", "@modelcontextprotocol/server-memory"],+ env: { PATH: root },+ platform: "win32",+ home: win.join("C:", "Users", "alice"),+ hostEnv: { PATH: root, PATHEXT: ".COM;.EXE;.BAT;.CMD" },+ fs: winFs([node, cli, npxCmd, npxSh]),+ });+ assert.equal(launch.command.toLowerCase(), node.toLowerCase());+ assert.deepEqual(launch.args, [cli, "-y", "@modelcontextprotocol/server-memory"]);+ assert.equal(launch.windowsVerbatimArguments, undefined);+ assert.ok(launch.env.PATH.toLowerCase().includes(root.toLowerCase()));+});++test("official Windows Node prefers npx.cmd over the Git-Bash shim", () => {+ const root = win.join("C:", "Program Files", "nodejs");+ const node = win.join(root, "node.exe");+ const npxCmd = win.join(root, "npx.cmd");+ const npxSh = win.join(root, "npx");+ const comspec = win.join("C:", "Windows", "System32", "cmd.exe");+ const launch = resolveMcpStdioLaunch({+ command: "npx",+ args: ["-y", "pkg"],+ env: { PATH: root },+ platform: "win32",+ home: win.join("C:", "Users", "alice"),+ hostEnv: {+ PATH: root,+ PATHEXT: ".COM;.EXE;.BAT;.CMD",+ ComSpec: comspec,+ },+ fs: winFs([node, npxCmd, npxSh]),+ });+ assert.equal(launch.command, comspec);+ // args[3] is the entire line wrapped in outer quotes for cmd.exe /s /c+ assert.match(launch.args[3] ?? "", /npx\.cmd/i);+ assert.ok(launch.args[3].startsWith('"'), "outer quote wraps the line");+});++test("uvx uses a sibling uvx.exe when present", () => {+ const bin = win.join("C:", "Users", "zhao", ".local", "bin");+ const uv = win.join(bin, "uv.exe");+ const uvx = win.join(bin, "uvx.exe");+ const launch = resolveMcpStdioLaunch({+ command: "uvx",+ args: ["mcp-server-git"],+ env: { PATH: win.join("C:", "Windows", "System32") },+ platform: "win32",+ home: win.join("C:", "Users", "zhao"),+ hostEnv: { PATH: win.join("C:", "Windows", "System32") },+ fs: winFs([uv, uvx]),+ });+ assert.equal(launch.command, uvx);+ assert.deepEqual(launch.args, ["mcp-server-git"]);+});++test("uvx falls back to uv tool run when uvx.exe is missing", () => {+ const bin = win.join("C:", "Users", "zhao", ".local", "bin");+ const uv = win.join(bin, "uv.exe");+ const launch = resolveMcpStdioLaunch({+ command: "uvx",+ args: ["mcp-server-git"],+ env: { PATH: win.join("C:", "Windows", "System32") },+ platform: "win32",+ home: win.join("C:", "Users", "zhao"),+ hostEnv: { PATH: win.join("C:", "Windows", "System32") },+ fs: winFs([uv]),+ });+ assert.equal(launch.command, uv);+ assert.deepEqual(launch.args, ["tool", "run", "mcp-server-git"]);+});++test("a remaining Windows .cmd shim is wrapped by cmd.exe with literal args", () => {+ const npxCmd = win.join("C:", "Users", "zhao", "AppData", "Roaming", "npm", "npx.cmd");+ const comspec = win.join("C:", "Windows", "System32", "cmd.exe");+ const launch = resolveMcpStdioLaunch({+ command: npxCmd,+ args: ["-y", "pkg&whoami"],+ env: { PATH: win.join("C:", "Windows", "System32") },+ platform: "win32",+ home: win.join("C:", "Users", "zhao"),+ hostEnv: {+ PATH: win.dirname(npxCmd),+ ComSpec: comspec,+ PATHEXT: ".EXE;.CMD",+ },+ fs: winFs([npxCmd]),+ });+ assert.equal(launch.command, comspec);+ assert.equal(launch.args[0], "/d");+ assert.equal(launch.args[1], "/s");+ assert.equal(launch.args[2], "/c");+ // The whole line is wrapped: "<cmd> <args>"+ assert.ok(launch.args[3].startsWith('"'), "outer quote wraps the line");+ assert.match(launch.args[3], /npx\.cmd/i);+ assert.match(launch.args[3], /"pkg&whoami"/);+ assert.equal(launch.windowsHide, true);+ assert.equal(launch.windowsVerbatimArguments, true);+});++test("cmd quoting keeps metacharacters inside one argument", () => {+ assert.equal(quoteWindowsCmdArg("ok"), "ok");+ assert.equal(quoteWindowsCmdArg("pkg&whoami"), '"pkg&whoami"');+ assert.equal(quoteWindowsCmdArg('say "hi"'), '"say ""hi"""');+ // % is doubled so cmd.exe does not expand environment variables+ assert.equal(quoteWindowsCmdArg("hello%PATH%world"), '"hello%%PATH%%world"');+ assert.equal(quoteWindowsCmdArg("%FOO%"), '"%%FOO%%"');+});++test("Windows stderr strings stay intact and buffers decode without throwing", () => {+ const text = '"node" is not recognized as an internal or external command';+ assert.equal(decodeMcpStderr(text, "win32"), text);+ assert.equal(decodeMcpStderr(Buffer.from(text, "utf8"), "darwin"), text);+ const chinese = "找不到命令: npx";+ assert.equal(decodeMcpStderr(Buffer.from(chinese, "utf8"), "win32"), chinese);+ const gbkNode = Buffer.from([0x27, 0x6e, 0x6f, 0x64, 0x65, 0x27]);+ assert.match(decodeMcpStderr(gbkNode, "win32", true), /node/);+});++test("wrapCmdShim outer-quotes survive when .cmd path contains spaces", () => {+ const npxCmd = win.join("C:", "Program Files", "nodejs", "npx.cmd");+ const comspec = win.join("C:", "Windows", "System32", "cmd.exe");+ const launch = resolveMcpStdioLaunch({+ command: npxCmd,+ args: ["-y", "pkg&whoami", 'say "hi"'],+ env: { PATH: win.join("C:", "Windows", "System32") },+ platform: "win32",+ home: win.join("C:", "Users", "alice"),+ hostEnv: {+ PATH: win.dirname(npxCmd),+ ComSpec: comspec,+ PATHEXT: ".EXE;.CMD",+ },+ fs: winFs([npxCmd]),+ });+ assert.equal(launch.command, comspec);+ const line = launch.args[3];+ // The whole line is wrapped in one pair of outer quotes for /s /c.+ assert.ok(line.startsWith('"'), "starts with outer quote");+ assert.ok(line.endsWith('"'), "ends with outer quote");+ // After /s strips the outer quotes, the inner structure stays intact:+ // "<path with spaces>" -y "pkg&whoami" "say ""hi"""+ const inner = line.slice(1, -1);+ assert.match(inner, /^"[^"]*npx\.cmd"/i, "path is quoted");+ assert.match(inner, /"pkg&whoami"/, "metachar arg stays quoted");+ assert.match(inner, /"say ""hi"""/, "embedded quotes doubled");+});diff --git a/apps/desktop/test/plugin-child-env.test.mjs b/apps/desktop/test/plugin-child-env.test.mjsindex 131ed647f..3335a8c4b 100644--- a/apps/desktop/test/plugin-child-env.test.mjs+++ b/apps/desktop/test/plugin-child-env.test.mjs@@ -85,8 +85,10 @@ test("both plugin child environments are built from the one allowlist", () => {const mcpSrc = readFileSync(join(desktopRoot, "electron/main/plugin-mcp.ts"), "utf8");const envSrc = readFileSync(join(desktopRoot, "electron/main/child-process-env.ts"), "utf8");assert.match(runtimeSrc, /env: pluginChildEnv\(pluginId\)/);- assert.match(mcpSrc, /\.\.\.minimalChildEnv\(\)/);+ assert.match(mcpSrc, /minimalChildEnv\(\)/);+ assert.match(mcpSrc, /MCP_STDIO_HOST_ENV_KEYS/);// A second private allowlist is how the identity variables went missing once.+ // Windows extras (PATHEXT, FNM_DIR, …) live on the named list, not inline.assert.doesNotMatch(runtimeSrc, /pluginProcessEnv/);assert.doesNotMatch(mcpSrc, /for \(const key of \["SystemRoot"/);assert.doesNotMatch(runtimeSrc, /for \(const key of \["PATH"/);diff --git a/docs/adr/0038-plugin-mcp-bridge.md b/docs/adr/0038-plugin-mcp-bridge.mdindex 76287ebc3..9ef9f0dde 100644--- a/docs/adr/0038-plugin-mcp-bridge.md+++ b/docs/adr/0038-plugin-mcp-bridge.md@@ -53,10 +53,15 @@ differently.from that source is not evidence.6. Credentials resolve **only** from the plugin's own settings through`{ "setting": "<key>" }` (D018). A stdio child receives `PATH`, temp/locale- variables, `PI_PLUGIN_ID`, and the declared values — not the host- environment, which holds provider keys. `command` must be a bare PATH name or- stay inside the plugin directory; `url` may use `http` or `https`, with- non-loopback HTTP subject to ADR 0142 and the plugin network allowlist.+ and profile/toolchain variables (`HOME`, `USERPROFILE`, `PATHEXT`, `ComSpec`,+ `FNM_DIR`, …), `PI_PLUGIN_ID`, and the declared values — not the host+ environment, which holds provider keys. Unix PATH is the login-shell PATH+ (D600). Bare `npx`/`uvx` resolve to real binaries: official Node+ (`node.exe` + `npx-cli.js`) first, then fnm/nvm/Volta, then a Windows+ `.cmd` shim through `cmd.exe /d /s /c` with quoted literal args (D624,+ issue #789). `command` must be a bare PATH name or stay inside the plugin+ directory; `url` may use `http` or `https`, with non-loopback HTTP subject+ to ADR 0142 and the plugin network allowlist.## Consequences@@ -99,3 +104,11 @@ credentials out of the plugin's reach.Rejected. Risk drives host-core's confirmation flow. A value chosen by theinspected party cannot gate the inspection.++## Amendment: stdio launcher resolution++GUI launches inherit a PATH that may not include fnm/nvm/uv shims. Windows+`npx` from the official Node installer is `npx.cmd` (plus a Git-Bash `npx`+script), which `spawn({ shell: false })` cannot start. Resolution stays in+Electron main, arguments stay literal, and remaining `.cmd` files go through+`cmd.exe` rather than `shell: true`.diff --git a/docs/adr/0056-extension-activation-scope.md b/docs/adr/0056-extension-activation-scope.mdindex e3462de3c..c9c0f074a 100644--- a/docs/adr/0056-extension-activation-scope.md+++ b/docs/adr/0056-extension-activation-scope.md@@ -110,7 +110,9 @@ which registry served a call.`commandPolicy` is `trusted` and the child's cwd is the user's home directory:no plugin owns the server, so there is no plugin root to sandbox it into, and-the command the user typed is their own.+the command the user typed is their own. The editor offers `npx`, `uvx`, and+Custom; spawn-time resolution of those names is shared with plugin MCP (ADR+0038, D624).### 4. A pasted `mcpServers` block is the primary way to add onediff --git a/docs/plugin-development.md b/docs/plugin-development.mdindex a4898f214..b0bec9f94 100644--- a/docs/plugin-development.md+++ b/docs/plugin-development.md@@ -636,12 +636,13 @@ remote server requires `mcp.server.remote`:```A stdio command must be a bare command found on `PATH` or a plugin-relative-executable; absolute paths are rejected. Remote URLs may use HTTP or HTTPS, and-the host must be listed in `net.domains`; non-loopback HTTP is unencrypted, so-use it only on a trusted network. Setting references read only this plugin's-settings—the host environment and provider secrets are never forwarded. MCP-tools follow the same Agent-only policy and namespacing as hand-written plugin-tools.+executable; absolute paths are rejected. `npx` and `uvx` are resolved to the+real Node.js / uv binaries (PATH, official Node, fnm, nvm, Volta, default uv+install). Remote URLs may use HTTP or HTTPS, and the host must be listed in+`net.domains`; non-loopback HTTP is unencrypted, so use it only on a trusted+network. Setting references read only this plugin's settings—the host+environment and provider secrets are never forwarded. MCP tools follow the+same Agent-only policy and namespacing as hand-written plugin tools.### 6.10 Resident service and message busdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex ff28fcde4..967f94442 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -2166,6 +2166,24 @@ identify the platform validation still needed.- **Status**: Automated (`apps/desktop/test/user-login-path.test.mjs`,`apps/desktop/test/plugin-mcp.test.mjs`)+#### E2E-MCP-stdio-windows-npx: Official Node and fnm both start `npx` MCP (issue #789)++- **Preconditions**: Windows; Node is either the official `Program Files\nodejs`+ install (`node.exe` + `npx.cmd` + `npx-cli.js` on PATH) or fnm-managed and+ not on the GUI PATH.+- **Steps**: 1) Add Memory from the MCP market (`npx -y @modelcontextprotocol/server-memory`).+ 2) Test connection. 3) Repeat with a user-typed `npx` server.+- **Expected**: Official Node rewrites to `node.exe` + `npx-cli.js` and+ handshakes. fnm is discovered from `%LOCALAPPDATA%\fnm\aliases\default` when+ PATH has no node. Remaining `.cmd` shims start through `cmd.exe /d /s /c`+ with quoted literal args, never `shell: true`. A Git-Bash extensionless+ `npx` next to `npx.cmd` is not chosen. Missing binaries still report+ `command not found: npx`.+- **Specs linked**: ADR 0038, D624, `07-plugins/04-plugin-security.md`+- **Acceptance**: Quality+- **Milestone**: M6++- **Status**: Automated (`apps/desktop/test/mcp-stdio-launch.test.mjs`)+### Session Persistence#### E2E-020: Session survives restartdiff --git a/docs/spec/07-plugins/04-plugin-security.md b/docs/spec/07-plugins/04-plugin-security.mdindex dcc91511b..702dd09e5 100644--- a/docs/spec/07-plugins/04-plugin-security.md+++ b/docs/spec/07-plugins/04-plugin-security.md@@ -350,12 +350,12 @@ manifest did not name:- `transport: "stdio"` spawns a local executable (`mcp.server.local`). The`command` must be a bare PATH name or a plugin-relative path; absolute pathsare refused at validation time. The child gets a minimal environment — the- declared `env` entries plus one shared allowlist (`child-process-env.ts`):- `PATH`, `SystemRoot`, `windir`, `TEMP`, `TMP`, `TMPDIR`, `LANG`, `HOME`,- `USER`, `USERPROFILE`. The identity variables are there because the child is- third-party code that resolves `~` through `$HOME` rather than calling- `os.homedir()` (issue #717); provider keys and other host state still never- cross.+ declared `env` entries plus the shared allowlist (`child-process-env.ts`)+ and the extra profile/toolchain keys `npx`/`uvx` need (`PATHEXT`, `ComSpec`,+ `FNM_DIR`, …). Unix PATH is the login-shell PATH (D600). Bare `npx`/`uvx`+ resolve to real binaries; official Windows Node uses `node.exe` ++ `npx-cli.js`, and remaining `.cmd` shims start through `cmd.exe` with quoted+ literal args (D624). Provider keys and other host state still never cross.- `transport: "http"` reaches a remote endpoint (`mcp.server.remote`). The `url`may use `http` or `https`; non-loopback HTTP is unencrypted and should only beused on a trusted network. Plugin endpoints must also be covered bydiff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 62fb7b250..1983106c5 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -1102,9 +1102,11 @@ section mirrors only marketplace/catalog items still blocking nothing.is not trustworthy.- `env` and `headers` resolve only from the plugin's own settings via`{ "setting": "<key>" }`; the host environment is never passed through (D018).- A stdio child gets `PATH`, temp/locale vars, and the declared values — nothing- else. `command` must be a bare PATH name or plugin-relative; `url` must be- `https` unless the host is loopback.+ A stdio child gets `PATH`, temp/locale, profile/toolchain keys (`HOME`,+ `USERPROFILE`, `PATHEXT`, `ComSpec`, `FNM_DIR`, …), and the declared values —+ not provider secrets. Bare `npx`/`uvx` resolve to real binaries (official+ Node, fnm, nvm, Volta). `command` must be a bare PATH name or plugin-relative;+ `url` must be `https` unless the host is loopback.- Both transports ship rather than stdio alone: a hosted MCP endpoint is commonenough that stdio-only would have pushed plugins to wrap it in a local shim,which is strictly worse — an extra process and an unreviewable proxy.@@ -7020,3 +7022,18 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.- The runtime remains inline-only: no background summary, user setting,protocol change, or transcript/storage rewrite. See ADR 0064,`03-runtime/02-agent-runtime.md`, and E2E-164.++## 2026-09-24 — Windows stdio MCP resolves official Node and fnm npx (D624, issue #789)++- Amend D176 / D600 / ADR 0038. D600 probes the login-shell PATH on Unix and+ explicitly keeps Windows on the inherited PATH. That does not start+ `npx.cmd`: `spawn({ shell: false })` returns ENOENT for `npx` and EINVAL+ for the `.cmd` shim, even when official Node is on PATH (issue #789).+- Electron main now resolves bare `npx`/`npm`/`node`/`uvx` before spawn:+ PATH `node.exe` from an official install wins, then fnm/nvm-windows/Volta.+ When `npx-cli.js` sits next to `node.exe`, the child is `node` plus that+ script — no cmd.exe. Remaining `.cmd` files go through+ `cmd.exe /d /s /c` with quoted literal arguments. PATHEXT is searched+ before an extensionless Git-Bash `npx` shim.+- Secrets still do not cross (D018). Command names stay bare. See ADR 0038+ and `07-plugins/04-plugin-security.md`.diff --git a/docs/zh-CN/plugin-development.md b/docs/zh-CN/plugin-development.mdindex fdd5e2da6..abb8e6578 100644--- a/docs/zh-CN/plugin-development.md+++ b/docs/zh-CN/plugin-development.md@@ -550,11 +550,12 @@ MCP 服务器是声明性的。本地服务器需要 `mcp.server.local`;一个}```-stdio 命令必须是 `PATH` 上的裸命令或与插件相关的命令-可执行文件;绝对路径被拒绝。远程 URL 可以使用 HTTP 或 HTTPS,并且主机必须-列在 `net.domains` 中;非回环 HTTP 不加密,因此只应在可信网络中使用。设置-引用仅读取该插件的设置——主机环境和提供商秘密永远不会被转发。MCP 工具-遵循与手写插件工具相同的仅代理策略和命名空间。+stdio 命令必须是 `PATH` 上的裸命令或插件相对路径的可执行文件;绝对路径会被拒绝。+`npx` 和 `uvx` 会解析到真实的 Node.js / uv(PATH、官方 Node 安装、fnm、nvm、Volta、+默认 uv 安装位置)。远程 URL 可以使用 HTTP 或 HTTPS,并且主机必须列在+`net.domains` 中;非回环 HTTP 不加密,因此只应在可信网络中使用。设置引用仅读取+该插件的设置——主机环境和提供商密钥永远不会被转发。MCP 工具遵循与手写插件工具+相同的仅 Agent 策略和命名空间。### 6.9 常驻服务和消息总线diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 88ef0b0a0..26df046d0 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -1015,6 +1015,22 @@ task-candidate E2E 从请求工作树运行,但使用主工作区已经准备- **里程碑**:M5- **状态**:自动化(host-core 单元测试:登录路径探测 + 子路径注入)+#### E2E-MCP-stdio-windows-npx:官方 Node 与 fnm 都能启动 `npx` MCP(issue #789)++- **先决条件**:Windows;Node 要么是官方 `Program Files\nodejs` 安装+ (PATH 上有 `node.exe`、`npx.cmd`、`npx-cli.js`),要么由 fnm 管理且不在 GUI PATH 中。+- **步骤**:1) 从 MCP 市场添加 Memory(`npx -y @modelcontextprotocol/server-memory`)。+ 2) 测试连接。3) 再用用户手写的 `npx` 服务器重复一次。+- **预期**:官方 Node 改写为 `node.exe` + `npx-cli.js` 并完成握手。PATH 没有+ node 时从 `%LOCALAPPDATA%\fnm\aliases\default` 发现 fnm。其余 `.cmd` 经+ `cmd.exe /d /s /c` 启动,参数加引号保持字面量,不用 `shell: true`。+ 与 `npx.cmd` 同目录的 Git-Bash 无扩展名 `npx` 不会被选中。真正缺失时仍报告+ `command not found: npx`。+- **链接规格**:ADR 0038、D624、`07-plugins/04-plugin-security.md`+- **接受**:质量+- **里程碑**:M6++- **状态**:自动化(`apps/desktop/test/mcp-stdio-launch.test.mjs`)+### 会话持续性#### E2E-020:会话在重新启动后仍然存在diff --git a/docs/zh-CN/spec/07-plugins/04-plugin-security.md b/docs/zh-CN/spec/07-plugins/04-plugin-security.mdindex 1486cf0c6..eb7285980 100644--- a/docs/zh-CN/spec/07-plugins/04-plugin-security.md+++ b/docs/zh-CN/spec/07-plugins/04-plugin-security.md@@ -269,13 +269,13 @@ MCP 服务器是 `net.fetch` 旁边的第二个出口路径,因此它是声明并且是可审查的而不是编程的——插件无法打开连接清单未命名:-- `transport: "stdio"` 生成本地可执行文件 (`mcp.server.local`)。的- `command` 必须是裸路径名称或插件相对路径;绝对路径- 在验证时被拒绝。子进程拿到的是最小环境——声明的 `env` 条目,加上共享- 白名单(`child-process-env.ts`):`PATH`、`SystemRoot`、`windir`、`TEMP`、- `TMP`、`TMPDIR`、`LANG`、`HOME`、`USER`、`USERPROFILE`。身份变量要透传,- 是因为子进程是第三方代码,用 `$HOME` 解析 `~` 而不是调用 `os.homedir()`- (issue #717);provider key 和其它宿主状态仍然不会穿越。+- `transport: "stdio"` 生成本地可执行文件 (`mcp.server.local`)。+ `command` 必须是裸 PATH 名称或插件相对路径;绝对路径在验证时被拒绝。+ 子进程拿到最小环境——声明的 `env` 条目、共享白名单(`child-process-env.ts`),+ 以及 `npx`/`uvx` 需要的工具链键(`PATHEXT`、`ComSpec`、`FNM_DIR` 等)。+ Unix 上 PATH 是 login-shell PATH(D600)。裸 `npx`/`uvx` 会解析到真实二进制:+ 官方 Windows Node 走 `node.exe` + `npx-cli.js`,其余 `.cmd` 经 `cmd.exe`+ 以引号字面参数启动(D624)。provider key 和其它宿主状态仍然不会穿越。- `transport: "http"` 到达远程端点 (`mcp.server.remote`)。`url` 可以使用`http` 或 `https`;非回环 HTTP 不加密,只应在可信网络中使用。插件端点还必须被 `manifest.net.domains` 覆盖。工具参数会离开机器,这就是为什么权限diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.mdindex a4bd5f258..6938cca4a 100644--- a/docs/zh-CN/spec/08-meta/decisions-log.md+++ b/docs/zh-CN/spec/08-meta/decisions-log.md@@ -976,9 +976,10 @@ project/group 层,而主要操作和页脚标识仍保留在不值得信赖。- `env` 和 `headers` 仅通过插件自己的设置进行解析`{ "setting": "<key>" }`;主机环境永远不会被传递(D018)。- stdio 子进程获取 `PATH`、temp/locale 变量和声明的值 — 无- 否则。 `command` 必须是裸路径名称或与插件相关的名称; `url` 必须是- `https` 除非主机环回。+ stdio 子进程获取 `PATH`、temp/locale、工具链键(`HOME`、`USERPROFILE`、+ `PATHEXT`、`ComSpec`、`FNM_DIR` 等)以及声明的值——不含 provider 密钥。+ 裸 `npx`/`uvx` 会解析到真实二进制(官方 Node、fnm、nvm、Volta)。+ `command` 必须是裸 PATH 名称或插件相对路径;`url` 必须是 `https`,除非主机环回。- 两种传输方式而不是单独的 stdio:托管 MCP 端点很常见足以让 stdio-only 推送插件将其包装在本地垫片中,这更糟糕——一个额外的过程和一个无法审查的代理。@@ -4959,3 +4960,16 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编只查自身目录。后缀本身不赋予推理能力:未命中的自由格式 ID 仍是未知通用模型,已发布能力和显式绑定覆盖沿用既有优先级。见`03-runtime/13-model-catalog-and-selection.md` §11.2。++## 2026-09-24 —— Windows stdio MCP 解析官方 Node 与 fnm 的 npx(D624,issue #789)++- 修订 D176 / D600 / ADR 0038。D600 在 Unix 探测 login-shell PATH,Windows 仍用+ 进程继承的 PATH。这启动不了 `npx.cmd`:`spawn({ shell: false })` 对 `npx`+ 返回 ENOENT,对 `.cmd` 返回 EINVAL,即使官方 Node 已在 PATH 里(issue #789)。+- Electron main 在 spawn 前解析裸 `npx`/`npm`/`node`/`uvx`:PATH 上的官方+ `node.exe` 优先,然后是 fnm / nvm-windows / Volta。若 `npx-cli.js` 与+ `node.exe` 同目录,子进程直接跑 `node` 加该脚本,不经过 cmd.exe。其余+ `.cmd` 走 `cmd.exe /d /s /c`,参数加引号保持字面量。PATHEXT 优先于无扩展名+ 的 Git-Bash `npx` 脚本。+- 密钥仍不穿越(D018)。命令名保持裸名。见 ADR 0038 与+ `07-plugins/04-plugin-security.md`。diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 02791be5e..2bde395f8 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -2184,6 +2184,11 @@ sklm: {"idHint": "Präfixe seiner Werkzeugnamen; kann später nicht mehr geändert werden.","command": "Befehl","commandHint": "Eine ausführbare Datei in Ihrem PATH oder ein absoluter Pfad.",+ "commandHintNpx": "Verwendet Node.js aus PATH, der offiziellen Installation, fnm, nvm oder Volta.",+ "commandHintUvx": "Verwendet uv aus PATH oder dem Standard-Installationsort.",+ "launcherCustom": "Benutzerdefiniert",+ "commandPath": "Programmdatei",+ "commandPlaceholder": "npx oder ein absoluter Pfad","args": "Argumente","argsHint": "Eine Zeile, wie in der README-Datei abgedruckt. Zitate werden respektiert.","env": "Umgebungsvariablen",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex a191ed6fd..ebe492c3b 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -2222,6 +2222,11 @@ importConfirm: "Imported extensions run inside the agent process with the same aidHint: "Prefixes its tool names; can't change later.",command: "Command",commandHint: "An executable on your PATH, or an absolute path.",+ commandHintNpx: "Uses Node.js from PATH, fnm, nvm, or Volta. Official Node installs work the same way.",+ commandHintUvx: "Uses uv from PATH or the default uv install location.",+ launcherCustom: "Custom",+ commandPath: "Executable",+ commandPlaceholder: "npx or an absolute path",args: "Arguments",argsHint: "One line, as printed in the README. Quotes are respected.",env: "Environment variables",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex dcf71d416..133ddba6c 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -2184,6 +2184,11 @@ sklm: {"idHint": "Prefija los nombres de sus herramientas; No puedo cambiar más tarde.","command": "Comando","commandHint": "Un ejecutable en su RUTA, o una ruta absoluta.",+ "commandHintNpx": "Usa Node.js de PATH, la instalación oficial, fnm, nvm o Volta.",+ "commandHintUvx": "Usa uv de PATH o de la ubicación de instalación predeterminada.",+ "launcherCustom": "Personalizado",+ "commandPath": "Ejecutable",+ "commandPlaceholder": "npx o una ruta absoluta","args": "Argumentos","argsHint": "Una línea, tal como está impresa en el archivo README. Se respetan las cotizaciones.","env": "Variables de entorno",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 8a8a4d2f2..9d8820f7f 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -2184,6 +2184,11 @@ sklm: {"idHint": "Préfixe ses noms d'outils ; je ne peux pas changer plus tard.","command": "Commande","commandHint": "Un exécutable sur votre PATH, ou un chemin absolu.",+ "commandHintNpx": "Utilise Node.js depuis PATH, l'installation officielle, fnm, nvm ou Volta.",+ "commandHintUvx": "Utilise uv depuis PATH ou l'emplacement d'installation par défaut.",+ "launcherCustom": "Personnalisé",+ "commandPath": "Exécutable",+ "commandPlaceholder": "npx ou un chemin absolu","args": "Arguments","argsHint": "Une ligne, telle qu'imprimée dans le README. Les citations sont respectées.","env": "Variables d'environnement",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 834b9cfca..b327a28cd 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -2218,6 +2218,11 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이idHint: "도구 이름 앞에 붙으며 나중에 변경할 수 없습니다.",command: "명령",commandHint: "PATH의 실행 파일 또는 절대 경로입니다.",+ commandHintNpx: "PATH, 공식 Node 설치, fnm, nvm, Volta의 Node.js를 사용합니다.",+ commandHintUvx: "PATH 또는 기본 설치 위치의 uv를 사용합니다.",+ launcherCustom: "사용자 지정",+ commandPath: "실행 파일",+ commandPlaceholder: "npx 또는 절대 경로",args: "인수",argsHint: "README에 표시된 대로 한 줄로 입력하세요. 따옴표는 유지됩니다.",env: "환경 변수",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 525c9f19c..b9838e708 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -2133,6 +2133,11 @@ export const ptBR = {idHint: "É usado como prefixo nos nomes das ferramentas e não pode ser alterado depois.",command: "Comando",commandHint: "Executável que será iniciado. Use um caminho absoluto se ele não estiver no PATH.",+ commandHintNpx: "Usa o Node.js do PATH, da instalação oficial, fnm, nvm ou Volta.",+ commandHintUvx: "Usa o uv do PATH ou do local de instalação padrão.",+ launcherCustom: "Personalizado",+ commandPath: "Executável",+ commandPlaceholder: "npx ou um caminho absoluto",args: "Argumentos",argsHint: "Argumentos passados ao comando, um por linha ou separados por espaço.",env: "Variáveis de ambiente",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 056bda4dd..a21ef8af2 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -2208,6 +2208,11 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araçidHint: "Araç adlarının önekidir; sonra değiştirilemez.",command: "Komut",commandHint: "PATH üzerindeki bir yürütülebilir veya mutlak bir yol.",+ commandHintNpx: "PATH, resmi Node kurulumu, fnm, nvm veya Volta üzerindeki Node.js’i kullanır.",+ commandHintUvx: "PATH veya varsayılan kurulum konumundaki uv’yi kullanır.",+ launcherCustom: "Özel",+ commandPath: "Yürütülebilir",+ commandPlaceholder: "npx veya mutlak bir yol",args: "Argümanlar",argsHint: "README’de yazıldığı gibi tek satır. Tırnaklara uyulur.",env: "Ortam değişkenleri",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex a607e5f2a..91742911a 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -2172,6 +2172,11 @@ sklm: {idHint: "作为工具名前缀,保存后不能修改。",command: "命令",commandHint: "PATH 中的可执行文件,或者绝对路径。",+ commandHintNpx: "自动查找本机 Node.js,包括 PATH、官方安装、fnm、nvm。",+ commandHintUvx: "自动查找本机的 uv。",+ launcherCustom: "自定义",+ commandPath: "可执行文件",+ commandPlaceholder: "npx 或绝对路径",args: "参数",argsHint: "写成一行,和 README 里一样。引号会被识别。",env: "环境变量",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex a04833641..35baecc21 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -2171,6 +2171,11 @@ sklm: {idHint: "作為工具名字首,儲存後不能修改。",command: "命令",commandHint: "PATH 中的執行檔,或者絕對路徑。",+ commandHintNpx: "自動尋找本機 Node.js,包括 PATH、官方安裝、fnm、nvm。",+ commandHintUvx: "自動尋找本機的 uv。",+ launcherCustom: "自訂",+ commandPath: "執行檔",+ commandPlaceholder: "npx 或絕對路徑",args: "引數",argsHint: "寫成一行,和 README 裡一樣。引號會被識別。",env: "環境變數",