Mcp配置如下:
json
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/Users/username/Desktop",
"/Users/username/Downloads"
]
}
}
}
报错如下:
bash
[info] [filesystem] Initializing server...
[error] [filesystem] spawn npx ENOENT
[error] [filesystem] spawn npx ENOENT
[info] [filesystem] Server transport closed
[info] [filesystem] Client transport closed
[info] [filesystem] Server transport closed unexpectedly, this is likely due to the process exiting early. If you are developing this MCP server you can add output to stderr (i.e. `console.error('...')` in JavaScript, `print('...', file=sys.stderr)` in python) and it will appear in this log.
[error] [filesystem] Server disconnected. For troubleshooting guidance, please visit our [debugging documentation](https://modelcontextprotocol.io/docs/tools/debugging)
原因:
使用 NVM(Node 版本管理器)时,MCP 服务器的标准安装和使用说明不起作用。应用程序会尝试使用错误的 Node,从而导致失败。
解决方法一:
- 避免npx,全局安装包。
- 对 Node 可执行文件和服务器脚本使用绝对路径。
举例:
json
{
"mcpServers": {
"filesystem": {
"command": "/Users/username/.nvm/versions/node/v22.17.1/bin/node",
"args": [
"/Users/username/.nvm/versions/node/v22.17.1/bin/mcp-server-filesystem",
"/Users/username/Desktop"
]
}
}
}
解决方法二:
方法一是最简单最直接的方法,但是不够灵活,一旦nvm更新了node版本,可能就会出现报错的情况; 我们可以写一个脚本,来自动选择最新的node版本:
步骤1: 制作 /usr/local/bin/latest-npx-for-claude
bash
#!/usr/bin/env bash
NODE_VERSIONS_DIR="$HOME/.nvm/versions/node"
LATEST_NODE_VERSION=$(ls -v "$NODE_VERSIONS_DIR" | grep "^v" | sort -V | tail -n 1)
export PATH="$NODE_VERSIONS_DIR/$LATEST_NODE_VERSION/bin:$PATH"
exec npx "$@"
这个脚本的主要作用是:
- 找到通过 nvm 安装的最新版本的 Node.js。
- 将该版本的 bin 目录添加到 PATH 的最前面,确保使用最新版本的 Node.js。
- 执行 npx 并传递所有原始参数。 使用场景
- 如果你经常使用 npx 但希望始终使用最新安装的 Node.js 版本,这个脚本可以确保这一点。
- 可以把这个脚本保存为一个可执行文件(例如 npx-latest),然后通过 ./npx-latest 来运行,这样就会用最新的 Node.js 版本执行 npx 。 注意事项
- 脚本假设 nvm 的 Node.js 版本安装在 ~/.nvm/versions/node 目录下。如果 nvm 的配置不同,可能需要调整路径。
- 如果没有安装任何 Node.js 版本,LATEST_NODE_VERSION 可能为空,导致 PATH 设置出错。可以添加错误处理来避免这种情况。
步骤2: latest-npx-for-claude授予执行权限
bash
chmod +x /usr/local/bin/npx-for-claude
步骤3: command替换MCP 服务器配置
json
{
"mcpServers": {
"filesystem": {
"command": "npx-for-claude",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/path/to/dir"
]
}
}
}