將 Codex 與 Agents SDK 配合使用
將 Codex 與 Agents SDK 配合使用
將 Codex 作為 MCP 伺服器呼叫,以建置多智能體開發工作流程
將 Codex 作為 MCP 伺服器執行
你可以將 Codex 作為 MCP 伺服器執行,並從其他 MCP 客戶端連線它(例如,使用 OpenAI Agents SDK MCP 整合建置的智能體)。
若要將 Codex 作為 MCP 伺服器啟動,可以使用以下命令:
codex mcp-server你可以使用 Model Context Protocol Inspector 啟動 Codex MCP 伺服器:
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 |
作為開發者角色訊息注入的開發者指令。 |
model |
string |
可選的模型名稱覆蓋項(例如 gpt-5.6-terra)。 |
sandbox |
string |
沙箱模式:read-only、workspace-write 或 danger-full-access。 |
codex-reply:通過提供執行緒 ID 和提示詞繼續 Codex 會話。codex-reply 工具接受以下屬性:
| 屬性 | 類型 | 說明 |
|---|---|---|
prompt(必需) |
string | 用於繼續 Codex 對話的下一個使用者提示詞。 |
threadId(必需) |
string | 要繼續的執行緒 ID。 |
conversationId(已棄用) |
string | threadId 的已棄用別名(為相容性而保留)。 |
使用 tools/call 響應中 structuredContent.threadId 的 threadId。審批提示(exec/patch)的 params 有效載荷中也包含 threadId。
響應有效載荷範例:
{
"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 客戶端。
建立多智能體工作流程
Codex CLI 的能力遠不止執行臨時任務。通過將 CLI 公開為 Model Context Protocol(MCP)伺服器,並使用 OpenAI Agents SDK 對其進行編排,你可以建立確定且可審查的工作流程,規模可從單個智能體擴充套件到完整的軟體交付流水線。
本指南將逐步介紹 OpenAI Cookbook 中展示的同一工作流程。你將:
- 將 Codex CLI 作為長期執行的 MCP 伺服器啟動;
- 建置一個專注的單智能體工作流程,用於生成可玩的瀏覽器遊戲;以及
- 編排一個包含交接、護欄和完整軌跡的多智能體團隊,供你事後審查。
開始之前,請確保你已具備:
- 已在本機安裝 Codex CLI,以便使用
codex命令。 - Python 3.10+ 和
pip。 - 如果要執行上面的 MCP Inspector 範例,需要 Node.js 18+。
- 儲存在本機的 OpenAI API key。你可以在 OpenAI 控制面板中建立或管理金鑰。
為本指南建立一個工作目錄,並將 API key 新增到 .env 檔案:
mkdir codex-workflows
cd codex-workflows
printf "OPENAI_API_KEY=sk-..." > .env安裝依賴項
Agents SDK 負責 Codex、交接和軌跡之間的編排。安裝最新的 SDK 軟體包:
python -m venv .venv
source .venv/bin/activate
pip install --upgrade openai openai-agents python-dotenv
將 Codex CLI 初始化為 MCP 伺服器
首先,將 Codex CLI 轉換為 Agents SDK 可以呼叫的 MCP 伺服器。該伺服器公開兩個工具(使用 codex() 啟動對話,使用 codex-reply() 繼續對話),並讓 Codex 在多個智能體輪次間保持執行。
建立名為 codex_mcp.py 的檔案並新增以下內容:
import asyncio
from agents import Agent, Runner
from 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 伺服器。
建置單智能體工作流程
我們先從一個範圍明確的範例開始,使用 Codex MCP 交付一個小型瀏覽器遊戲。該工作流程依賴兩個智能體:
- 遊戲設計師:編寫遊戲簡介。
- 遊戲開發者:通過呼叫 Codex MCP 實現遊戲。
使用以下程式碼更新 codex_mcp.py。它會保留上述 MCP 伺服器設定,並新增這兩個智能體。
import asyncio
import os
from dotenv import load_dotenv
from agents import Agent, Runner, set_default_openai_api
from 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 檔案,並將完整遊戲寫入磁碟。在瀏覽器中開啟生成的檔案即可遊玩。每次執行都會生成不同的設計,具有獨特的玩法變化和打磨細節。
擴充套件為多智能體工作流程
現在,將單智能體設定轉換為經過編排且可追蹤的工作流程。系統會新增:
- 專案經理:建立共享需求、協調交接並實施護欄。
- 設計師、前端開發者、伺服器開發者和測試人員:各自擁有範圍明確的指令和輸出資料夾。
建立名為 multi_agent_workflow.py 的新檔案:
import asyncio
import 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_PREFIX
from agents.mcp import MCPServerStdio
from 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.py
ls -R專案經理智能體會寫入 REQUIREMENTS.md、TEST.md 和 AGENT_TASKS.md,然後協調設計師、前端、伺服器和測試智能體之間的交接。每個智能體都會先在自己的資料夾中寫入範圍明確的工件,然後再將控制權交還給專案經理。
追蹤工作流程
Codex 會自動記錄軌跡,捕獲每個提示詞、工具呼叫和交接。多智能體執行完成後,開啟軌跡控制面板檢視執行時間線。
高層級軌跡會突出顯示專案經理如何在繼續推進之前驗證交接。點選各個步驟可檢視提示詞、Codex MCP 呼叫、寫入的檔案和執行時長。這些詳細資訊讓你能夠輕鬆審計每次交接,並瞭解工作流程逐輪演變的過程。 這些軌跡無需額外檢測機制,即可輕鬆除錯工作流程故障、審計智能體行為,並持續衡量效能。