1# Use Codex with the Agents SDK1# Codex MCP server removal
2 2
3> For the complete documentation index, see [llms.txt](https://learn.chatgpt.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.3> For the complete documentation index, see [llms.txt](https://learn.chatgpt.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.
4 4
5# Running Codex as an MCP server5The `codex mcp-server` command and the standalone `codex-mcp-server` binary have
6been removed. Integrations that launch either command must migrate before
7upgrading Codex. The previous MCP tool reference and Agents SDK examples on this
8page are no longer supported.
6 9
7You can run Codex as an MCP server and connect it from other MCP clients (for example, an agent built with the [OpenAI Agents SDK MCP integration](https://developers.openai.com/api/docs/guides/agents/integrations-observability#mcp)).10## Use the Codex app server
8 11
9To start Codex as an MCP server, you can use the following command:12Use the [Codex app server](https://learn.chatgpt.com/docs/app-server) for integrations that need
13authentication, conversation history, approvals, and streamed agent events.
10 14
11```bash15The app server uses its own [JSON-RPC protocol](https://learn.chatgpt.com/docs/app-server#protocol). It
12codex mcp-server16isn't an MCP server or a drop-in replacement for an MCP client: update your
13```17integration to use the app-server protocol instead of MCP tool calls.
18The app-server command is experimental and isn't supported for production
19workloads.
14 20
15You can launch a Codex MCP server with the [Model Context Protocol Inspector](https://modelcontextprotocol.io/legacy/tools/inspector):21## Connect Codex to MCP tools
16 22
17```bash23Codex continues to support [external MCP servers](https://learn.chatgpt.com/docs/extend/mcp).
18npx @modelcontextprotocol/inspector codex mcp-server24Use `codex mcp` to manage those connections. The removal affects hosting Codex
19```25as an MCP server.
20
21Send a `tools/list` request to see two tools:
22
23**`codex`**: Run a Codex session with the following prompt and configuration overrides:
24
25| Property | Type | Description |
26| ------------------------ | -------- | -------------------------------------------------------------------------------------------------------- |
27| **`prompt`** (required) | `string` | The initial user prompt to start the Codex conversation. |
28| `approval-policy` | `string` | Approval policy for shell commands generated by the model: `untrusted`, `on-request`, and `never`. |
29| `base-instructions` | `string` | The set of instructions to use instead of the default ones. |
30| `compact-prompt` | `string` | Prompt used when compacting the conversation. |
31| `config` | `object` | Individual configuration settings that override what's in `$CODEX_HOME/config.toml`. |
32| `cwd` | `string` | Working directory for the session. If relative, resolved against the server process's current directory. |
33| `developer-instructions` | `string` | Developer instructions injected as a developer-role message. |
34| `model` | `string` | Optional override for the model name (for example, `gpt-5.6-terra`). |
35| `sandbox` | `string` | Sandbox mode: `read-only`, `workspace-write`, or `danger-full-access`. |
36
37**`codex-reply`**: Continue a Codex session by providing the thread ID and prompt. The `codex-reply` tool takes these properties:
38
39| Property | Type | Description |
40| ----------------------------- | ------ | --------------------------------------------------------- |
41| **`prompt`** (required) | string | The next user prompt to continue the Codex conversation. |
42| **`threadId`** (required) | string | The ID of the thread to continue. |
43| `conversationId` (deprecated) | string | Deprecated alias for `threadId` (kept for compatibility). |
44
45Use the `threadId` from `structuredContent.threadId` in the `tools/call` response. Approval prompts (exec/patch) also include `threadId` in their `params` payload.
46
47Example response payload:
48
49```json
50{
51 "structuredContent": {
52 "threadId": "019bbb20-bff6-7130-83aa-bf45ab33250e",
53 "content": "`ls -lah` (or `ls -alh`) — long listing, includes dotfiles, human-readable sizes."
54 },
55 "content": [
56 {
57 "type": "text",
58 "text": "`ls -lah` (or `ls -alh`) — long listing, includes dotfiles, human-readable sizes."
59 }
60 ]
61}
62```
63
64Note modern MCP clients generally report only `"structuredContent"` as the result of a tool call, if present, though the Codex MCP server also returns `"content"` for the benefit of older MCP clients.
65
66# Creating multi-agent workflows
67
68Codex CLI can do far more than run ad-hoc tasks. By exposing the CLI as a [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) server and orchestrating it with the OpenAI Agents SDK, you can create deterministic, reviewable workflows that scale from a single agent to a complete software delivery pipeline.
69
70This guide walks through the same workflow showcased in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook/blob/main/examples/codex/codex_mcp_agents_sdk/building_consistent_workflows_codex_cli_agents_sdk.ipynb). You will:
71
72- launch Codex CLI as a long-running MCP server,
73- build a focused single-agent workflow that produces a playable browser game, and
74- orchestrate a multi-agent team with hand-offs, guardrails, and full traces you can review afterwards.
75
76Before starting, make sure you have:
77
78- [Codex CLI](https://learn.chatgpt.com/docs/codex/cli) installed locally so the `codex` command is available.
79- Python 3.10+ with `pip`.
80- Node.js 18+ if you want to run the MCP Inspector example above.
81- An OpenAI API key stored locally. You can create or manage keys in the [OpenAI dashboard](https://platform.openai.com/account/api-keys).
82
83Create a working directory for the guide and add your API key to a `.env` file:
84
85```bash
86mkdir codex-workflows
87cd codex-workflows
88printf "OPENAI_API_KEY=sk-..." > .env
89```
90
91## Install dependencies
92
93The Agents SDK handles orchestration across Codex, hand-offs, and traces. Install the latest SDK packages:
94
95```bash
96python -m venv .venv
97source .venv/bin/activate
98pip install --upgrade openai openai-agents python-dotenv
99```
100
101Activating a virtual environment keeps the SDK dependencies isolated from the
102 rest of your system.
103
104## Initialize Codex CLI as an MCP server
105
106Start by turning Codex CLI into an MCP server that the Agents SDK can call. The server exposes two tools (`codex()` to start a conversation and `codex-reply()` to continue one) and keeps Codex alive across multiple agent turns.
107
108Create a file called `codex_mcp.py` and add the following:
109
110```python
111import asyncio
112
113from agents import Agent, Runner
114from agents.mcp import MCPServerStdio
115
116
117async def main() -> None:
118 async with MCPServerStdio(
119 name="Codex CLI",
120 params={
121 "command": "codex",
122 "args": ["mcp-server"],
123 },
124 client_session_timeout_seconds=360000,
125 ) as codex_mcp_server:
126 print("Codex MCP server started.")
127 # More logic coming in the next sections.
128 return
129
130
131if __name__ == "__main__":
132 asyncio.run(main())
133```
134
135Run the script once to verify that Codex launches successfully:
136
137```bash
138python codex_mcp.py
139```
140
141The script exits after printing `Codex MCP server started.`. In the next sections you will reuse the same MCP server inside richer workflows.
142
143## Build a single-agent workflow
144
145Let’s start with a scoped example that uses Codex MCP to ship a small browser game. The workflow relies on two agents:
146
1471. **Game Designer**: writes a brief for the game.
1482. **Game Developer**: implements the game by calling Codex MCP.
149
150Update `codex_mcp.py` with the following code. It keeps the MCP server setup from above and adds both agents.
151
152```python
153import asyncio
154import os
155
156from dotenv import load_dotenv
157
158from agents import Agent, Runner, set_default_openai_api
159from agents.mcp import MCPServerStdio
160
161load_dotenv(override=True)
162set_default_openai_api(os.getenv("OPENAI_API_KEY"))
163
164
165async def main() -> None:
166 async with MCPServerStdio(
167 name="Codex CLI",
168 params={
169 "command": "codex",
170 "args": ["mcp-server"],
171 },
172 client_session_timeout_seconds=360000,
173 ) as codex_mcp_server:
174 developer_agent = Agent(
175 name="Game Developer",
176 instructions=(
177 "You are an expert in building simple games using basic html + css + javascript with no dependencies. "
178 "Save your work in a file called index.html in the current directory. "
179 "Always call codex with \"approval-policy\": \"never\" and \"sandbox\": \"workspace-write\"."
180 ),
181 mcp_servers=[codex_mcp_server],
182 )
183
184 designer_agent = Agent(
185 name="Game Designer",
186 instructions=(
187 "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. "
188 "Format your request as a 3 sentence design brief for a game developer and call the Game Developer coder with your idea."
189 ),
190 model="gpt-5",
191 handoffs=[developer_agent],
192 )
193
194 await Runner.run(designer_agent, "Implement a fun new game!")
195
196
197if __name__ == "__main__":
198 asyncio.run(main())
199```
200
201Execute the script:
202
203```bash
204python codex_mcp.py
205```
206
207Codex will read the designer's brief, create an `index.html` file, and write the full game to disk. Open the generated file in a browser to play the result. Every run produces a different design with unique play-style twists and polish.
208
209## Expand to a multi-agent workflow
210
211Now turn the single-agent setup into an orchestrated, traceable workflow. The system adds:
212
213- **Project Manager**: creates shared requirements, coordinates hand-offs, and enforces guardrails.
214- **Designer**, **Frontend Developer**, **Server Developer**, and **Tester**: each with scoped instructions and output folders.
215
216Create a new file called `multi_agent_workflow.py`:
217
218```python
219import asyncio
220import os
221
222from dotenv import load_dotenv
223
224from agents import (
225 Agent,
226 ModelSettings,
227 Runner,
228 WebSearchTool,
229 set_default_openai_api,
230)
231from agents.extensions.handoff_prompt import RECOMMENDED_PROMPT_PREFIX
232from agents.mcp import MCPServerStdio
233from openai.types.shared import Reasoning
234
235load_dotenv(override=True)
236set_default_openai_api(os.getenv("OPENAI_API_KEY"))
237
238
239async def main() -> None:
240 async with MCPServerStdio(
241 name="Codex CLI",
242 params={"command": "codex", "args": ["mcp-server"]},
243 client_session_timeout_seconds=360000,
244 ) as codex_mcp_server:
245 designer_agent = Agent(
246 name="Designer",
247 instructions=(
248 f"""{RECOMMENDED_PROMPT_PREFIX}"""
249 "You are the Designer.\n"
250 "Your only source of truth is AGENT_TASKS.md and REQUIREMENTS.md from the Project Manager.\n"
251 "Do not assume anything that is not written there.\n\n"
252 "You may use the internet for additional guidance or research."
253 "Deliverables (write to /design):\n"
254 "- design_spec.md – a single page describing the UI/UX layout, main screens, and key visual notes as requested in AGENT_TASKS.md.\n"
255 "- wireframe.md – a simple text or ASCII wireframe if specified.\n\n"
256 "Keep the output short and implementation-friendly.\n"
257 "When complete, handoff to the Project Manager with transfer_to_project_manager."
258 "When creating files, call Codex MCP with {\"approval-policy\":\"never\",\"sandbox\":\"workspace-write\"}."
259 ),
260 model="gpt-5",
261 tools=[WebSearchTool()],
262 mcp_servers=[codex_mcp_server],
263 )
264
265 frontend_developer_agent = Agent(
266 name="Frontend Developer",
267 instructions=(
268 f"""{RECOMMENDED_PROMPT_PREFIX}"""
269 "You are the Frontend Developer.\n"
270 "Read AGENT_TASKS.md and design_spec.md. Implement exactly what is described there.\n\n"
271 "Deliverables (write to /frontend):\n"
272 "- index.html – main page structure\n"
273 "- styles.css or inline styles if specified\n"
274 "- main.js or game.js if specified\n\n"
275 "Follow the Designer’s DOM structure and any integration points given by the Project Manager.\n"
276 "Do not add features or branding beyond the provided documents.\n\n"
277 "When complete, handoff to the Project Manager with transfer_to_project_manager_agent."
278 "When creating files, call Codex MCP with {\"approval-policy\":\"never\",\"sandbox\":\"workspace-write\"}."
279 ),
280 model="gpt-5",
281 mcp_servers=[codex_mcp_server],
282 )
283
284 backend_developer_agent = Agent(
285 name="Backend Developer",
286 instructions=(
287 f"""{RECOMMENDED_PROMPT_PREFIX}"""
288 "You are the Backend Developer.\n"
289 "Read AGENT_TASKS.md and REQUIREMENTS.md. Implement the backend endpoints described there.\n\n"
290 "Deliverables (write to /backend):\n"
291 "- package.json – include a start script if requested\n"
292 "- server.js – implement the API endpoints and logic exactly as specified\n\n"
293 "Keep the code as simple and readable as possible. No external database.\n\n"
294 "When complete, handoff to the Project Manager with transfer_to_project_manager_agent."
295 "When creating files, call Codex MCP with {\"approval-policy\":\"never\",\"sandbox\":\"workspace-write\"}."
296 ),
297 model="gpt-5",
298 mcp_servers=[codex_mcp_server],
299 )
300
301 tester_agent = Agent(
302 name="Tester",
303 instructions=(
304 f"""{RECOMMENDED_PROMPT_PREFIX}"""
305 "You are the Tester.\n"
306 "Read AGENT_TASKS.md and TEST.md. Verify that the outputs of the other roles meet the acceptance criteria.\n\n"
307 "Deliverables (write to /tests):\n"
308 "- TEST_PLAN.md – bullet list of manual checks or automated steps as requested\n"
309 "- test.sh or a simple automated script if specified\n\n"
310 "Keep it minimal and easy to run.\n\n"
311 "When complete, handoff to the Project Manager with transfer_to_project_manager."
312 "When creating files, call Codex MCP with {\"approval-policy\":\"never\",\"sandbox\":\"workspace-write\"}."
313 ),
314 model="gpt-5",
315 mcp_servers=[codex_mcp_server],
316 )
317
318 project_manager_agent = Agent(
319 name="Project Manager",
320 instructions=(
321 f"""{RECOMMENDED_PROMPT_PREFIX}"""
322 """
323 You are the Project Manager.
324
325 Objective:
326 Convert the input task list into three project-root files the team will execute against.
327
328 Deliverables (write in project root):
329 - REQUIREMENTS.md: concise summary of product goals, target users, key features, and constraints.
330 - TEST.md: tasks with [Owner] tags (Designer, Frontend, Backend, Tester) and clear acceptance criteria.
331 - AGENT_TASKS.md: one section per role containing:
332 - Project name
333 - Required deliverables (exact file names and purpose)
334 - Key technical notes and constraints
335
336 Process:
337 - Resolve ambiguities with minimal, reasonable assumptions. Be specific so each role can act without guessing.
338 - Create files using Codex MCP with {"approval-policy":"never","sandbox":"workspace-write"}.
339 - Do not create folders. Only create REQUIREMENTS.md, TEST.md, AGENT_TASKS.md.
340
341 Handoffs (gated by required files):
342 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.
343 2) Wait for the Designer to produce /design/design_spec.md. Verify that file exists before proceeding.
344 3) When design_spec.md exists, hand off in parallel to both:
345 - Frontend Developer with transfer_to_frontend_developer_agent (provide design_spec.md, REQUIREMENTS.md, AGENT_TASKS.md).
346 - Backend Developer with transfer_to_backend_developer_agent (provide REQUIREMENTS.md, AGENT_TASKS.md).
347 4) Wait for Frontend to produce /frontend/index.html and Backend to produce /backend/server.js. Verify both files exist.
348 5) When both exist, hand off to the Tester with transfer_to_tester_agent and provide all prior artifacts and outputs.
349 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.
350
351 PM Responsibilities:
352 - Coordinate all roles, track file completion, and enforce the above gating checks.
353 - Do NOT respond with status updates. Just handoff to the next agent until the project is complete.
354 """
355 ),
356 model="gpt-5",
357 model_settings=ModelSettings(
358 reasoning=Reasoning(effort="medium"),
359 ),
360 handoffs=[designer_agent, frontend_developer_agent, backend_developer_agent, tester_agent],
361 mcp_servers=[codex_mcp_server],
362 )
363
364 designer_agent.handoffs = [project_manager_agent]
365 frontend_developer_agent.handoffs = [project_manager_agent]
366 backend_developer_agent.handoffs = [project_manager_agent]
367 tester_agent.handoffs = [project_manager_agent]
368
369 task_list = """
370Goal: Build a tiny browser game to showcase a multi-agent workflow.
371
372High-level requirements:
373- Single-screen game called "Bug Busters".
374- Player clicks a moving bug to earn points.
375- Game ends after 20 seconds and shows final score.
376- Optional: submit score to a simple backend and display a top-10 leaderboard.
377
378Roles:
379- Designer: create a one-page UI/UX spec and basic wireframe.
380- Frontend Developer: implement the page and game logic.
381- Backend Developer: implement a minimal API (GET /health, GET/POST /scores).
382- Tester: write a quick test plan and a simple script to verify core routes.
383
384Constraints:
385- No external database—memory storage is fine.
386- Keep everything readable for beginners; no frameworks required.
387- All outputs should be small files saved in clearly named folders.
388"""
389
390 result = await Runner.run(project_manager_agent, task_list, max_turns=30)
391 print(result.final_output)
392
393
394if __name__ == "__main__":
395 asyncio.run(main())
396```
397
398Run the script and watch the generated files:
399
400```bash
401python multi_agent_workflow.py
402ls -R
403```
404
405The project manager agent writes `REQUIREMENTS.md`, `TEST.md`, and `AGENT_TASKS.md`, then coordinates hand-offs across the designer, frontend, server, and tester agents. Each agent writes scoped artifacts in its own folder before handing control back to the project manager.
406
407## Trace the workflow
408
409Codex automatically records traces that capture every prompt, tool call, and hand-off. After the multi-agent run completes, open the [Traces dashboard](https://platform.openai.com/trace) to inspect the execution timeline.
410
411The high-level trace highlights how the project manager verifies hand-offs before moving forward. Click into individual steps to see prompts, Codex MCP calls, files written, and execution durations. These details make it straightforward to audit every hand-off and understand how the workflow evolved turn by turn.
412These traces make it straightforward to debug workflow hiccups, audit agent behavior, and measure performance over time without requiring extra instrumentation.