使用 Codex 与 Agents SDK
如需完整文档索引,请参阅 llms.txt。文档页面的 Markdown 版本可通过在页面后追加
.md来获取 URL。
将 Codex 作为 MCP 服务器运行
Section titled “将 Codex 作为 MCP 服务器运行”你可以将 Codex 作为 MCP 服务器运行,并从其他 MCP 客户端连接它(例如,使用 OpenAI Agents SDK MCP 集成 构建的 Agent)。
要将 Codex 作为 MCP 服务器启动,可以使用以下命令:
codex mcp-server你可以启动一个 Codex MCP 服务器,使用 Model Context Protocol Inspector:
npx @modelcontextprotocol/inspector codex mcp-server发送 tools/list 请求以查看两个工具:
codex:使用以下提示词和配置覆盖项运行 Codex 会话:
| 属性 | 类型 | 描述 |
|---|---|---|
prompt (必需) |
string |
用于启动 Codex 对话的初始用户提示。 |
approval-policy |
string |
模型生成的 shell 命令的审批策略: untrusted, on-request,以及 never。 |
base-instructions |
string |
用于替代默认指令的一组指令。 |
compact-prompt |
string |
压缩对话时使用的提示。 |
config |
object |
覆盖 $CODEX_HOME/config.toml中内容的单项配置设置。 |
cwd |
string |
会话的工作目录。如果是相对路径,则相对于服务器进程的当前目录解析。 |
developer-instructions |
string |
作为 developer 角色消息注入的开发者指令。 |
model |
string |
模型名称的可选覆盖项(例如, gpt-5.6-terra)。 |
sandbox |
string |
沙箱模式: read-only, workspace-write,或 danger-full-access。 |
codex-reply:通过提供线程 Codex 和提示来继续一个 ID 会话。 codex-reply 工具接受以下属性:
| 属性 | 类型 | 描述 |
|---|---|---|
prompt (必需) |
字符串 | 用于继续 Codex 对话的下一条用户提示。 |
threadId (必需) |
字符串 | 要继续的线程的 ID 。 |
conversationId (已弃用) |
字符串 | 以下项的已弃用别名: threadId (为兼容性保留)。 |
使用 threadId 来自 structuredContent.threadId 响应中的 tools/call 。审批提示(exec/patch)也会在其 threadId 载荷中包含 params 。
示例响应负载:
{ "structuredContent": { "threadId": "019bbb20-bff6-7130-83aa-bf45ab33250e", "content": "`ls -lah` (or `ls -alh`) — long listing, includes dotfiles, human-readable sizes." }, "content": [ { "type": "text", "text": "`ls -lah` (or `ls -alh`) — long listing, includes dotfiles, human-readable sizes." } ]}请注意,现代 MCP 客户端通常只会在工具调用结果中报告 "structuredContent"(如果存在),但 Codex MCP 服务器也会返回 "content",以便旧版 MCP 客户端使用。
创建多 Agent 工作流
Section titled “创建多 Agent 工作流”Codex CLI 的功能远不止执行临时任务。通过将 CLI 作为 Model Context Protocol(MCP)服务器公开,并使用 OpenAI Agents SDK 对其进行编排,你可以创建确定性、可审查的工作流,让规模从单个 Agent 扩展到完整的软件交付流水线。
本指南将介绍 OpenAI Cookbook 中展示的相同工作流。你将:
- 启动 Codex CLI 作为长期运行的 MCP 服务器;
- 构建一个专注的单 Agent 工作流,生成可玩的浏览器游戏;以及
- 编排一个包含交接、护栏和完整追踪记录的多 Agent 团队,以便你之后进行审查。
开始之前,请确保你具备:
- Codex CLI 已在本地安装,以便
codex命令可用。 - Python 3.10+,并带有
pip。 - Node.js 18+,如果你想运行上面的 MCP Inspector 示例。
- 一个 OpenAI API 本地存储的密钥。你可以在 OpenAI dashboard中创建或管理密钥。
为本指南创建一个工作目录,并将 API 密钥添加到 .env 文件中:
mkdir codex-workflowscd codex-workflowsprintf "OPENAI_API_KEY=sk-..." > .envAgents SDK 负责处理 Codex、交接和追踪记录之间的编排。安装最新的 SDK 软件包:
python -m venv .venvsource .venv/bin/activatepip install --upgrade openai openai-agents python-dotenv激活虚拟环境可以让 SDK 依赖与 系统其他部分隔离开来。
将 Codex CLI 初始化为 MCP 服务器
Section titled “将 Codex CLI 初始化为 MCP 服务器”首先将 Codex CLI 转换为一个 MCP 服务器,供 Agents SDK 调用。该服务器公开两个工具(codex() 用于启动对话, codex-reply() 用于继续对话),并让 Codex 在多个 agent 轮次之间保持存活。
创建名为 codex_mcp.py 的文件,并添加以下内容:
import asyncio
from agents import Agent, Runnerfrom agents.mcp import MCPServerStdio
async def main() -> None: async with MCPServerStdio( name="Codex CLI", params={ "command": "codex", "args": ["mcp-server"], }, client_session_timeout_seconds=360000, ) as codex_mcp_server: print("Codex MCP server started.") # More logic coming in the next sections. return
if __name__ == "__main__": asyncio.run(main())运行一次脚本,以验证 Codex 是否成功启动:
python codex_mcp.py脚本会在打印 Codex MCP server started. 后退出。在接下来的部分中,你将把同一个 MCP 服务器用于更丰富的工作流。
构建单 Agent 工作流
Section titled “构建单 Agent 工作流”先从一个范围明确的示例开始:使用 Codex MCP 发布一个小型浏览器游戏。该工作流依赖两个 Agent:
- 游戏设计师:为游戏编写简要说明。
- 游戏开发者:通过调用 Codex MCP 实现游戏。
使用以下代码更新 codex_mcp.py。它保留上面的 MCP 服务器设置,并添加这两个 Agent。
import asyncioimport os
from dotenv import load_dotenv
from agents import Agent, Runner, set_default_openai_apifrom agents.mcp import MCPServerStdio
load_dotenv(override=True)set_default_openai_api(os.getenv("OPENAI_API_KEY"))
async def main() -> None: async with MCPServerStdio( name="Codex CLI", params={ "command": "codex", "args": ["mcp-server"], }, client_session_timeout_seconds=360000, ) as codex_mcp_server: developer_agent = Agent( name="Game Developer", instructions=( "You are an expert in building simple games using basic html + css + javascript with no dependencies. " "Save your work in a file called index.html in the current directory. " "Always call codex with \"approval-policy\": \"never\" and \"sandbox\": \"workspace-write\"." ), mcp_servers=[codex_mcp_server], )
designer_agent = Agent( name="Game Designer", instructions=( "You are an indie game connoisseur. Come up with an idea for a single page html + css + javascript game that a developer could build in about 50 lines of code. " "Format your request as a 3 sentence design brief for a game developer and call the Game Developer coder with your idea." ), model="gpt-5", handoffs=[developer_agent], )
await Runner.run(designer_agent, "Implement a fun new game!")
if __name__ == "__main__": asyncio.run(main())执行脚本:
python codex_mcp.pyCodex 将读取设计师的简要说明,创建 index.html 文件,并将完整游戏写入磁盘。在浏览器中打开生成的文件即可游玩。每次运行都会生成不同的设计,并带有独特的玩法变化和完善度。
扩展为多 Agent 工作流
Section titled “扩展为多 Agent 工作流”现在,将单 Agent 设置转换为经过编排且可追踪的工作流。系统会添加:
- 项目经理:创建共享需求,协调交接,并强制执行护栏。
- 设计师、前端开发者、服务器开发者和测试人员:每个 Agent 都有范围明确的指令和输出文件夹。
创建名为 multi_agent_workflow.py 的新文件:
import asyncioimport os
from dotenv import load_dotenv
from agents import ( Agent, ModelSettings, Runner, WebSearchTool, set_default_openai_api,)from agents.extensions.handoff_prompt import RECOMMENDED_PROMPT_PREFIXfrom agents.mcp import MCPServerStdiofrom openai.types.shared import Reasoning
load_dotenv(override=True)set_default_openai_api(os.getenv("OPENAI_API_KEY"))
async def main() -> None: async with MCPServerStdio( name="Codex CLI", params={"command": "codex", "args": ["mcp-server"]}, client_session_timeout_seconds=360000, ) as codex_mcp_server: designer_agent = Agent( name="Designer", instructions=( f"""{RECOMMENDED_PROMPT_PREFIX}""" "You are the Designer.\n" "Your only source of truth is AGENT_TASKS.md and REQUIREMENTS.md from the Project Manager.\n" "Do not assume anything that is not written there.\n\n" "You may use the internet for additional guidance or research." "Deliverables (write to /design):\n" "- design_spec.md – a single page describing the UI/UX layout, main screens, and key visual notes as requested in AGENT_TASKS.md.\n" "- wireframe.md – a simple text or ASCII wireframe if specified.\n\n" "Keep the output short and implementation-friendly.\n" "When complete, handoff to the Project Manager with transfer_to_project_manager." "When creating files, call Codex MCP with {\"approval-policy\":\"never\",\"sandbox\":\"workspace-write\"}." ), model="gpt-5", tools=[WebSearchTool()], mcp_servers=[codex_mcp_server], )
frontend_developer_agent = Agent( name="Frontend Developer", instructions=( f"""{RECOMMENDED_PROMPT_PREFIX}""" "You are the Frontend Developer.\n" "Read AGENT_TASKS.md and design_spec.md. Implement exactly what is described there.\n\n" "Deliverables (write to /frontend):\n" "- index.html – main page structure\n" "- styles.css or inline styles if specified\n" "- main.js or game.js if specified\n\n" "Follow the Designer’s DOM structure and any integration points given by the Project Manager.\n" "Do not add features or branding beyond the provided documents.\n\n" "When complete, handoff to the Project Manager with transfer_to_project_manager_agent." "When creating files, call Codex MCP with {\"approval-policy\":\"never\",\"sandbox\":\"workspace-write\"}." ), model="gpt-5", mcp_servers=[codex_mcp_server], )
backend_developer_agent = Agent( name="Backend Developer", instructions=( f"""{RECOMMENDED_PROMPT_PREFIX}""" "You are the Backend Developer.\n" "Read AGENT_TASKS.md and REQUIREMENTS.md. Implement the backend endpoints described there.\n\n" "Deliverables (write to /backend):\n" "- package.json – include a start script if requested\n" "- server.js – implement the API endpoints and logic exactly as specified\n\n" "Keep the code as simple and readable as possible. No external database.\n\n" "When complete, handoff to the Project Manager with transfer_to_project_manager_agent." "When creating files, call Codex MCP with {\"approval-policy\":\"never\",\"sandbox\":\"workspace-write\"}." ), model="gpt-5", mcp_servers=[codex_mcp_server], )
tester_agent = Agent( name="Tester", instructions=( f"""{RECOMMENDED_PROMPT_PREFIX}""" "You are the Tester.\n" "Read AGENT_TASKS.md and TEST.md. Verify that the outputs of the other roles meet the acceptance criteria.\n\n" "Deliverables (write to /tests):\n" "- TEST_PLAN.md – bullet list of manual checks or automated steps as requested\n" "- test.sh or a simple automated script if specified\n\n" "Keep it minimal and easy to run.\n\n" "When complete, handoff to the Project Manager with transfer_to_project_manager." "When creating files, call Codex MCP with {\"approval-policy\":\"never\",\"sandbox\":\"workspace-write\"}." ), model="gpt-5", mcp_servers=[codex_mcp_server], )
project_manager_agent = Agent( name="Project Manager", instructions=( f"""{RECOMMENDED_PROMPT_PREFIX}""" """ You are the Project Manager.
Objective: Convert the input task list into three project-root files the team will execute against.
Deliverables (write in project root): - REQUIREMENTS.md: concise summary of product goals, target users, key features, and constraints. - TEST.md: tasks with [Owner] tags (Designer, Frontend, Backend, Tester) and clear acceptance criteria. - AGENT_TASKS.md: one section per role containing: - Project name - Required deliverables (exact file names and purpose) - Key technical notes and constraints
Process: - Resolve ambiguities with minimal, reasonable assumptions. Be specific so each role can act without guessing. - Create files using Codex MCP with {"approval-policy":"never","sandbox":"workspace-write"}. - Do not create folders. Only create REQUIREMENTS.md, TEST.md, AGENT_TASKS.md.
Handoffs (gated by required files): 1) After the three files above are created, hand off to the Designer with transfer_to_designer_agent and include REQUIREMENTS.md and AGENT_TASKS.md. 2) Wait for the Designer to produce /design/design_spec.md. Verify that file exists before proceeding. 3) When design_spec.md exists, hand off in parallel to both: - Frontend Developer with transfer_to_frontend_developer_agent (provide design_spec.md, REQUIREMENTS.md, AGENT_TASKS.md). - Backend Developer with transfer_to_backend_developer_agent (provide REQUIREMENTS.md, AGENT_TASKS.md). 4) Wait for Frontend to produce /frontend/index.html and Backend to produce /backend/server.js. Verify both files exist. 5) When both exist, hand off to the Tester with transfer_to_tester_agent and provide all prior artifacts and outputs. 6) Do not advance to the next handoff until the required files for that step are present. If something is missing, request the owning agent to supply it and re-check.
PM Responsibilities: - Coordinate all roles, track file completion, and enforce the above gating checks. - Do NOT respond with status updates. Just handoff to the next agent until the project is complete. """ ), model="gpt-5", model_settings=ModelSettings( reasoning=Reasoning(effort="medium"), ), handoffs=[designer_agent, frontend_developer_agent, backend_developer_agent, tester_agent], mcp_servers=[codex_mcp_server], )
designer_agent.handoffs = [project_manager_agent] frontend_developer_agent.handoffs = [project_manager_agent] backend_developer_agent.handoffs = [project_manager_agent] tester_agent.handoffs = [project_manager_agent]
task_list = """Goal: Build a tiny browser game to showcase a multi-agent workflow.
High-level requirements:- Single-screen game called "Bug Busters".- Player clicks a moving bug to earn points.- Game ends after 20 seconds and shows final score.- Optional: submit score to a simple backend and display a top-10 leaderboard.
Roles:- Designer: create a one-page UI/UX spec and basic wireframe.- Frontend Developer: implement the page and game logic.- Backend Developer: implement a minimal API (GET /health, GET/POST /scores).- Tester: write a quick test plan and a simple script to verify core routes.
Constraints:- No external database—memory storage is fine.- Keep everything readable for beginners; no frameworks required.- All outputs should be small files saved in clearly named folders."""
result = await Runner.run(project_manager_agent, task_list, max_turns=30) print(result.final_output)
if __name__ == "__main__": asyncio.run(main())运行脚本并查看生成的文件:
python multi_agent_workflow.pyls -R项目经理 Agent 会写入 REQUIREMENTS.md、TEST.md 和 AGENT_TASKS.md,然后协调设计师、前端、服务器和测试 Agent 之间的交接。每个 Agent 都会先在自己的文件夹中写入范围明确的工件,然后将控制权交还给项目经理 Agent。
Codex 会自动记录追踪信息,捕获每条提示词、工具调用和交接。多 Agent 运行完成后,打开 Traces 控制台查看执行时间线。
高级别追踪记录会突出显示项目经理如何在继续之前验证交接。点击各个步骤即可查看提示词、Codex MCP 调用、写入的文件和执行时长。这些详细信息让你可以轻松审计每次交接,并了解工作流如何逐轮演进。 这些追踪记录让你无需额外的检测代码,即可轻松调试工作流中的问题、审计 Agent 行为,并衡量一段时间内的性能。