Claude Code CLI
MCP Servers
在 Claude Code 中添加和配置 MCP(Model Context Protocol)服务器
什么是 MCP?
Model Context Protocol (MCP) 是一个开放协议,允许 AI 助手连接外部工具和数据源。Claude Code 支持作为 MCP 客户端,连接到各种 MCP 服务器。
添加 MCP 服务器
使用 CLI 命令
# 添加 stdio 传输的 MCP 服务器
claude mcp add my-server -- node /path/to/server.js
# 添加带参数的服务器
claude mcp add my-db-server -- npx @modelcontextprotocol/server-postgres postgresql://localhost/mydb
# 添加 HTTP 传输的 MCP 服务器
claude mcp add --transport http my-remote-server https://mcp.example.com
# 列出已配置的服务器
claude mcp list
# 移除服务器
claude mcp remove my-server作用域
# 添加到用户级(所有项目可用)
claude mcp add --scope user my-server -- node server.js
# 添加到项目级(仅当前项目)
claude mcp add --scope project my-server -- node server.js直接编辑配置
在 ~/.claude/settings.json 或 .claude/settings.json 中:
{
"mcpServers": {
"filesystem": {
"type": "stdio",
"command": "npx",
"args": [
"@modelcontextprotocol/server-filesystem",
"/path/to/allowed/dir"
]
},
"github": {
"type": "stdio",
"command": "npx",
"args": ["@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "ghp_xxx"
}
},
"remote-api": {
"type": "http",
"url": "https://mcp.example.com"
}
}
}传输类型
stdio(标准输入输出)
最常用的方式,MCP 服务器作为子进程运行:
{
"mcpServers": {
"my-server": {
"type": "stdio",
"command": "node",
"args": ["server.js"],
"cwd": "/path/to/server",
"env": {
"API_KEY": "xxx"
}
}
}
}HTTP(远程服务器)
连接远程 MCP 服务器:
{
"mcpServers": {
"remote": {
"type": "http",
"url": "https://mcp.example.com"
}
}
}常用 MCP 服务器
| 服务器 | 包名 | 功能 |
|---|---|---|
| 文件系统 | @modelcontextprotocol/server-filesystem | 文件读写 |
| GitHub | @modelcontextprotocol/server-github | Issues、PR 管理 |
| PostgreSQL | @modelcontextprotocol/server-postgres | 数据库查询 |
| Brave Search | @modelcontextprotocol/server-brave-search | 网络搜索 |
| Puppeteer | @modelcontextprotocol/server-puppeteer | 浏览器自动化 |
添加示例
GitHub 服务器
# 设置 GitHub Token
export GITHUB_TOKEN="ghp_your_token"
# 添加 GitHub MCP 服务器
claude mcp add github -- npx @modelcontextprotocol/server-github
# 现在可以让 Claude 操作 GitHub
# "列出我的 PR"
# "创建一个 Issue"数据库服务器
claude mcp add postgres -- npx @modelcontextprotocol/server-postgres \
"postgresql://user:pass@localhost:5432/mydb"自定义服务器
# 如果你有自己的 MCP 服务器
claude mcp add my-tools -- node /path/to/my-mcp-server/index.js调试
# 检查 MCP 服务器状态
claude mcp list
# 查看服务器输出
# MCP 服务器的 stderr 会显示在 Claude Code 中最佳实践
- 环境变量:敏感信息通过
env字段传递,不要硬编码 - 作用域选择:通用服务器用
user级,项目特定用project级 - 版本固定:生产环境中固定 MCP 服务器版本
- 权限控制:只添加必要的 MCP 服务器
- 本地优先:优先使用 stdio 传输,减少网络依赖