For the complete documentation index, see llms.txt. Markdown versions of documentation pages are available by appending .md to the page URL.
Primary navigation

Codex App Server

Embed Codex into your product with the app-server protocol

Codex app-server is the interface Codex uses to power rich clients (for example, the Codex VS Code extension). Use it when you want a deep integration inside your own product: authentication, conversation history, approvals, and streamed agent events. The app-server implementation is open source in the Codex GitHub repository (openai/codex/codex-rs/app-server). See the Open Source page for the full list of open-source Codex components.

If you are automating jobs or running Codex in CI, use the Codex SDK instead.

Connect the CLI terminal UI

Remote terminal UI mode lets you run app-server on one machine and connect the Codex CLI terminal interface from another. Start a WebSocket listener:

codex app-server --listen ws://127.0.0.1:4500

Then connect the terminal UI:

codex --remote ws://127.0.0.1:4500

For a non-local connection, configure WebSocket authentication and put the connection behind TLS. Store the bearer token in an environment variable and pass its name instead of putting the token on the command line:

export CODEX_REMOTE_TOKEN="$(cat "$HOME/.codex/app-server-token")"
codex --remote wss://remote-host:4500 \
  --remote-auth-token-env CODEX_REMOTE_TOKEN

The --remote option accepts ws://, wss://, unix://, and unix://PATH endpoints. Use plain WebSockets only for localhost or an SSH port-forwarded connection.

Connect a remote Code Mode host

By default, app-server starts a local Code Mode host. To use a remote host instead, pass its secure WebSocket URL:

codex app-server --code-mode-host wss://code-mode.example.com/host

--code-mode-host controls the outbound connection from app-server to its Code Mode host. It doesn’t change --listen, which controls how clients connect to app-server. Every thread in the same app-server process shares the selected Code Mode host connection.

Use wss:// for a remote host. Use ws:// only for a localhost or SSH-forwarded connection. The app-server command and WebSocket transport are experimental and aren’t supported for production workloads.

Protocol

Like MCP, codex app-server supports bidirectional communication using JSON-RPC 2.0 messages (with the "jsonrpc":"2.0" header omitted on the wire).

