提交工单

Codex CLI 接入 MCP 服务器:扩展Agent能力边界的完整实战教程

文档更新于

Codex CLI 默认只能访问本地文件系统。通过接入 MCP(Model Context Protocol)服务器,Codex 的能力边界可以显著扩展:读写 GitHub Issues/PR、查询数据库、搜索内部文档、调用外部 API……本文提供从配置到实战的完整教程。


一、MCP 架构原理

MCP 是 Anthropic 提出的开放协议,定义了 AI Agent 如何与外部工具/数据源交互。其架构由三部分组成:

┌─────────────────────────────────────┐
│           Codex CLI(Host)          │
│  发现 MCP 服务器 → 调用工具 → 读取资源 │
└──────────────┬──────────────────────┘
               │ JSON-RPC over stdio/HTTP
    ┌──────────┼──────────┐
    ▼          ▼          ▼
[filesystem] [github]  [postgres]     ← MCP Servers
    │          │          │
  本地文件   GitHub API  数据库

Codex CLI 作为 MCP Host,在启动时根据 config.toml 的配置启动各 MCP Server 子进程(通过 stdio 通信),或连接到已运行的 HTTP MCP 服务。每个 MCP Server 向 Codex 暴露一组「工具(Tools)」和「资源(Resources)」,Codex 在推理时可按需调用。

二、在 config.toml 中配置 MCP 服务器

所有 MCP 服务器配置集中在 ~/.codex/config.toml 的 [mcp_servers] 节:

# ~/.codex/config.toml

[mcp_servers.filesystem]
# 官方 MCP filesystem 服务器,允许 Codex 访问额外目录
command = "npx"
args = [
  "-y",
  "@modelcontextprotocol/server-filesystem",
  "/home/user/shared-libs",     # 允许访问的额外目录
  "/home/user/docs"
]
timeout_secs = 30

[mcp_servers.github]
# 官方 GitHub MCP 服务器
command = "npx"
args = ["-y", "@modelcontextprotocol/server-github"]
env = { GITHUB_PERSONAL_ACCESS_TOKEN = "${GITHUB_TOKEN}" }  # 从环境变量读取
timeout_secs = 30

[mcp_servers.postgres]
# PostgreSQL 数据库 MCP 服务器
command = "npx"
args = ["-y", "@modelcontextprotocol/server-postgres"]
env = { DATABASE_URL = "${DATABASE_URL}" }
timeout_secs = 60

[mcp_servers.fetch]
# 允许 Codex 发起 HTTP 请求(用于读取在线文档、API)
command = "npx"
args = ["-y", "@modelcontextprotocol/server-fetch"]
timeout_secs = 30

三、实战案例一:接入 GitHub MCP,让 Codex 直接操作 PR

前置准备

# 1. 在 GitHub 创建 Personal Access Token
# 访问 https://github.com/settings/tokens,勾选:
# repo(完整仓库访问)、issues、pull_requests

# 2. 配置环境变量
echo 'export GITHUB_TOKEN="ghp_xxxxxxxxxxxx"' >> ~/.bashrc
source ~/.bashrc

# 3. 安装 MCP Server(首次运行时 npx 自动安装)
npx -y @modelcontextprotocol/server-github --help

Codex + GitHub MCP 实战

# 进入项目目录(必须是 GitHub 仓库)
cd ~/my-project

# 启动 Codex 并使用 GitHub MCP
codex "查看最近5个未关闭的 Issue,为每个 Issue 生成对应的代码修复方案"

Codex 会通过 GitHub MCP 调用 list_issues 工具读取 Issue 列表,结合本地代码库分析,然后生成针对性的修复建议,甚至可以直接创建 PR:

codex "修复 Issue #42(用户注册时邮箱验证未生效),修复后创建一个 PR,
       标题格式:fix: 修复用户注册邮箱验证逻辑,并关联 Issue #42"

GitHub MCP 可用工具清单

工具名 说明
list_issues 列出仓库 Issue(支持过滤标签、状态)
get_issue 获取指定 Issue 详情和评论
create_issue 创建新 Issue
list_pull_requests 列出 PR 列表
get_pull_request 获取 PR 详情、变更文件、审查评论
create_pull_request 创建新 PR
list_commits 查看提交历史
get_file_contents 读取指定分支的文件内容
search_code 在仓库内搜索代码

四、实战案例二:接入 PostgreSQL MCP,让 Codex 理解数据库结构

配置

# 设置数据库连接(使用只读用户!)
export DATABASE_URL="postgresql://readonly_user:password@localhost:5432/mydb"

# config.toml 中已配置 postgres MCP server(见第二节)

使用场景

# 让 Codex 自动理解数据库结构后再生成代码
codex "查看数据库中 orders 表和 users 表的结构,然后为订单列表接口
       生成对应的 SQLAlchemy 查询,包含分页和多条件过滤"

