Türkçe

Codex'i Agents SDK ile kullanma

Codex'i Agents SDK ile kullanma

Çok ajanlı geliştirme iş akışları oluşturmak için Codex'i bir MCP sunucusu olarak çağırın

Codex'i MCP sunucusu olarak çalıştırma

Codex'i bir MCP sunucusu olarak çalıştırabilir ve diğer MCP istemcilerinden bağlanabilirsiniz (örneğin OpenAI Agents SDK MCP entegrasyonu ile oluşturulmuş bir ajan).

Codex'i MCP sunucusu olarak başlatmak için aşağıdaki komutu kullanabilirsiniz:

codex mcp-server

Model Context Protocol Inspector ile bir Codex MCP sunucusu başlatabilirsiniz:

npx @modelcontextprotocol/inspector codex mcp-server

İki aracı görmek için bir tools/list isteği gönderin:

codex: Aşağıdaki istem ve yapılandırma geçersiz kılmalarıyla bir Codex oturumu çalıştırır:

Özellik Tür Açıklama
prompt (gerekli) string Codex görüşmesini başlatan ilk kullanıcı istemi.
approval-policy string Model tarafından oluşturulan kabuk komutlarına yönelik onay politikası: untrusted, on-request ve never.
base-instructions string Varsayılan talimatların yerine kullanılacak talimat kümesi.
compact-prompt string Görüşme sıkıştırılırken kullanılan istem.
config object $CODEX_HOME/config.toml içindeki ayarları geçersiz kılan bağımsız yapılandırma ayarları.
cwd string Oturumun çalışma dizini. Göreliyse sunucu işleminin geçerli dizinine göre çözümlenir.
developer-instructions string Geliştirici rolü mesajı olarak eklenen geliştirici talimatları.
model string Model adı için isteğe bağlı geçersiz kılma (örneğin gpt-5.6-terra).
sandbox string Sandbox modu: read-only, workspace-write veya danger-full-access.

codex-reply: İş parçacığı kimliğini ve istemi sağlayarak bir Codex oturumunu sürdürür. codex-reply aracı şu özellikleri alır:

Özellik Tür Açıklama
prompt (gerekli) string Codex görüşmesini sürdürmek için bir sonraki kullanıcı istemi.
threadId (gerekli) string Sürdürülecek iş parçacığının kimliği.
conversationId (kullanımdan kaldırıldı) string threadId için kullanımdan kaldırılmış takma ad (uyumluluk amacıyla korunur).

tools/call yanıtında, structuredContent.threadId içindeki threadId değerini kullanın. Onay istemleri (exec/patch) de params yüklerinde threadId içerir.

Örnek yanıt yükü:

{
  "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."
    }
  ]
}

Modern MCP istemcilerinin, mevcutsa genellikle bir araç çağrısının sonucu olarak yalnızca "structuredContent" değerini bildirdiğini unutmayın; ancak Codex MCP sunucusu eski MCP istemcileri için "content" değerini de döndürür.

Çok ajanlı iş akışları oluşturma

Codex CLI, geçici görevleri çalıştırmanın çok ötesine geçebilir. CLI'ı bir Model Context Protocol (MCP) sunucusu olarak kullanıma açıp OpenAI Agents SDK ile düzenleyerek tek bir ajandan eksiksiz bir yazılım teslim hattına kadar ölçeklenebilen, deterministik ve incelenebilir iş akışları oluşturabilirsiniz.

Bu kılavuz, OpenAI Cookbook içinde sergilenen iş akışının aynısını adım adım açıklar. Şunları yapacaksınız:

  • Codex CLI'ı uzun süre çalışan bir MCP sunucusu olarak başlatmak,
  • oynanabilir bir tarayıcı oyunu üreten, belirli bir amaca odaklanmış tek ajanlı bir iş akışı oluşturmak ve
  • devirler, koruma önlemleri ve sonradan inceleyebileceğiniz eksiksiz izlerle çok ajanlı bir ekibi düzenlemek.

Başlamadan önce şunların hazır olduğundan emin olun:

  • codex komutunun kullanılabilmesi için Codex CLI yerel olarak yüklü olmalıdır.
  • pip ile birlikte Python 3.10+.
  • Yukarıdaki MCP Inspector örneğini çalıştırmak istiyorsanız Node.js 18+.
  • Yerel olarak depolanmış bir OpenAI API key. Anahtarları OpenAI dashboard üzerinden oluşturabilir veya yönetebilirsiniz.

