Codex CLI-06-MCP集成-扩展AI能力的正确姿势
·
目录
🚀 Codex CLI MCP 集成:扩展 AI 能力的正确姿势
📅 更新于 2026年6月 | ✍️ 原创文章,转载请注明出处
本系列共12篇,本文是第6篇
1. 什么是 MCP
📖 MCP 定义
MCP (Model Context Protocol) 是 Anthropic 提出的一个开放协议,用于标准化 AI 助手与外部工具/数据源的通信方式。
简单说:MCP 让 AI 能调用外部工具和访问外部数据。
🔧 核心能力
| 能力 | 说明 | 示例 |
|---|---|---|
| 工具调用 | AI 可以调用外部函数 | 查询数据库、发送邮件 |
| 资源访问 | AI 可以读取外部数据 | 读取文件、访问 API |
| 提示模板 | 预定义的提示词 | 代码审查模板 |
| 采样 | 从 AI 获取补全 | 多轮对话 |
💡 工作流程
用户请求 → AI 分析 → 需要外部工具 → 调用 MCP 服务器 → 获取结果 → 返回给用户
🌐 生态系统
Codex CLI (MCP 客户端)
↓ MCP 协议
MCP 服务器 (各种工具)
├── 文件系统
├── 数据库
├── API 服务
├── 浏览器
└── 自定义工具
2. 为什么使用 MCP
🎯 核心价值
| 没有 MCP | 有 MCP |
|---|---|
| AI 只能操作本地文件 | AI 可以访问数据库、API |
| AI 无法查询实时数据 | AI 可以获取实时信息 |
| AI 能力受限于模型 | AI 能力可以无限扩展 |
| 每个工具需要单独集成 | 统一的集成标准 |
📊 使用场景
| 场景 | MCP 工具 | 效果 |
|---|---|---|
| 数据库查询 | postgres-mysql-mcp | AI 直接查询数据库 |
| 文件系统 | filesystem-mcp | 安全地访问文件 |
| 网页浏览 | puppeteer-mcp | AI 可以浏览网页 |
| API 调用 | fetch-mcp | AI 可以调用 REST API |
| Git 操作 | git-mcp | AI 可以操作 Git |
| 发送邮件 | email-mcp | AI 可以发邮件 |
| 日历管理 | calendar-mcp | AI 可以管理日程 |
✅ 什么时候用 MCP
- 需要访问外部数据源(数据库、API)
- 需要调用外部服务(邮件、通知)
- 需要浏览器操作
- 需要扩展 AI 的原生能力
❌ 什么时候不用 MCP
- 简单的文件操作(Codex 原生支持)
- 基本的终端命令(Codex 原生支持)
- 不需要外部依赖的任务
3. MCP 工作原理
🏗️ 架构图
┌─────────────────────────────────────────────┐
│ Codex CLI │
│ (MCP Client) │
└─────────────────────────────────────────────┘
│
│ MCP Protocol (JSON-RPC)
│
┌─────────────────────────────────────────────┐
│ MCP Server Manager │
└─────────────────────────────────────────────┘
│
┌───────────┼───────────┐
│ │ │
▼ ▼ ▼
┌────────────┐ ┌────────────┐ ┌────────────┐
│ MCP Server │ │ MCP Server │ │ MCP Server │
│ (Database) │ │ (FileSys) │ │ (Browser) │
└────────────┘ └────────────┘ └────────────┘
📡 通信协议
MCP 使用 JSON-RPC 2.0 协议:
请求:
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "query_database",
"arguments": {
"sql": "SELECT * FROM users LIMIT 10"
}
}
}
响应:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [
{
"type": "text",
"text": "[{\"id\": 1, \"name\": \"Alice\"}, ...]"
}
]
}
}
🔌 传输方式
| 方式 | 说明 | 适用场景 |
|---|---|---|
| stdio | 标准输入输出 | 本地进程 |
| SSE | Server-Sent Events | HTTP 服务 |
| HTTP | HTTP POST | REST API |
4. 常用 MCP 服务器
📦 官方 MCP 服务器
| 服务器 | 说明 | 安装 |
|---|---|---|
| filesystem | 文件系统访问 | @anthropic/mcp-filesystem |
| postgres | PostgreSQL 数据库 | @anthropic/mcp-postgres |
| mysql | MySQL 数据库 | @anthropic/mcp-mysql |
| sqlite | SQLite 数据库 | @anthropic/mcp-sqlite |
| github | GitHub API | @anthropic/mcp-github |
| puppeteer | 浏览器自动化 | @anthropic/mcp-puppeteer |
| fetch | HTTP 请求 | @anthropic/mcp-fetch |
| memory | 知识图谱 | @anthropic/mcp-memory |
| brave-search | 网页搜索 | @anthropic/mcp-brave-search |
| slack | Slack 集成 | @anthropic/mcp-slack |
🔥 社区热门 MCP 服务器
| 服务器 | 说明 | GitHub |
|---|---|---|
| notion-mcp | Notion 集成 | anthropics/notion-mcp |
| linear-mcp | Linear 集成 | anthropics/linear-mcp |
| sentry-mcp | Sentry 错误追踪 | anthropics/sentry-mcp |
| jira-mcp | Jira 集成 | anthropics/jira-mcp |
| confluence-mcp | Confluence 文档 | anthropics/confluence-mcp |
| redis-mcp | Redis 操作 | anthropics/redis-mcp |
| elasticsearch-mcp | ES 搜索 | anthropics/elasticsearch-mcp |
💡 如何选择
| 需求 | 推荐 MCP 服务器 |
|---|---|
| 操作文件 | filesystem |
| 查询数据库 | postgres / mysql / sqlite |
| 调用 API | fetch |
| 浏览网页 | puppeteer / brave-search |
| GitHub 操作 | github |
| 团队协作 | slack / notion / linear |
5. 配置 MCP 服务器
📁 配置文件位置
| 系统 | 路径 |
|---|---|
| Mac/Linux | ~/.codex/config.json |
| Windows | %USERPROFILE%\.codex\config.json |
⚙️ 配置格式
{
"mcpServers": {
"server-name": {
"command": "command",
"args": ["arg1", "arg2"],
"env": {
"KEY": "value"
}
}
}
}
📝 配置示例
1. 文件系统 MCP
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-filesystem", "/path/to/allowed/dir"]
}
}
}
2. PostgreSQL MCP
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-postgres"],
"env": {
"DATABASE_URL": "postgresql://user:pass@localhost:5432/mydb"
}
}
}
}
3. GitHub MCP
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_xxxxxxxxxxxx"
}
}
}
}
4. 多个 MCP 服务器
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-filesystem", "."]
},
"postgres": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-postgres"],
"env": {
"DATABASE_URL": "postgresql://localhost/mydb"
}
},
"github": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-github"],
"env": {
"GITHUB_TOKEN": "ghp_xxx"
}
}
}
}
🔧 使用命令配置
# 查看当前 MCP 配置
codex config get mcpServers
# 添加 MCP 服务器
codex config set mcpServers.postgres.command "npx"
codex config set mcpServers.postgres.args '["-y", "@anthropic/mcp-postgres"]'
# 删除 MCP 服务器
codex config unset mcpServers.postgres
# 编辑配置文件
codex config edit
✅ 验证配置
# 启动 Codex
codex
# 查看可用的 MCP 工具
/mcp list
# 测试 MCP 工具
> 使用 postgres 工具查询所有用户
6. 实战案例
💼 案例1:数据库查询助手
场景:让 AI 帮你查询和分析数据库
配置:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-postgres"],
"env": {
"DATABASE_URL": "postgresql://user:pass@localhost:5432/analytics"
}
}
}
}
使用:
codex
> 查询最近 7 天的用户注册数量,按天分组
AI 会:
- 调用 MCP 工具执行 SQL
- 获取结果
- 生成图表或分析报告
💼 案例2:自动化代码审查
场景:PR 提交后自动审查代码
配置:
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-github"],
"env": {
"GITHUB_TOKEN": "ghp_xxx"
}
}
}
}
使用:
codex
> 审查 GitHub 上 org/repo 仓库的 PR #123
> 重点关注安全问题和性能问题
AI 会:
- 通过 MCP 获取 PR 详情
- 分析代码差异
- 生成审查报告
- (可选)提交评论
💼 案例3:知识库问答系统
场景:基于文档的智能问答
配置:
{
"mcpServers": {
"memory": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-memory"]
},
"filesystem": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-filesystem", "./docs"]
}
}
}
使用:
codex
> 读取 docs/ 目录下的所有文档
> 然后回答:如何配置用户权限?
AI 会:
- 通过 MCP 读取文档
- 建立知识图谱
- 基于文档内容回答问题
💼 案例4:全栈开发助手
场景:同时操作数据库、文件系统、Git
配置:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-postgres"],
"env": {
"DATABASE_URL": "postgresql://localhost/dev"
}
},
"filesystem": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-filesystem", "."]
},
"github": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-github"],
"env": {
"GITHUB_TOKEN": "ghp_xxx"
}
}
}
}
使用:
codex
> 1. 查询数据库中的用户表结构
> 2. 根据表结构生成 Entity 类
> 3. 创建数据库迁移脚本
> 4. 提交到 Git 并创建 PR
AI 会:
- 通过 postgres MCP 查询表结构
- 通过 filesystem MCP 生成代码
- 运行迁移脚本
- 通过 github MCP 创建 PR
7. 开发自己的 MCP 服务器
🛠️ 开发准备
# 安装 MCP SDK
npm install @anthropic/mcp-sdk
# 或使用 Python
pip install mcp
📝 Node.js 示例
import { McpServer } from '@anthropic/mcp-sdk/server';
import { StdioServerTransport } from '@anthropic/mcp-sdk/server/stdio';
// 创建服务器
const server = new McpServer({
name: 'my-custom-mcp',
version: '1.0.0',
});
// 定义工具
server.tool(
'get_weather', // 工具名
'获取天气信息', // 描述
{
city: { type: 'string', description: '城市名' },
}, // 参数
async ({ city }) => {
// 调用天气 API
const weather = await fetchWeather(city);
return {
content: [{ type: 'text', text: JSON.stringify(weather) }],
};
}
);
// 启动服务器
const transport = new StdioServerTransport();
await server.connect(transport);
📝 Python 示例
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
# 创建服务器
server = Server("my-custom-mcp")
# 定义工具
@server.tool()
async def get_weather(city: str) -> str:
"""获取天气信息"""
weather = await fetch_weather(city)
return TextContent(type="text", text=str(weather))
# 启动服务器
async def main():
async with stdio_server() as (read, write):
await server.run(read, write)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
📦 打包发布
// package.json
{
"name": "my-custom-mcp",
"version": "1.0.0",
"bin": {
"my-custom-mcp": "./dist/index.js"
}
}
# 构建
npm run build
# 发布
npm publish
🔧 配置使用
{
"mcpServers": {
"my-custom-mcp": {
"command": "npx",
"args": ["-y", "my-custom-mcp"]
}
}
}
🎯 开发最佳实践
-
工具命名清晰
// ✅ 好的命名 server.tool('query_database', ...) server.tool('send_email', ...) // ❌ 不好的命名 server.tool('doStuff', ...) server.tool('tool1', ...) -
参数描述详细
server.tool('query_database', '执行 SQL 查询', { sql: { type: 'string', description: 'SQL 查询语句,支持 SELECT 查询' }, limit: { type: 'number', description: '返回结果数量限制,默认 100', default: 100 }, }, handler); -
错误处理完善
try { const result = await db.query(sql); return { content: [{ type: 'text', text: result }] }; } catch (error) { return { content: [{ type: 'text', text: `查询失败: ${error.message}` }], isError: true }; } -
返回格式统一
// 成功 return { content: [{ type: 'text', text: '操作成功' }], }; // 失败 return { content: [{ type: 'text', text: '操作失败' }], isError: true, };
8. 与 Claude Code MCP 对比
📊 功能对比
| 特性 | Codex CLI | Claude Code |
|---|---|---|
| MCP 支持 | ✅ 支持 | ✅ 支持 |
| 配置格式 | JSON | JSON |
| 传输方式 | stdio, SSE, HTTP | stdio, SSE, HTTP |
| 工具调用 | ✅ 支持 | ✅ 支持 |
| 资源访问 | ✅ 支持 | ✅ 支持 |
| 提示模板 | ✅ 支持 | ✅ 支持 |
| 采样 | ✅ 支持 | ✅ 支持 |
🔄 配置对比
Codex CLI 配置(~/.codex/config.json):
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-postgres"],
"env": {
"DATABASE_URL": "postgresql://localhost/db"
}
}
}
}
Claude Code 配置(~/.claude/settings.json):
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-postgres"],
"env": {
"DATABASE_URL": "postgresql://localhost/db"
}
}
}
}
结论:配置格式几乎相同,可以轻松切换。
💡 选择建议
| 场景 | 推荐 |
|---|---|
| 已有 MCP 服务器 | 两者都支持,直接用 |
| 开发新 MCP | 使用官方 SDK,两者兼容 |
| 团队协作 | 统一使用一种工具 |
| 个人偏好 | 喜欢哪个用哪个 |
9. 常见问题
❓ Q1:MCP 服务器启动失败
症状:
Error: MCP server failed to start
解决方案:
# 检查命令是否正确
npx -y @anthropic/mcp-postgres --help
# 检查环境变量
echo $DATABASE_URL
# 查看详细错误
codex --verbose
# 手动测试 MCP 服务器
echo '{"jsonrpc":"2.0","method":"initialize","params":{},"id":1}' | npx -y @anthropic/mcp-postgres
❓ Q2:工具调用超时
症状:
Error: Tool call timed out
解决方案:
# 检查网络连接
ping api.example.com
# 增加超时时间
codex config set mcpTimeout 60000
# 检查 MCP 服务器日志
codex --verbose
❓ Q3:权限被拒绝
症状:
Error: Permission denied to access resource
解决方案:
# 检查 MCP 服务器配置
codex config get mcpServers
# 检查 API Token 是否有效
# 检查数据库用户权限
# 检查文件系统权限
❓ Q4:多个 MCP 服务器冲突
症状:
- 工具名冲突
- 响应混乱
解决方案:
{
"mcpServers": {
"db-prod": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-postgres"],
"env": { "DATABASE_URL": "postgresql://prod/db" }
},
"db-dev": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-postgres"],
"env": { "DATABASE_URL": "postgresql://dev/db" }
}
}
}
10. 总结
🎯 核心要点
- MCP 是什么:AI 与外部工具通信的标准协议
- 为什么用:扩展 AI 能力,访问外部数据和服务
- 怎么配置:在 config.json 中添加 mcpServers
- 常用工具:数据库、文件系统、GitHub、浏览器
- 开发自己的:使用官方 SDK,发布到 npm
📋 快速开始
- 选择需要的 MCP 服务器
- 安装 MCP 服务器包
- 在 config.json 中配置
- 重启 Codex CLI
- 使用
/mcp list验证
📚 下一步
- 📖 第7篇:Skills 技能系统:从安装到开发完全指南
- 🔧 实践:配置一个数据库 MCP 服务器
- 💬 社区:分享你的 MCP 配置
📝 系列文章导航
- 上一篇:[第5篇 - 避坑指南:新手必看的20个常见问题]
- 下一篇:[第7篇 - Skills 技能系统:从安装到开发完全指南]
- 系列目录:[Codex CLI 中文官方手册与使用指南(12篇)]
💡 遇到问题? 欢迎在评论区留言,我会及时回复!
👍 觉得有用? 点赞收藏,帮助更多开发者!
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)