codex mcp运行器
](https://www.npmjs.com/package/codex-mcp-runner) ](https://www.npmjs.com/package/codex-mcp-runner) 
英语 | 韩语
运行并行Codex CLI任务 安全地 --隔离在git工作树中,由6层防御层保护。
为什么?
运行多个 codex exec 并行处理是可能的,但是 不稳定:
codex mcp运行器 解决这个问题:
||原始 codex exec x N|codex mcp运行器| |--|---|---| |并行执行|可能但不稳定|稳定(工作树隔离)| |会话冲突|共享状态干扰|每个任务都在自己的git工作树中| |安全|无边界|6层防御(命令分配、路径限制、环境净化)| |结果收集|手动|带补丁、日志和证据的结构化输出| |清理|手动|完成、超时或崩溃时自动| |集成|仅限CLI| MCP标准 --适用于Claude、Cursor和任何MCP客户端|
概述
codex-mcp-runner 是一个MCP(模型上下文协议)服务器,它以完全隔离和安全的方式编排并行Codex CLI任务。它允许任何MCP客户端:
- 以可配置的并发性并行运行多个Codex任务(最多8个)
- 将每个任务隔离在自己的git工作树中,以防止会话冲突
- 根据安全策略验证补丁和文件修改
- 使用命令日志、文件更改和证据收集结构化结果
- 审查开发计划的完整性和并行化机会
该服务器将MCP客户端的规划功能与Codex的自主代码执行连接起来,实现了安全、经过审核和可重复的多步骤代码生成工作流程。
建筑
Claude (Manager)
|
| MCP Protocol (stdio)
|
v
codex-mcp-runner (MCP Server)
|
+-- Config Validator (security policies, limits)
|
+-- Task Orchestrator (concurrency control, scheduling)
|
+-- Worktree Manager (creates/cleanup git worktrees)
|
+-- Codex Launcher (spawns parallel Codex CLI processes)
|
+-- Result Aggregator (collects and validates outputs)
|
v
Task 1 (Worktree A) --> Codex CLI --> [Execution + Logs]
Task 2 (Worktree B) --> Codex CLI --> [Execution + Logs]
Task 3 (Worktree C) --> Codex CLI --> [Execution + Logs]每个任务在其独立的工作树中独立运行,在允许并行执行的同时防止状态泄漏。收集、验证结果并将其连同完整的审计跟踪返回给Claude。
特性
- 并行任务执行:以可配置的限制同时运行多个Codex CLI任务
- Git工作树隔离:每个任务都在自己的工作台上运行,防止交叉污染
- 安全第一设计:命令分配、路径限制、环境清理和执行后验证
- 补丁验证:验证补丁是否干净地应用于基础存储库引用
- 结构化输出:详细的任务结果,包括命令日志、文件更改、执行证据和时间
- 计划审查工具:分析开发计划的完整性、依赖性和并行化差距
- 综合录井:带有时间戳的日志用于调试,并具有自动保留策略
- 优雅的清理:完成、超时或崩溃时自动清理工作台
- 试运行模式:未实际执行的测试任务配置
- 资源限制:可配置的并发性、超时和任务计数上限
先决条件
- Node.js >= 18.0.0
- Git (带工作台支撑)
- OpenAI Codex命令行界面 (已安装并位于PATH中)
- 认证 (以下之一):
- CODEX_API_KEY 具有有效OpenAI API密钥的环境变量,或 - codex login (基于OAuth的身份验证)
验证先决条件
node --version # >= 18.0.0
git --version # any recent version
which codex # should return path to codex binary
codex auth status # check authentication status安装
全局安装(建议用于MCP服务器)
npm install -g codex-mcp-runner然后运行:
codex-mcp-runner使用npx(无需安装)
npx -y codex-mcp-runner本地开发安装
git clone https://github.com/jsc7727/codex-mcp-runner.git
cd codex-mcp-runner
npm install
npm run build
npm startMCP客户端设置
Claude桌面配置
编辑 ~/Library/Application Support/Claude/claude_desktop_config.json (macOS)或您平台上的同等产品:
{
"mcpServers": {
"codex-runner": {
"command": "npx",
"args": ["-y", "codex-mcp-runner"],
"env": {
"CODEX_API_KEY": "your-openai-api-key-here"
}
}
}
}重新启动克劳德桌面。现在你应该看到 run_codex_tasks 和 review_plan_with_codex 工具可用。
克劳德代码(哦,我的claudecode)配置
将以下内容添加到您的 .claude/agents.json 或者在代理配置中:
{
"mcp_servers": [
{
"name": "codex-runner",
"command": "npx",
"args": ["-y", "codex-mcp-runner"],
"env": {
"CODEX_API_KEY": "your-openai-api-key-here"
}
}
]
}项目配置
配置 codex-mcp-runner 行为与a .mcp-codex.json 存储库根目录中的文件。
配置文件示例
{
"allowed_commands": [
"npm test",
"npm run lint",
"npm run build",
"npx tsc --noEmit"
],
"default_allowed_paths": [
"src/**",
"tests/**",
"package.json",
"tsconfig.json"
],
"default_concurrency": 2,
"default_timeout_sec": 300,
"resource_policy": "conservative",
"network_policy": "deny",
"codex_command": "codex",
"codex_model": "o4-mini",
"codex_full_auto": true,
"codex_ephemeral": true,
"sandbox_mode": "workspace-write",
"max_runs_retained": 20,
"max_tasks_per_run": 10
}配置字段
| 字段 | 类型 | 默认值 | 描述 |
|---|---|---|---|
allowed_commands | string\[\] | ["npm test", "npm run lint", "npx tsc --noEmit"] | 命令前缀allowlist。Codex只能运行以这些前缀开头的命令。 |
default_allowed_paths | string\[\] | ["src/**", "tests/**", "package.json"] | 用于文件修改的球形图案。Codex修改的文件必须符合一种模式。 |
default_concurrency | 编号 | 2 | 每次运行的最大并行任务数(1-8)。 |
default_timeout_sec | 编号 | 300 | 每项任务超时时间(秒)(10-1800)。 |
resource_policy | 字符串 | "conservative" | 资源配置策略: "conservative" 或 "normal". |
network_policy | 字符串 | "deny" | 网络访问策略: "deny" 或 "allow". |
codex_command | 字符串 | "codex" | 调用Codex CLI的路径或命令。 |
codex_model | 字符串 | "o4-mini" | 用于Codex任务的模型。 |
codex_full_auto | 布尔值 | true | 启用 --full-auto 自主执行的标志。 |
codex_ephemeral | 布尔值 | true | 启用 --ephemeral 标志(无对话历史记录)。 |
sandbox_mode | 字符串 | "workspace-write" | 沙盒级别: "read-only", "workspace-write",或 "danger-full-access". |
max_runs_retained | 编号 | 20 | 要保留的最大日志目录数。旧日志将被删除。 |
max_tasks_per_run | 编号 | 10 | 每个允许的最大任务数 run_codex_tasks 呼叫(1-50)。 |
MCP工具
run_codex_tasks
并行执行多个Codex CLI任务,并进行完全隔离和安全验证。
输入架构:
{
run_id?: string; // Optional run identifier (auto-generated if omitted)
base_ref?: string; // Git reference for patch validation (default: "HEAD")
concurrency?: number; // Override default concurrency (1-8)
resource_policy?: "conservative" | "normal"; // Override resource policy
tasks: {
task_id: string; // Unique identifier within the run
prompt: string; // Codex prompt
allowed_paths?: string[]; // Override default allowed paths
allowed_commands?: string[]; // Override default allowed commands
timeout_sec?: number; // Override default timeout (10-600)
}[];
dry_run?: boolean; // If true, validate but don't execute
}输出架构:
{
run_id: string;
results: {
task_id: string;
status: "success" | "failed" | "timeout" | "skipped";
exit_code: number | null;
files_changed: string[];
patch: string; // Redacted after validation
patch_applicable: boolean;
apply_check_log: string;
commands_run: {
cmd: string;
exit_code: number | null;
}[];
evidence: string;
logs: {
stdout: string;
stderr: string;
tail: string; // Last 500 chars of combined output
};
workspace_path: string; // Path to worktree
duration_ms: number;
summary: string;
notes_for_manager: string; // Security violations, errors, etc.
}[];
total_duration_ms: number;
}示例用法:
const result = await mcp.callTool("run_codex_tasks", {
run_id: "feature-auth-v2",
tasks: [
{
task_id: "add-login-endpoint",
prompt: "Add POST /auth/login endpoint with bcrypt password hashing",
timeout_sec: 120
},
{
task_id: "add-jwt-middleware",
prompt: "Add JWT middleware for route protection",
timeout_sec: 120
}
],
concurrency: 2,
dry_run: false
});review_plan_with_codex
审查开发计划的完整性、依赖性、并行化机会和风险。
输入架构:
{
plan_text: string; // Development plan to review
repo_context?: string; // Optional repository context (architecture, tech stack, etc.)
}输出架构:
{
report: {
missing_tasks: string[]; // Tasks that should be added
dependency_issues: string[]; // Unmet or circular dependencies
parallelization_suggestions: string[]; // Tasks that could run in parallel
test_gaps: string[]; // Missing test coverage
risk_flags: string[]; // Identified risks
recommended_task_splits: string[]; // Tasks that should be broken down
}
}示例用法:
const review = await mcp.callTool("review_plan_with_codex", {
plan_text: `
1. Add user authentication service
2. Add login endpoint
3. Add JWT middleware
4. Add permission checks
5. Write integration tests
`,
repo_context: "Node.js / Express API, PostgreSQL database, Jest for testing"
});安全
这 codex-mcp-runner 实现六层防御以确保代码执行安全:
第1层:飞行前验证
- 验证任务ID(字母数字、点、连字符、下划线;1-64个字符)
- 确保运行中的任务ID唯一
- 验证配置文件架构
- 检查先决条件(Node.js、git、Codex CLI、API密钥)
第二层:环境消毒
- 允许列出特定的环境变量:
PATH,HOME,USER,LANG,TERM,SHELL,TMPDIR,NODE_ENV - 总是通过
CODEX_API_KEY用于食品法典认证 - 剥离所有类似秘密的变量(名称以结尾
_KEY,_SECRET,_TOKEN,_PASSWORD) - 防止基于环境的注入攻击
第3层:命令允许列表
- 拒绝shell元字符:
;,|,&,$,(), ```,换行符 - 强制对配置的前缀进行匹配
allowed_commands - 在任务提交(飞行前)和执行结果(执行后)时进行验证
- 防止命令注入和shell逃逸
第4层:路径允许列表
- 强制进行全局模式匹配
default_allowed_paths - 阻止目录遍历(
..,绝对路径) - 执行后验证所有文件修改
- 引发越界更改的违规行为
第5层:Git工作树隔离
- 每个任务都在自己的git工作树中运行
.git/worktrees/{runId}-{taskId} - 防止跨任务干扰和文件系统污染
- 保证在完成、超时或崩溃时进行清理
- 基础存储库保持原始状态
第6层:补丁验证
- 生成的补丁将根据基础存储库参考进行验证
- 确保补丁干净无冲突地应用
- 补丁在结果中被编辑,以防止秘密泄露
- 应用的补丁在日志中签名并加盖时间戳
发展
克隆和设置
git clone https://github.com/jsc7727/codex-mcp-runner.git
cd codex-mcp-runner
npm install构建
npm run build输出TypeScript编译为 dist/ 目录。
观看模式(开发)
npm run dev源文件更改时自动重新编译。
运行测试
npm test使用Vitest运行测试套件。
观看测试
npm run test:watch运行测试并重新运行文件更改。
在本地运行
npm start启动stdio上的MCP服务器。集 CODEX_API_KEY 环境变量优先:
export CODEX_API_KEY=your-key-here
npm start项目结构
codex-mcp-runner/
├── src/
│ ├── index.ts # Entry point
│ ├── server.ts # MCP server setup
│ ├── types.ts # Type definitions and schemas
│ ├── config.ts # Configuration loader
│ ├── security.ts # Security validators
│ ├── worktree.ts # Git worktree management
│ ├── codex-runner.ts # Codex CLI executor
│ ├── codex-output-parser.ts # Parse Codex JSONL output
│ ├── patch-validator.ts # Patch validation
│ ├── log-redactor.ts # Log sanitization
│ ├── logger.ts # Structured logging
│ ├── active-runs.ts # Active run tracking
│ ├── errors.ts # Custom error types
│ ├── startup.ts # Initialization checks
│ ├── tools/
│ │ ├── run-codex-tasks.ts # Main orchestration tool
│ │ └── review-plan.ts # Plan review tool
│ └── utils/
│ ├── exec.ts # Process execution
│ ├── fs.ts # File system utilities
│ └── id.ts # ID generation and validation
├── package.json
├── tsconfig.json
├── .mcp-codex.json # Example configuration
└── README.md # This file故障排除
未找到身份验证
错误: No Codex authentication found. Set CODEX_API_KEY environment variable or run 'codex login'.
解决方案(选项1-OAuth): 运行Codex登录一次:
codex login解决方案(选项2-API密钥): 设置环境变量:
export CODEX_API_KEY=sk-...
npx codex-mcp-runner或者在MCP客户端配置中:
"env": { "CODEX_API_KEY": "sk-..." }未找到Codex CLI
错误: ENOENT: spawn codex ENOENT
解决方案: 安装并验证Codex CLI:
npm install -g @openai/codex-cli
which codex或者在中配置自定义路径 .mcp-codex.json:
{ "codex_command": "/usr/local/bin/codex" }任务超时
错误: Task timeout exceeded (300s)
解决方案: 增加 default_timeout_sec 在 .mcp-codex.json:
{ "default_timeout_sec": 600 }或按任务传递覆盖:
{
task_id: "slow-task",
prompt: "...",
timeout_sec: 600
}违反安全规定:命令不在允许列表中
错误: Command not in allowlist: "npm run custom-script"
解决方案: 将命令添加到 allowed_commands 在 .mcp-codex.json:
{
"allowed_commands": [
"npm test",
"npm run lint",
"npm run custom-script"
]
}安全违规:路径不符合允许的模式
错误: Path not in allowed patterns: "config/secrets.json"
解决方案: 将图案添加到 default_allowed_paths 在 .mcp-codex.json:
{
"default_allowed_paths": [
"src/**",
"tests/**",
"config/**",
"package.json"
]
}工作树清理失败
错误: Worktree cleanup failed: unable to delete directory
解决方法: 手动清理孤立的工作树:
git worktree list
git worktree remove /path/to/orphaned/worktree --force或清洁所有:
git worktree prune许可证
MIT许可证。有关详细信息,请参阅LICENSE文件。
贡献
欢迎捐款。请在GitHub上打开问题并拉取请求。
