本地 IDE 里配好的 MCP server,搬到 Spring Boot 就起不来,报
exec: "npx": executable file not found in $PATH。根因是子进程的 PATH 不等于你交互式 shell 的 PATH,Node 的安装目录没进去;Windows 上npx其实是npx.cmd批处理,ProcessBuilder不能直接执行,得用cmd /c包一层。
Issue & Env(案发现场与环境)
- 业务场景:用 stdio 方式接 MCP server,比如官方的 filesystem。在本地 IDE(Qoder、Claude Desktop 这类)里配好能用,搬到 Spring Boot 应用里,启动就失败。
- 环境:Spring AI 1.1.x,
spring-ai-starter-mcp-client(或...-webflux版),stdio transport。Node.js 没装,或者装了但不在 JVM 进程的 PATH 里。
StackTrace(堆栈日志)
最常见的一条报错原文:
java.lang.RuntimeException: failed to start command: exec: "npx": executable file not found in $PATH
Windows 上换了个说法:
'npx.cmd' is not recognized as an internal or external command, operable program or batch file.
这两条文案来自 MCP 客户端与宿主,Qoder 和阿里云 Lingma 的 FAQ 都原样收录了。如果失败是从 Java 侧 ProcessBuilder 冒出来的,形态通常是这样(这是 ProcessBuilder 的通用输出,不是 Spring AI 独有):
java.io.IOException: Cannot run program "npx": error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
Reproduce(复现代码)
配置里 command 直接写 npx:
spring:
ai:
mcp:
client:
stdio:
connections:
filesystem:
command: npx
args:
- -y
- "@modelcontextprotocol/server-filesystem"
- /Users/username/Desktop
同一串命令在终端手敲能跑,应用一启动就失败。差别不在命令,在“谁去执行它”。
Root Cause(根因分析)
PATH 不是同一份
子进程继承的是启动它的 JVM 进程的 PATH,跟你登录后交互式 shell 的 PATH 是两回事。终端启动 shell 时会读 .zshrc、.bash_profile,nvm、Homebrew 这些工具往 PATH 里加目录,就在这一步。IDE 的 Run 面板、系统服务、容器里的 JVM 往往不读这些 rc 文件,拿到的 PATH 更精简,自然找不到 npx。
直接 exec,没有 shell 兜底
StdioClientTransport 用 ProcessBuilder 直接拉起 command 指定的可执行文件,中间没有 shell。命令不会被 shell 再展开一遍,rc 文件里追加的 PATH 也不生效。终端能跑、IDE 能跑,不代表 Java 进程能跑。
Windows:npx 不是可执行文件
Windows 上 npx、npm、node 都是批处理(.cmd)。ProcessBuilder 只能执行原生 .exe,或者交给 cmd.exe 执行的系统命令,批处理它直接执行不了。Spring AI 官方文档专门写了这一条:Windows 上要用 cmd.exe /c 把批处理命令包起来。
The Fix(解决方案)
1. command 换成绝对路径
最稳的是写绝对路径,绕开 PATH 查找:
spring:
ai:
mcp:
client:
stdio:
connections:
filesystem:
command: /usr/local/bin/npx
args:
- -y
- "@modelcontextprotocol/server-filesystem"
- /Users/username/Desktop
先用 which npx(Windows 用 where npx)拿到真实路径再填。用 nvm 的话路径里带 Node 版本号,升级 Node 后要跟着改。
2. Windows 用 cmd /c 包一层
spring:
ai:
mcp:
client:
stdio:
connections:
filesystem:
command: cmd
args:
- /c
- npx
- -y
- "@modelcontextprotocol/server-filesystem"
- C:\\Users\\username\\Desktop
官方文档的示例用 cmd.exe,和 cmd 等价。
3. 运行时先备好
- Node.js 18 及以上(自带 npm 8 及以上)。版本低于这个线,容易出各种问题。
- Python 系的 MCP server 走
uv/uvx,也要先装好。
4. 配好先用命令行验证
把 command 和 args 拼成一行,在终端原样跑一遍:
npx -y @modelcontextprotocol/server-filesystem /Users/username/Desktop
能起来,说明命令本身没问题,剩下就是 Java 进程的 PATH 和 Windows 批处理两件事。
References(参考来源)
- MCP Client Boot Starter(含 Windows STDIO 配置)— Spring AI 官方文档spring-docs
- MCP Common Issues:npx/uvx 环境缺失 — Qoder 文档qoder-docs
- MCP 常见问题说明 — 阿里云 Lingma FAQaliyun-docs
