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