繁體中文

通過 Agents SDK 使用 Codex

將 Codex CLI 作為 MCP server 接入其他客戶端,並基於 Agents SDK 建置可追蹤的多智能體工作流程

將 Codex CLI 作為 MCP server 執行

你可以將 Codex 作為 MCP server 執行,並從其他 MCP 客戶端連線它,例如通過 OpenAI Agents SDK 的 MCP 整合 建置的智能體客戶端。

要啟動 Codex 作為 MCP server,可使用下面的命令:

codex mcp-server

你也可以結合 Model Context Protocol Inspector 啟動 Codex MCP server:

npx @modelcontextprotocol/inspector codex mcp-server

向服務端傳送 tools/list 後,你會看到兩個工具:

codex

使用下面的提示詞與設定覆蓋項啟動 Codex 會話:

屬性 類型 說明
prompt(必填) string 啟動 Codex 對話時的初始使用者提示詞。
approval-policy string 模型生成 shell 命令時使用的審批策略:untrustedon-requestnever
base-instructions string 用來替代預設指令的一組指令。
compact-prompt string 壓縮對話時使用的提示詞。
config object 覆蓋 $CODEX_HOME/config.toml 中的個別設定項。
cwd string 會話工作目錄。若傳相對路徑,則相對於服務端程序當前目錄解析。
developer-instructions string 以 developer role 訊息注入的開發者指令。
model string 可選的模型名覆蓋,例如 gpt-5.6-terra
sandbox string 沙箱模式:read-onlyworkspace-writedanger-full-access

codex-reply

用於在提供對話執行緒 ID 和提示詞的前提下繼續某個已有 Codex 會話。

屬性 類型 說明
prompt(必填) string 繼續對話時要傳送的下一條使用者提示詞。
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 server 之所以同時返回 "content",主要是為了相容舊版 MCP 客戶端。

建置多智能體工作流程

Codex CLI 遠不止能執行臨時任務。把 CLI 作為 Model Context Protocol(MCP)server 暴露出來,再配合 OpenAI Agents SDK 進行編排,你可以建置出確定性強、便於審查的工作流程,從單智能體一直擴充套件到完整的軟體交付流水線。

本指南對應 OpenAI Cookbook 範例。你將完成:

  • 將 Codex CLI 作為一個長期執行的 MCP server 啟動起來
  • 建置一個聚焦的單智能體工作流程,產出一個可玩的瀏覽器小遊戲
  • 編排一支多智能體團隊,加入交接、護欄和可回看的完整追蹤

開始前,請先準備:

  • 已安裝 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 server

第一步是把 Codex CLI 變成 Agents SDK 可以呼叫的 MCP server。這個 server 會暴露兩個工具: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())

先執行一次,確認能成功啟動:

python codex_mcp.py

指令碼會在列印 Codex MCP server started. 後退出。接下來的範例會在更完整的工作流程裡複用這個 MCP server。

建置單智能體工作流程

先從一個範圍明確的範例開始,用 Codex MCP 交付一個小型瀏覽器遊戲。這個工作流程依賴兩個智能體:

  1. Game Designer:為遊戲撰寫簡短設計說明。
  2. Game Developer:通過呼叫 Codex MCP 來實現這個遊戲。

codex_mcp.py 更新為下面的版本。它會保留前面的 MCP server 設定,並額外加入這兩個智能體。

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.py

Codex 會讀取 Designer 給出的設計說明,建立 index.html,並把完整遊戲寫到磁碟。你可以在瀏覽器中開啟生成的檔案來試玩結果。每次執行都會得到不同的設計,玩法和細節打磨也會有所變化。

擴充套件為多智能體工作流程

現在把單智能體方案擴充套件成一個經過編排、可追蹤的工作流程。系統會新增:

  • Project Manager:建立共享需求、協調交接,並落實護欄約束。
  • DesignerFrontend DeveloperServer DeveloperTester:每個角色都有各自範圍明確的指令和輸出目錄。

建立新檔案 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

在這個流程裡,Project Manager 會先寫出 REQUIREMENTS.mdTEST.mdAGENT_TASKS.md,然後按前置檔案是否存在來控制交接,依次驅動 Designer、Frontend、Backend 和 Tester 這些智能體完成各自產物。

跟蹤工作流程

Codex 會自動記錄追蹤,覆蓋整個工作流程中的每一次提示詞、工具呼叫和交接。

多智能體執行結束後,可以開啟 Traces dashboard 檢視執行時間線。

高層追蹤可以幫助你確認 Project Manager 是否在正確時機檢查了前置檔案併發起下一次交接。點進單個步驟後,則可以看到具體提示詞、Codex MCP 呼叫、寫入的檔案,以及每一步的耗時。

這些細節讓你可以按會話輪次審計每一次交接,並理解整個工作流程是如何演進的。它們也讓除錯流程卡點、審查智能體行為,以及長期衡量效能變得更加直接,而無需額外埋點。


來源:</zh-TW/docs/mcp-server> 更新時間:2026-04-30(UTC)