Codex CLI-06-MCP集成-扩展AI能力的正确姿势

Codex CLI-06-MCP集成-扩展AI能力的正确姿势 目录 Codex CLI MCP 集成扩展 AI 能力的正确姿势1. 什么是 MCP MCP 定义 核心能力 工作流程 生态系统2. 为什么使用 MCP 核心价值 使用场景✅ 什么时候用 MCP❌ 什么时候不用 MCP3. MCP 工作原理️ 架构图 通信协议 传输方式4. 常用 MCP 服务器 官方 MCP 服务器 社区热门 MCP 服务器 如何选择5. 配置 MCP 服务器 配置文件位置⚙️ 配置格式 配置示例1. 文件系统 MCP2. PostgreSQL MCP3. GitHub MCP4. 多个 MCP 服务器 使用命令配置✅ 验证配置6. 实战案例 案例1数据库查询助手 案例2自动化代码审查 案例3知识库问答系统 案例4全栈开发助手7. 开发自己的 MCP 服务器️ 开发准备 Node.js 示例 Python 示例 打包发布 配置使用 开发最佳实践8. 与 Claude Code MCP 对比 功能对比 配置对比 选择建议9. 常见问题❓ Q1MCP 服务器启动失败❓ Q2工具调用超时❓ Q3权限被拒绝❓ Q4多个 MCP 服务器冲突10. 总结 核心要点 快速开始 下一步 系列文章导航 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有 MCPAI 只能操作本地文件AI 可以访问数据库、APIAI 无法查询实时数据AI 可以获取实时信息AI 能力受限于模型AI 能力可以无限扩展每个工具需要单独集成统一的集成标准 使用场景场景MCP 工具效果数据库查询postgres-mysql-mcpAI 直接查询数据库文件系统filesystem-mcp安全地访问文件网页浏览puppeteer-mcpAI 可以浏览网页API 调用fetch-mcpAI 可以调用 REST APIGit 操作git-mcpAI 可以操作 Git发送邮件email-mcpAI 可以发邮件日历管理calendar-mcpAI 可以管理日程✅ 什么时候用 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标准输入输出本地进程SSEServer-Sent EventsHTTP 服务HTTPHTTP POSTREST API4. 常用 MCP 服务器 官方 MCP 服务器服务器说明安装filesystem文件系统访问anthropic/mcp-filesystempostgresPostgreSQL 数据库anthropic/mcp-postgresmysqlMySQL 数据库anthropic/mcp-mysqlsqliteSQLite 数据库anthropic/mcp-sqlitegithubGitHub APIanthropic/mcp-githubpuppeteer浏览器自动化anthropic/mcp-puppeteerfetchHTTP 请求anthropic/mcp-fetchmemory知识图谱anthropic/mcp-memorybrave-search网页搜索anthropic/mcp-brave-searchslackSlack 集成anthropic/mcp-slack 社区热门 MCP 服务器服务器说明GitHubnotion-mcpNotion 集成anthropics/notion-mcplinear-mcpLinear 集成anthropics/linear-mcpsentry-mcpSentry 错误追踪anthropics/sentry-mcpjira-mcpJira 集成anthropics/jira-mcpconfluence-mcpConfluence 文档anthropics/confluence-mcpredis-mcpRedis 操作anthropics/redis-mcpelasticsearch-mcpES 搜索anthropics/elasticsearch-mcp 如何选择需求推荐 MCP 服务器操作文件filesystem查询数据库postgres / mysql / sqlite调用 APIfetch浏览网页puppeteer / brave-searchGitHub 操作github团队协作slack / notion / linear5. 配置 MCP 服务器 配置文件位置系统路径Mac/Linux~/.codex/config.jsonWindows%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:passlocalhost: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 configsetmcpServers.postgres.commandnpxcodex configsetmcpServers.postgres.args[-y, anthropic/mcp-postgres]# 删除 MCP 服务器codex configunsetmcpServers.postgres# 编辑配置文件codex config edit✅ 验证配置# 启动 Codexcodex# 查看可用的 MCP 工具/mcp list# 测试 MCP 工具使用 postgres 工具查询所有用户6. 实战案例 案例1数据库查询助手场景让 AI 帮你查询和分析数据库配置{mcpServers:{postgres:{command:npx,args:[-y,anthropic/mcp-postgres],env:{DATABASE_URL:postgresql://user:passlocalhost: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}}}}使用codex1. 查询数据库中的用户表结构2. 根据表结构生成 Entity 类3. 创建数据库迁移脚本4. 提交到 Git 并创建 PRAI 会通过 postgres MCP 查询表结构通过 filesystem MCP 生成代码运行迁移脚本通过 github MCP 创建 PR7. 开发自己的 MCP 服务器️ 开发准备# 安装 MCP SDKnpminstallanthropic/mcp-sdk# 或使用 Pythonpipinstallmcp Node.js 示例import{McpServer}fromanthropic/mcp-sdk/server;import{StdioServerTransport}fromanthropic/mcp-sdk/server/stdio;// 创建服务器constservernewMcpServer({name:my-custom-mcp,version:1.0.0,});// 定义工具server.tool(get_weather,// 工具名获取天气信息,// 描述{city:{type:string,description:城市名},},// 参数async({city}){// 调用天气 APIconstweatherawaitfetchWeather(city);return{content:[{type:text,text:JSON.stringify(weather)}],};});// 启动服务器consttransportnewStdioServerTransport();awaitserver.connect(transport); Python 示例frommcp.serverimportServerfrommcp.server.stdioimportstdio_serverfrommcp.typesimportTool,TextContent# 创建服务器serverServer(my-custom-mcp)# 定义工具server.tool()asyncdefget_weather(city:str)-str:获取天气信息weatherawaitfetch_weather(city)returnTextContent(typetext,textstr(weather))# 启动服务器asyncdefmain():asyncwithstdio_server()as(read,write):awaitserver.run(read,write)if__name____main__:importasyncio asyncio.run(main()) 打包发布// package.json{name:my-custom-mcp,version:1.0.0,bin:{my-custom-mcp:./dist/index.js}}# 构建npmrun build# 发布npmpublish 配置使用{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{constresultawaitdb.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 CLIClaude CodeMCP 支持✅ 支持✅ 支持配置格式JSONJSON传输方式stdio, SSE, HTTPstdio, 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. 常见问题❓ Q1MCP 服务器启动失败症状Error: MCP server failed to start解决方案# 检查命令是否正确npx-yanthropic/mcp-postgres--help# 检查环境变量echo$DATABASE_URL# 查看详细错误codex--verbose# 手动测试 MCP 服务器echo{jsonrpc:2.0,method:initialize,params:{},id:1}|npx-yanthropic/mcp-postgres❓ Q2工具调用超时症状Error: Tool call timed out解决方案# 检查网络连接pingapi.example.com# 增加超时时间codex configsetmcpTimeout60000# 检查 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篇]遇到问题欢迎在评论区留言我会及时回复觉得有用点赞收藏帮助更多开发者