Codex 会先调用 PostgreSQL MCP 的 describe_table 工具获取表结构,然后生成精确匹配实际字段名和类型的代码,避免了手动查表的麻烦。

# 数据库性能分析
codex --sandbox read-only \
  "分析 slow_query_log 中出现频率最高的5条查询,
   结合数据库表结构给出索引优化建议"

安全注意事项

  • MCP 数据库连接必须使用只读账号,绝不使用 DBA 或 root 账号
  • 生产数据库不应直接暴露给 Codex,使用 staging 数据库的镜像
  • 在 config.toml 中引用环境变量(${DATABASE_URL}),不要硬编码连接串
# 创建只读数据库用户(PostgreSQL)
CREATE USER codex_readonly WITH PASSWORD 'strong_password';
GRANT CONNECT ON DATABASE mydb TO codex_readonly;
GRANT USAGE ON SCHEMA public TO codex_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO codex_readonly;
-- 后续新表自动授权
ALTER DEFAULT PRIVILEGES IN SCHEMA public
  GRANT SELECT ON TABLES TO codex_readonly;

五、实战案例三:在香港VPS上自托管 MCP 服务器

某些场景需要自建 MCP 服务器,例如接入内部知识库、私有 API 或自定义工具。以下是在香港 VPS 上用 Node.js 实现一个简单 MCP 服务器的完整示例:

# 创建项目
mkdir ~/my-mcp-server && cd ~/my-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk

创建 server.js:

// server.js — 自定义 MCP 服务器示例
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  ListToolsRequestSchema,
  CallToolRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { execSync } from "child_process";

const server = new Server(
  { name: "vps-tools", version: "1.0.0" },
  { capabilities: { tools: {} } }
);

// 声明可用工具
server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [
    {
      name: "get_server_stats",
      description: "获取 VPS 服务器的 CPU、内存、磁盘使用情况",
      inputSchema: {
        type: "object",
        properties: {},
        required: [],
      },
    },
    {
      name: "list_running_services",
      description: "列出当前运行的 systemd 服务",
      inputSchema: {
        type: "object",
        properties: {
          filter: {
            type: "string",
            description: "过滤关键词(可选)",
          },
        },
      },
    },
  ],
}));

// 工具执行逻辑
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;

  if (name === "get_server_stats") {
    const cpu = execSync("top -bn1 | grep 'Cpu(s)' | awk '{print $2}'")
      .toString().trim();
    const mem = execSync("free -h | awk 'NR==2{print $3\"/\"$2}'")
      .toString().trim();
    const disk = execSync("df -h / | awk 'NR==2{print $3\"/\"$2\" (\"$5\" used)\"}'")
      .toString().trim();

    return {
      content: [
        {
          type: "text",
          text: `CPU 使用率: ${cpu}%\n内存: ${mem}\n磁盘: ${disk}`,
        },
      ],
    };
  }

  if (name === "list_running_services") {
    const filter = args?.filter || "";
    const cmd = filter
      ? `systemctl list-units --type=service --state=running | grep ${filter}`
      : "systemctl list-units --type=service --state=running";
    const result = execSync(cmd, { timeout: 5000 }).toString();
    return { content: [{ type: "text", text: result }] };
  }

  throw new Error(`Unknown tool: ${name}`);
});

// 启动 stdio 传输
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("VPS Tools MCP Server started");

在 config.toml 中接入:

[mcp_servers.vps-tools]
command = "node"
args = ["/home/user/my-mcp-server/server.js"]
timeout_secs = 30
# 使用自定义 MCP 工具
codex "检查服务器当前状态,如果内存使用率超过 80%,分析代码中可能的内存泄漏点"

六、在 Codex 会话中管理 MCP 连接

# 交互模式中查看 MCP 状态
codex
> /mcp

# 输出示例:
# Connected MCP Servers:
#   ✅ filesystem    5 tools, 0 resources
#   ✅ github        12 tools, 3 resources  
#   ✅ postgres      8 tools, 2 resources
#   ✅ vps-tools     2 tools, 0 resources
#   ❌ fetch         Connection failed: timeout

> /mcp reconnect fetch    # 重连失败的服务器

七、总结

MCP 将 Codex CLI 从「本地文件 AI」升级为「连接企业数据和工具生态的 AI Agent」。通过合理配置 GitHub MCP + 数据库 MCP,Codex 可以在理解完整上下文(代码 + Issue + 数据结构)的前提下生成更准确的解决方案,显著减少人工补充信息的成本。自托管 MCP 服务器则进一步打通了内部系统的边界,是企业级 Codex 部署的关键能力。

需要服务器?

香港 / 美国 / 日本服务器与 VPS,工程师 7×24 在线,工单平均 10 分钟内响应。