105 MCP 工具扩展
通过 Model Context Protocol 将 Codex 连接到外部 API、数据库和自定义服务,打破终端边界。
学习目标
完成本课程后,你将能够:
一、MCP 协议概述
什么是 MCP
**Model Context Protocol(MCP)** 是由 Anthropic 提出、OpenAI Codex 原生支持的开放协议。它定义了 AI 模型与外部工具/数据源之间的标准通信方式。
简单来说:MCP 让 Codex 不再局限于代码文件,而是可以**读取数据库、调用 API、查询外部服务**,就像一个全能的 DevOps 工程师。
MCP 架构
┌──────────┐ MCP Protocol ┌──────────────┐
│ Codex │ ◄──────────────────► │ MCP Server │
│ (Host) │ JSON-RPC 2.0 │ (Provider) │
└──────────┘ └──────┬───────┘
│
┌──────────┼──────────┐
│ │ │
Database REST API Filesystem- **Codex(Host)**:发起请求的一方,如 Codex CLI
- **MCP Server**:提供工具和数据的一方
- **协议**:基于 JSON-RPC 2.0,通过标准输入/输出(stdio)通信
为什么需要 MCP
传统 AI 编程工具只能操作代码文件。现实中,开发需要:
- 读数据库看表结构和数据样例
- 调外部 API 获取实时信息
- 查阅内部文档和知识库
- 操作云服务(部署、监控)
MCP 让这一切成为可能。Codex 可以直接说"查一下 users 表的结构,帮我写对应的 TypeScript 类型"。
二、连接外部 API 和数据源
配置 MCP Server
在 `codex.yaml` 中注册 MCP 服务器:
# codex.yaml
mcp:
enabled: true
servers:
# —— PostgreSQL 数据库 ——
- name: postgres-db
command: npx
args: ["-y", "@anthropic/mcp-server-postgres", "${DATABASE_URL}"]
# —— GitHub API ——
- name: github
command: npx
args: ["-y", "@anthropic/mcp-server-github"]
env:
GITHUB_TOKEN: "${GITHUB_TOKEN}"
# —— 文件系统 ——
- name: filesystem
command: npx
args: ["-y", "@anthropic/mcp-server-filesystem", "/path/to/allowed/dir"]
# —— Web 搜索 ——
- name: brave-search
command: npx
args: ["-y", "@anthropic/mcp-server-brave-search"]
env:
BRAVE_API_KEY: "${BRAVE_API_KEY}"实际使用示例
配置完成后,Codex 会自动识别 MCP 工具。你可以这样用:
# 数据库查询
帮我查一下 orders 表最近 30 天的订单量和总金额
看看 users 表有哪些索引,有没有缺失的
# GitHub 操作
查看 repo 的 open issues,按标签分类
帮我创建 PR 描述,基于最近 5 次 commit
# 文件系统
读取 /docs/api-spec.yaml,根据这个 spec 生成 Express 路由
# Web 搜索
搜索 Next.js 14 Server Actions 的最佳实践,总结 5 条关键建议三、数据库 MCP Server 配置
安装与启动
# 安装 PostgreSQL MCP Server
npm install -g @anthropic/mcp-server-postgres
# 在 codex.yaml 中配置(见上节)常用的数据库操作
# Schema 理解
"读取数据库的所有表结构,生成 Prisma schema 文件"
# 数据查询
"统计每个分类下的产品数量,按数量降序排列"
"查询过去 7 天注册但未下单的用户邮箱"
# 性能分析
"找出缺少索引的慢查询"
"检查哪些表的数据量增长最快"
# Migration 辅助
"对比数据库当前 schema 和 prisma/schema.prisma,列出差异"
"生成一个 migration 给 orders 表添加 refund_amount 字段"安全注意
# 限制 MCP 数据库 Server 的权限
mcp:
servers:
- name: postgres-db
command: npx
args:
- "-y"
- "@anthropic/mcp-server-postgres"
- "--read-only" # 只读模式,禁止写操作
- "--max-rows=100" # 限制返回行数
- "${DATABASE_URL_READONLY}" # 使用只读数据库账号四、构建自定义 MCP 工具
基础框架
// my-custom-mcp-server.ts
import { Server } from "@anthropic/mcp-sdk";
import { StdioServerTransport } from "@anthropic/mcp-sdk/stdio.js";
// 创建 MCP Server
const server = new Server(
{
name: "my-custom-server",
version: "1.0.0",
},
{
capabilities: {
tools: {}, // 声明支持工具调用
},
}
);
// 注册工具:获取天气
server.setRequestHandler("tools/list", async () => ({
tools: [
{
name: "get_weather",
description: "获取指定城市的当前天气",
inputSchema: {
type: "object",
properties: {
city: { type: "string", description: "城市名称,如 Beijing" },
unit: { type: "string", enum: ["celsius", "fahrenheit"], default: "celsius" }
},
required: ["city"]
}
},
{
name: "get_deploy_status",
description: "查询项目的部署状态",
inputSchema: {
type: "object",
properties: {
environment: { type: "string", enum: ["staging", "production"] }
},
required: ["environment"]
}
}
]
}));
// 处理工具调用
server.setRequestHandler("tools/call", async (request) => {
const { name, arguments: args } = request.params;
switch (name) {
case "get_weather": {
// 调用真实天气 API
const response = await fetch(`https://api.weather.com/v1/${args.city}`);
const data = await response.json();
return {
content: [{ type: "text", text: `${args.city}: ${data.temp}°${args.unit}` }]
};
}
case "get_deploy_status": {
// 查询部署状态
const status = await checkDeployStatus(args.environment);
return {
content: [{ type: "text", text: JSON.stringify(status, null, 2) }]
};
}
default:
throw new Error(`Unknown tool: ${name}`);
}
});
// 启动服务(通过 stdio 与 Codex 通信)
const transport = new StdioServerTransport();
await server.connect(transport);在 codex.yaml 中注册自定义 Server
mcp:
servers:
- name: my-custom
command: node
args: [".codex/mcp-servers/my-custom-server.js"]五、MCP 安全考虑
风险清单
| 风险 | 说明 | 防护措施 |
|---|---|---|
| 数据泄露 | Codex 可能通过 MCP 读取敏感数据 | 使用只读账号,限制表/字段访问 |
| 权限过大 | MCP Server 拥有过高系统权限 | 遵循最小权限原则 |
| 命令注入 | 用户输入可能被注入到系统命令 | 严格校验和清理输入 |
| 敏感信息 | 数据库密码等可能被 Codex 输出 | 使用环境变量,不硬编码 |
| 工具滥用 | 恶意 prompt 可能滥用 MCP 工具 | 工具描述中声明限制条件 |
安全配置示例
mcp:
enabled: true
security:
require_confirmation: true # 使用 MCP 工具前需要用户确认
allowed_tools: # 白名单模式
- "get_weather"
- "get_deploy_status"
# 未列出的工具不可用
servers:
- name: postgres-db
command: npx
args:
- "-y"
- "@anthropic/mcp-server-postgres"
- "--read-only"
- "--max-rows=50"
- "--allowed-tables=users,products,orders"
# 只允许访问指定的表六、本课总结
**核心要点:**
- MCP 是连接 Codex 与外部世界的标准协议,基于 JSON-RPC 2.0
- 通过 codex.yaml 注册 MCP Server,Codex 自动发现可用工具
- 数据库 MCP Server 让 Codex 直接查询表结构、执行 SQL、分析数据
- 自定义 MCP Server 只需实现 `tools/list` 和 `tools/call` 两个接口
- 安全第一:始终使用只读账号、限制访问范围、开启确认模式
- MCP 生态在快速增长,关注官方和社区发布的新 Server
**下一步:** 最后一课将学习 Codex 自定义指令系统,创建可复用的指令模板,并与团队共享最佳实践。