Supported transports:

  • stdio (--listen stdio://, default): newline-delimited JSON (JSONL).
  • websocket (--listen ws://IP:PORT, experimental and unsupported): one JSON-RPC message per WebSocket text frame.
  • Unix socket (--listen unix:// or --listen unix://PATH): WebSocket connections over Codex’s default app-server control socket or a custom Unix socket path, using the standard HTTP Upgrade handshake.
  • off (--listen off): don’t expose a local transport.

When you run with --listen ws://IP:PORT, the same listener also serves basic HTTP health probes:

  • GET /readyz returns 200 OK once the listener accepts new connections.
  • GET /healthz returns 200 OK when the request doesn’t include an Origin header.
  • Requests with an Origin header are rejected with 403 Forbidden.

WebSocket transport is experimental and unsupported. Local listeners such as ws://127.0.0.1:PORT are appropriate for localhost and SSH port-forwarding workflows. Non-loopback WebSocket listeners currently allow unauthenticated connections by default during rollout, so configure WebSocket auth before exposing one remotely.

Supported WebSocket auth flags:

  • --ws-auth capability-token --ws-token-file /absolute/path
  • --ws-auth capability-token --ws-token-sha256 HEX
  • --ws-auth signed-bearer-token --ws-shared-secret-file /absolute/path

For signed bearer tokens, you can also set --ws-issuer, --ws-audience, and --ws-max-clock-skew-seconds. Clients present the credential as Authorization: Bearer <token> during the WebSocket handshake, and app-server enforces auth before JSON-RPC initialize.

Prefer --ws-token-file over passing raw bearer tokens on the command line. Use --ws-token-sha256 only when the client keeps the raw high-entropy token in a separate local secret store; the hash is only a verifier, and clients still need the original token.

In WebSocket mode, app-server uses bounded queues. When request ingress is full, the server rejects new requests with JSON-RPC error code -32001 and message "Server overloaded; retry later." Clients should retry with an exponentially increasing delay and jitter.

Message schema

Requests include method, params, and id:

{ "method": "thread/start", "id": 10, "params": { "model": "gpt-5.6-terra" } }

Responses echo the id with either result or error:

{ "id": 10, "result": { "thread": { "id": "thr_123" } } }
{ "id": 10, "error": { "code": 123, "message": "Something went wrong" } }

Notifications omit id and use only method and params:

{ "method": "turn/started", "params": { "turn": { "id": "turn_456" } } }

You can generate a TypeScript schema or a JSON Schema bundle from the CLI. Each output is specific to the Codex version you ran, so the generated artifacts match that version exactly:

codex app-server generate-ts --out ./schemas
codex app-server generate-json-schema --out ./schemas

Getting started

  1. Start the server with codex app-server (default stdio transport), codex app-server --listen ws://127.0.0.1:4500 (TCP WebSocket), or codex app-server --listen unix:// (default Unix socket).
  2. Connect a client over the selected transport, then send initialize followed by the initialized notification.
  3. Start a thread and a turn, then keep reading notifications from the active transport stream.

Example (Node.js / TypeScript):

import { spawn } from "node:child_process";
import readline from "node:readline";

const proc = spawn("codex", ["app-server"], {
  stdio: ["pipe", "pipe", "inherit"],
});
const rl = readline.createInterface({ input: proc.stdout });

const send = (message: unknown) => {
  proc.stdin.write(`${JSON.stringify(message)}\n`);
};

let threadId: string | null = null;

rl.on("line", (line) => {
  const msg = JSON.parse(line) as any;
  console.log("server:", msg);

  if (msg.id === 1 && msg.result?.thread?.id && !threadId) {
    threadId = msg.result.thread.id;
    send({
      method: "turn/start",
      id: 2,
      params: {
        threadId,
        input: [{ type: "text", text: "Summarize this repo." }],
      },
    });
  }
});

send({
  method: "initialize",
  id: 0,
  params: {
    clientInfo: {
      name: "my_product",
      title: "My Product",
      version: "0.1.0",
    },
  },
});
send({ method: "initialized", params: {} });
send({ method: "thread/start", id: 1, params: { model: "gpt-5.6-terra" } });

Core primitives

  • Thread: A conversation between a user and the Codex agent. Threads contain turns.
  • Turn: A single user request and the agent work that follows. Turns contain items and stream incremental updates.
  • Item: A unit of input or output (user message, agent message, command runs, file change, tool call, and more).

Use the thread APIs to create, list, or archive conversations. Drive a conversation with turn APIs and stream progress via turn notifications.

Lifecycle overview

  • Initialize once per connection: Immediately after opening a transport connection, send an initialize request with your client metadata, then emit initialized. The server rejects any request on that connection before this handshake.
  • Start (or resume) a thread: Call thread/start for a new conversation, thread/resume to continue an existing one, or thread/fork to branch history into a new thread id.
  • Begin a turn: Call turn/start with the target threadId and user input. Optional fields override model, personality, cwd, sandbox policy, and more.
  • Steer an active turn: Call turn/steer to append user input to the currently in-flight turn without creating a new turn.
  • Stream events: After turn/start, keep reading notifications on stdout: thread/archived, thread/unarchived, item/started, item/completed, item/agentMessage/delta, tool progress, and other updates.
  • Finish the turn: The server emits turn/completed with final status when the model finishes or after a turn/interrupt cancellation.

Initialization

Clients must send a single initialize request per transport connection before invoking any other method on that connection, then acknowledge with an initialized notification. Requests sent before initialization receive a Not initialized error, and repeated initialize calls on the same connection return Already initialized.

The server returns the user agent string it will present to upstream services plus platformFamily and platformOs values that describe the runtime target. Set clientInfo to identify your integration.

initialize.params.capabilities also supports these client capabilities:

  • optOutNotificationMethods - exact notification method names to suppress for this connection. Matching is exact (no wildcards or prefixes); unknown names are accepted and ignored.
  • requestAttestation - opt into the server-initiated attestation/generate request. Desktop hosts that provide upstream attestation respond with an opaque { "token": "..." } value.
  • mcpServerOpenaiFormElicitation - allow downstream MCP servers to send the OpenAI extended-form variant of mcpServer/elicitation/request.

Important: Use clientInfo.name to identify your client for the OpenAI Compliance Logs Platform. If you are developing a new Codex integration intended for enterprise use, please contact OpenAI to get it added to a known clients list. For more context, see the Codex logs reference.

Example (from the Codex VS Code extension):

{
  "method": "initialize",
  "id": 0,
  "params": {
    "clientInfo": {
      "name": "codex_vscode",
      "title": "Codex VS Code Extension",
      "version": "0.1.0"
    }
  }
}

Example with notification opt-out:

{
  "method": "initialize",
  "id": 1,
  "params": {
    "clientInfo": {
      "name": "my_client",
      "title": "My Client",
      "version": "0.1.0"
    },
    "capabilities": {
      "experimentalApi": true,
      "optOutNotificationMethods": ["thread/started", "item/agentMessage/delta"]
    }
  }
}

Experimental API opt-in

Some app-server methods and fields are intentionally gated behind experimentalApi capability.

  • Omit capabilities (or set experimentalApi to false) to stay on the stable API surface, and the server rejects experimental methods/fields.
  • Set capabilities.experimentalApi to true to enable experimental methods and fields.
{
  "method": "initialize",
  "id": 1,
  "params": {
    "clientInfo": {
      "name": "my_client",
      "title": "My Client",
      "version": "0.1.0"
    },
    "capabilities": {
      "experimentalApi": true
    }
  }
}

If a client sends an experimental method or field without opting in, app-server rejects it with:

<descriptor> requires experimentalApi capability

API overview

  • thread/start - create a new thread; emits thread/started and automatically subscribes you to turn/item events for that thread.
  • thread/resume - reopen an existing thread by id so later turn/start calls append to it.
  • thread/fork - fork a thread into a new thread id by copying stored history. Pass lastTurnId to copy history through that turn and omit later turns, or ephemeral: true to create an in-memory fork. Emits thread/started for the new thread; returned threads include forkedFromId when available.
  • thread/read - read a stored thread by id without resuming it; set includeTurns to return full turn history. Returned thread objects include runtime status.
  • thread/list - page through stored thread logs; supports cursor-based pagination plus modelProviders, sourceKinds, archived, isPinned, cwd, useStateDbOnly, searchTerm, and experimental parentThreadId or ancestorThreadId filters. Returned thread objects include runtime status.
  • thread/turns/list - experimental; page through a stored thread’s turn history without resuming it. itemsView controls whether turn items are omitted, summarized, or fully loaded.
  • thread/items/list - experimental; page through persisted thread items, optionally restricted to one turnId. The active thread store must support item pagination.
  • thread/loaded/list - list the thread ids currently loaded in memory.
  • thread/name/set - set or update a thread’s user-facing name for a loaded thread or a persisted rollout; emits thread/name/updated.
  • thread/goal/set - set the goal for a thread; emits thread/goal/updated.
  • thread/goal/get - read the current goal for a thread.
  • thread/goal/clear - clear the goal for a thread; emits thread/goal/cleared.
  • thread/metadata/update - patch SQLite-backed stored thread metadata, including persisted gitInfo and isPinned.
  • thread/archive - move a thread’s log file into the archived directory and attempt to archive spawned descendant thread logs that aren’t already archived; returns {} on success and emits thread/archived for each archived thread.
  • thread/delete - permanently delete a persisted active or archived thread and any spawned descendant threads; returns {} on success and emits thread/deleted for each deleted thread.
  • thread/unsubscribe - unsubscribe this connection from thread turn/item events. If this was the last subscriber, the server unloads the thread after a no-subscriber inactivity grace period and emits thread/closed.
  • thread/unarchive - restore an archived thread rollout back into the active sessions directory; returns the restored thread and emits thread/unarchived.
  • thread/status/changed - notification emitted when a loaded thread’s runtime status changes.
  • thread/compact/start - trigger conversation history compaction for a thread; returns {} immediately while progress streams via turn/* and item/* notifications.
  • thread/shellCommand - run a user-initiated shell command against a thread. This runs outside the sandbox with full access and doesn’t inherit the thread sandbox policy.
  • thread/backgroundTerminals/clean - stop all running background terminals for a thread (experimental; requires capabilities.experimentalApi).
  • thread/backgroundTerminals/list - list running background terminals for a loaded thread (experimental; requires capabilities.experimentalApi).
  • thread/backgroundTerminals/terminate - terminate one running background terminal by app-server processId (experimental; requires capabilities.experimentalApi).
  • thread/rollback - deprecated; drop the last N turns from the in-memory context and persist a rollback marker; returns the updated thread.
  • turn/start - add user input to a thread and begin Codex generation; responds with the initial turn and streams events. For collaborationMode, settings.developer_instructions: null means “use built-in instructions for the selected mode.”
  • thread/inject_items - append raw Responses API items to a loaded thread’s model-visible history without starting a user turn.
  • turn/steer - append user input to the active in-flight turn for a thread; returns the accepted turnId.
  • turn/interrupt - request cancellation of an in-flight turn; success is {} and the turn ends with status: "interrupted".
  • review/start - kick off the Codex reviewer for a thread; emits enteredReviewMode and exitedReviewMode items.
  • command/exec - run a single command under the server sandbox without starting a thread/turn.
  • command/exec/write - write stdin bytes to a running command/exec session or close stdin.
  • command/exec/resize - resize a running PTY-backed command/exec session.
  • command/exec/terminate - stop a running command/exec session.
  • command/exec/outputDelta (notify) - emitted for base64-encoded stdout/stderr chunks from a streaming command/exec session.
  • process/spawn - start an explicit process session outside Codex’s sandbox (experimental; requires capabilities.experimentalApi).
  • process/writeStdin - write stdin bytes to a running process/spawn session or close stdin (experimental).
  • process/resizePty - resize a running PTY-backed process session (experimental).
  • process/kill - terminate a running process session (experimental).
  • process/outputDelta and process/exited (notify) - emitted for streaming process output and process exit status (experimental).
  • model/list - list available models (set includeHidden: true to include entries with hidden: true) with effort options, optional upgrade, and inputModalities.
  • modelProvider/capabilities/read - read provider capability bounds for model/provider combinations.
  • experimentalFeature/list - list feature flags with lifecycle stage metadata and cursor pagination.
  • experimentalFeature/enablement/set - patch in-memory runtime settings for supported feature keys such as apps and plugins.
  • environment/info - experimental; connect to a configured execution environment and return its shell plus default working directory.
  • permissionProfile/list - list beta permission profiles and whether effective requirements allow them, with cursor pagination.
  • collaborationMode/list - list collaboration mode presets (experimental, no pagination).
  • skills/list - list skills for one or more cwd values (supports forceReload and optional perCwdExtraUserRoots).
  • skills/extraRoots/set - replace the process-level extra roots used to discover standalone skills without persisting them.
  • skills/changed (notify) - emitted when watched local skill files change.
  • hooks/list - list discovered lifecycle hooks for one or more cwd values.
  • marketplace/add - add a remote plugin marketplace and persist it into the user’s marketplace config.