
MCP
配置
建议直接命名为 mcp.json 并放在对应的隐藏文件夹(如 .vscode 或 .cursor)中
格式
json
{
"mcpServers": {
"database-tool": {
"command": "node",
"args": [
"./build/index.js"
],
"cwd": "C:\\Users\\MyUser\\Projects\\db-mcp",
"env": {
"DB_HOST": "localhost",
"API_KEY": "secret_123"
},
"timeout": 10000,
"disabled": false
}
}
}- disabled 是否启用这个mcp服务
- timeout 超时时间 一般为默认30s
- cwd 需要进入到哪个目录下执行命令
跨平台兼容的最佳实践
为了让你不用维护两份配置文件(一份给 Mac,一份给 Windows),我建议使用 npx 或者 绝对路径,并统一使用 正斜杠。
方案 A:使用 npx (推荐)
如果你的项目是本地开发的,或者使用了包管理器,用 npx 可以自动处理很多环境差异。
json
{
"mcpServers": {
"my-server": {
"command": "npx",
"args": [
"-y",
"ts-node",
"build/index.js",
"--port", "3000"
],
"cwd": "C:/Users/YourName/Projects/my-mcp-project",
"env": {
"API_KEY": "secret_123",
"DEBUG": "true"
}
}
}
}注意:这里 cwd 使用了正斜杠 /,这在 Windows 的 Node.js 环境中通常是兼容的,能避免转义烦恼。
方案 B:针对 Windows 的特化配置
如果你必须在 Windows 上直接运行 node,配置应该长这样:
json
{
"mcpServers": {
"my-server": {
"command": "node",
"args": [
"C:/full/path/to/your/project/build/index.js",
"--port", "3000"
],
"env": {
"API_KEY": "secret_123"
}
}
}
}程序获取
当 MCP 服务启动时,它本质上是一个普通的程序(Node.js, Python 等)。除了 args 和 env,它还能拿到以下信息:
如果你是 Node.js (index.js):
js
// 1. 获取 args (命令行参数)
// process.argv 包含所有参数,通常是 [node路径, 脚本路径, ...剩余参数]
const args = process.argv.slice(2);
console.log(args); // 输出: ['--port', '3000']
// 2. 获取 env (环境变量)
const apiKey = process.env.API_KEY;
const debug = process.env.DEBUG;
console.log(apiKey); // 输出: secret_123如果你是 Python (main.py):
python
import os
import sys
# 1. 获取 args
args = sys.argv[1:]
print(args) # 输出: ['--port', '3000']
# 2. 获取 env
api_key = os.getenv("API_KEY")
print(api_key) # 输出: secret_123如果你是 Go (main.go):
go
package main
import (
"fmt"
"os"
)
func main() {
// 1. 获取 args (命令行参数)
// os.Args 是一个字符串切片,包含所有参数
// 索引 0 是程序本身的路径,所以我们需要从索引 1 开始截取
args := os.Args[1:]
fmt.Printf("命令行参数: %v\n", args)
// 如果配置是 ["build/index.js", "--port", "3000"]
// 输出: [build/index.js --port 3000]
// 如果你只想获取特定的标志位(如 --port),通常需要解析
// 这里演示简单的遍历查找
var port string
for i, arg := range args {
if arg == "--port" && i+1 < len(args) {
port = args[i+1]
break
}
}
fmt.Printf("解析到的端口: %s\n", port) // 输出: 3000
// 2. 获取 env (环境变量)
// os.Getenv("KEY") 用于获取指定名称的环境变量值
// 如果变量不存在,它会返回空字符串 ""
apiKey := os.Getenv("API_KEY")
debug := os.Getenv("DEBUG")
fmt.Printf("API Key: %s\n", apiKey) // 输出: secret_123
fmt.Printf("Debug Mode: %s\n", debug) // 输出: true
}
