模型上下文协议(MCP,Model Context Protocol)是 Anthropic 开源的 AI 工具连接标准。通过 MCP,Claude Code 可以直接访问数据库、调用 API、操作外部服务——而不需要你手动复制粘贴数据。
MCP 是什么?
MCP 是一个开放标准,让 AI 助手能够安全地访问和操作外部数据源及工具。就像 USB 插口一样——任何符合 MCP 规范的服务,都可以被任何支持 MCP 的 AI 工具直接使用。
MCP 服务器:提供数据和操作的服务(你的数据库、GitHub、Google Drive 等)
MCP 客户端:使用这些服务的 AI ���具(Claude Code、claude.ai 等)
配置 MCP 服务器
在 Claude Code 中添加 MCP 服务器
bash
# 交互式添加
claude mcp add
# 或直接指定
claude mcp add --name github --command "npx @modelcontextprotocol/server-github"配置文件方式(.mcp.json)
在项目根目录创建 .mcp.json:
json
{
"mcpServers": {
"github": {
"type": "stdio",
"command": "npx",
"args": ["@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "your_token"
}
},
"postgres": {
"type": "stdio",
"command": "npx",
"args": ["@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"]
},
"pipedream": {
"type": "http",
"url": "https://mcp.pipedream.net/v2"
}
}
}常用 MCP 服务器
文件系统
json
{
"filesystem": {
"type": "stdio",
"command": "npx",
"args": ["@modelcontextprotocol/server-filesystem", "/path/to/allowed/dir"]
}
}让 Claude Code 访问指定目录的文件,适合隔离访问特定项目目录。
GitHub
json
{
"github": {
"type": "stdio",
"command": "npx",
"args": ["@modelcontextprotocol/server-github"],
"env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_..." }
}
}让 Claude Code 直接操作 GitHub:读取 Issues、创建 PR、查看代码。
PostgreSQL/MySQL
json
{
"postgres": {
"type": "stdio",
"command": "npx",
"args": ["@modelcontextprotocol/server-postgres", "postgresql://user:pass@localhost/db"]
}
}让 Claude Code 查询数据库、分析数据结构。
Brave Search(网络搜索)
json
{
"brave-search": {
"type": "stdio",
"command": "npx",
"args": ["@modelcontextprotocol/server-brave-search"],
"env": { "BRAVE_API_KEY": "BSA..." }
}
}Slack
json
{
"slack": {
"type": "stdio",
"command": "npx",
"args": ["@modelcontextprotocol/server-slack"],
"env": { "SLACK_BOT_TOKEN": "xoxb-..." }
}
}实战场景
场景 1:结合数据库分析业务问题
bash
# 配置好 postgres MCP 后
claude
> 查询 orders 表,分析过去 30 天的销售趋势,找出下单量最高的时间段和最受欢迎的商品类别Claude Code 直接查询数据库,生成分析报告。
场景 2:GitHub 自动化
bash
> 读取 #234 Issue 的内容,在 feature/fix-234 分支上实现需求,然后创建 PR 并关联这个 IssueClaude Code 通过 GitHub MCP 完成从读 Issue 到创建 PR 的完整流程。
场景 3:邮件处理(结合 Pipedream)
bash
> 检查我的邮件,找出过去一周未回复的客户邮件,为每封写一个草稿回复Pipedream MCP 连接 Gmail,Claude Code 读取邮件并生成草稿。
管理 MCP 服务器
bash
claude mcp list # 查看已配置的服务器
claude mcp add # 添加服务器
claude mcp remove name # 删除服务器
claude mcp get name # 查看单个配置MCP 服务器类型
| 类型 | 说明 | 适用场景 |
|---|---|---|
stdio | 本地进程,通过标准 I/O 通信 | 本地工具、CLI |
http | 远程 HTTP 服务 | 云服务、SaaS API |
sse | Server-Sent Events(流式) | 实时数据 |
安全注意事项
- MCP 服务器以当前用户权限运行,注意访问控制
- 数据库连接字符串包含密码,不要提交到 git
- 使用
.mcp.json.local(加入.gitignore)存储含密钥的配置 - HTTP MCP 服务器的 URL 可能日志中可见,注意不要包含敏感信息
发现更多 MCP 服务器
- 官方仓库:github.com/modelcontextprotocol/servers
- 社区:mcp.so(第三方 MCP 服务器目录)
- Pipedream:连接 300+ 服务的一站式 MCP 服务器
原文整理自:Claude Code MCP 文档 | 来源:Anthropic 官方文档