Kılavuz için bir çalışma dizini oluşturun ve API key'inizi bir .env dosyasına ekleyin:

mkdir codex-workflows
cd codex-workflows
printf "OPENAI_API_KEY=sk-..." > .env

Bağımlılıkları yükleme

Agents SDK; Codex, devirler ve izler arasındaki düzenlemeyi yönetir. En güncel SDK paketlerini yükleyin:

python -m venv .venv
source .venv/bin/activate
pip install --upgrade openai openai-agents python-dotenv

Codex CLI'ı MCP sunucusu olarak başlatma

İlk olarak Codex CLI'ı Agents SDK'nin çağırabileceği bir MCP sunucusuna dönüştürün. Sunucu iki aracı kullanıma açar (bir görüşme başlatmak için codex() ve görüşmeyi sürdürmek için codex-reply()) ve Codex'in birden fazla ajan turu boyunca çalışmasını sağlar.

codex_mcp.py adlı bir dosya oluşturup aşağıdakileri ekleyin:

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'in başarıyla başlatıldığını doğrulamak için betiği bir kez çalıştırın:

python codex_mcp.py

Betik, Codex MCP server started. yazdırdıktan sonra sonlanır. Sonraki bölümlerde aynı MCP sunucusunu daha kapsamlı iş akışlarında yeniden kullanacaksınız.

Tek ajanlı bir iş akışı oluşturma

Codex MCP kullanarak küçük bir tarayıcı oyunu teslim eden, kapsamı belirlenmiş bir örnekle başlayalım. İş akışı iki ajana dayanır:

  1. Oyun Tasarımcısı: oyun için kısa bir tasarım özeti yazar.
  2. Oyun Geliştiricisi: Codex MCP'yi çağırarak oyunu uygular.

codex_mcp.py dosyasını aşağıdaki kodla güncelleyin. Bu kod, yukarıdaki MCP sunucusu kurulumunu korur ve iki ajanı da ekler.

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())

Betiği çalıştırın:

python codex_mcp.py

Codex tasarımcının özetini okuyacak, bir index.html dosyası oluşturacak ve oyunun tamamını diske yazacaktır. Ortaya çıkan oyunu oynamak için oluşturulan dosyayı bir tarayıcıda açın. Her çalıştırma, kendine özgü oynanış değişiklikleri ve iyileştirmeler içeren farklı bir tasarım üretir.

Çok ajanlı bir iş akışına genişletme

Şimdi tek ajanlı kurulumu düzenlenmiş ve izlenebilir bir iş akışına dönüştürün. Sistem şunları ekler:

  • Proje Yöneticisi: ortak gereksinimler oluşturur, devirleri koordine eder ve koruma önlemlerini uygular.
  • Tasarımcı, Ön Uç Geliştiricisi, Sunucu Geliştiricisi ve Test Uzmanı: her biri belirli kapsamlı talimatlara ve çıktı klasörlerine sahiptir.

multi_agent_workflow.py adlı yeni bir dosya oluşturun:

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())

Betiği çalıştırın ve oluşturulan dosyaları izleyin:

python multi_agent_workflow.py
ls -R

Proje yöneticisi ajanı REQUIREMENTS.md, TEST.md ve AGENT_TASKS.md dosyalarını yazar; ardından tasarımcı, ön uç, sunucu ve test uzmanı ajanlar arasındaki devirleri koordine eder. Her ajan, denetimi proje yöneticisine geri devretmeden önce kendi klasörüne kapsamı belirlenmiş yapıtlar yazar.

İş akışını izleme

Codex her istemi, araç çağrısını ve devri yakalayan izleri otomatik olarak kaydeder. Çok ajanlı çalıştırma tamamlandıktan sonra yürütme zaman çizelgesini incelemek için Traces dashboard sayfasını açın.

Üst düzey iz, proje yöneticisinin ilerlemeden önce devirleri nasıl doğruladığını gösterir. İstemleri, Codex MCP çağrılarını, yazılan dosyaları ve yürütme sürelerini görmek için ayrı ayrı adımları açın. Bu ayrıntılar, her devri denetlemeyi ve iş akışının her turda nasıl geliştiğini anlamayı kolaylaştırır. Bu izler; ek araçlandırma gerektirmeden iş akışındaki aksaklıkları gidermeyi, ajan davranışını denetlemeyi ve zaman içindeki performansı ölçmeyi kolaylaştırır.