← Blog
CodexAI agentsSandboxes

Codex app-server: run Codex on a remote machine and drive it from your app

Yura Dubinin
Yura Dubinin

The Codex app-server is the JSON-RPC server inside the Codex CLI that the Codex VS Code extension and other rich clients use to drive the agent. You start it with codex app-server, send initialize, open a thread with thread/start, send work with turn/start, and read the stream of events that comes back. The same server can listen on a WebSocket behind a token, and that is how you run Codex on a remote machine and drive it from your own app.

For the remote machine I use Lizard (lizard.build). It is our product, so weigh that. With Lizard Sandboxes, lizard sandbox create -t codex -s small starts a Firecracker microVM with its own kernel and the Codex CLI already installed. The outputs in this guide come from such a sandbox, tested on 22 November 2026 with Codex CLI 0.171.0, and I say so wherever I did not run a command.

What is the Codex app-server?

The Codex app-server is a subcommand of the Codex CLI, codex app-server, that exposes the Codex agent over JSON-RPC 2.0. OpenAI's documentation describes it as "the interface Codex uses to power rich clients (for example, the Codex VS Code extension)" and recommends it for a deep integration: authentication, conversation history, approvals and streamed agent events (Codex App Server docs, read 22 November 2026).

The protocol has three primitives. A thread is a conversation. A turn is one user request and the agent work that follows it. An item is one unit inside a turn: a user message, an agent message, a command run, a file change, a tool call.

Messages travel as one JSON object per line over stdio by default. The "jsonrpc":"2.0" field is left out on the wire. The server also listens on a Unix socket (--listen unix://) or a WebSocket (--listen ws://IP:PORT), and OpenAI marks the WebSocket transport as experimental and unsupported.

codex app-server generate-json-schema --out ./schemas on Codex CLI 0.171.0 wrote a schema with 110 client request methods, 87 server notifications and 10 server requests. A first turn needs three of the requests (initialize, thread/start, turn/start), the initialized notification and the turn/completed event.

Codex app-server vs codex exec vs the Codex SDK: which do you need?

Use the app-server when a person watches the agent and answers its questions in your interface. Use codex exec or the Codex SDK when a script runs the agent and only needs the result. OpenAI draws the same line: "If you are automating jobs or running Codex in CI, use the Codex SDK instead."

codex app-servercodex execCodex SDK
What it isA long-lived JSON-RPC serverOne non-interactive runA library over the CLI
How you talk to itRequests and notifications over stdio, a Unix socket or a WebSocketA prompt in, text or JSONL events out (--json)thread.run() in TypeScript, thread_start() in Python
Approvals in the middle of a turnYes, the server asks your clientNo, you set the sandbox and approval settings before the runSet when you create the thread
Sign-in and account methodsYes (account/read, account/login/start)Uses the stored login or CODEX_API_KEYUses the stored login or CODEX_API_KEY
Good forA web UI, an IDE plugin, a chat bot, a mobile clientCI steps, cron jobs, shell scriptsCalling Codex from backend code

Sources: OpenAI's app-server, non-interactive mode and Codex SDK pages, read 22 November 2026.

The SDKs sit on top of the same CLI. The TypeScript SDK (@openai/codex-sdk) "spawns the CLI and exchanges JSONL events over stdin/stdout", according to its README. The Python SDK (openai-codex) "controls the local Codex app-server over JSON-RPC", according to OpenAI's SDK page. So in Python the SDK already is an app-server client. For scripted runs, see our guide to codex exec.

How do you start the app-server and send a first turn?

Start codex app-server as a child process, send initialize and the initialized notification, then thread/start and turn/start. Each request has a method, params and an id, and the response repeats the id. The server rejects everything before the handshake: in my test, a thread/list sent first came back as {"error":{"code":-32600,"message":"Not initialized"}}.

This client has no dependencies and runs on Node 18 or later. Save it as client.mjs:

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

const prompt = process.argv[2] ?? "Reply with the single word: pong";
const proc = spawn("codex", ["app-server"], { stdio: ["pipe", "pipe", "inherit"] });
const rl = readline.createInterface({ input: proc.stdout });

let nextId = 0;
const pending = new Map();
const send = (msg) => proc.stdin.write(JSON.stringify(msg) + "\n");
const request = (method, params = {}) =>
  new Promise((resolve, reject) => {
    const id = nextId++;
    pending.set(id, { resolve, reject });
    send({ method, id, params });
  });

let turnDone;
const turnCompleted = new Promise((resolve) => (turnDone = resolve));

rl.on("line", (line) => {
  const msg = JSON.parse(line);
  // A response to one of our requests: an id and no method.
  if (msg.id !== undefined && msg.method === undefined) {
    const p = pending.get(msg.id);
    pending.delete(msg.id);
    return msg.error ? p.reject(msg.error) : p.resolve(msg.result);
  }
  // A request from the server: an id and a method. Approvals arrive here.
  if (msg.id !== undefined) {
    console.log("server asks:", msg.method, JSON.stringify(msg.params.command ?? ""));
    return send({ id: msg.id, result: { decision: "decline" } });
  }
  // A notification: a method and no id.
  if (msg.method === "item/agentMessage/delta") process.stdout.write(msg.params.delta);
  else if (msg.method === "item/completed") console.log("\nitem:", msg.params.item.type);
  else if (msg.method === "error") console.log("error:", JSON.stringify(msg.params.error));
  else if (msg.method === "turn/completed") turnDone(msg.params.turn);
});

const init = await request("initialize", {
  clientInfo: { name: "my_client", title: "My Client", version: "0.1.0" },
});
console.log("server:", init.userAgent);
send({ method: "initialized", params: {} });

const { account } = await request("account/read", { refreshToken: false });
console.log("account:", account ? account.type : "not signed in");

const { thread } = await request("thread/start", { cwd: process.cwd() });
console.log("thread:", thread.id);

const { turn } = await request("turn/start", {
  threadId: thread.id,
  input: [{ type: "text", text: prompt }],
});
console.log("turn:", turn.id, turn.status);

const done = await turnCompleted;
console.log("turn finished:", done.status, done.error ? JSON.stringify(done.error) : "");
proc.stdin.end();
rl.close();

I ran it in a sandbox on Lizard with node client.mjs. The sandbox had no OpenAI sign-in, so this is what an unauthenticated server does (the server's log lines on stderr, the repeated retry lines and the long request IDs are cut):

server: my_client/0.171.0 (Debian 12.0.0; x86_64) unknown (my_client; 0.1.0)
account: not signed in
thread: 01a20267-ccb5-7893-bfbc-28698e0f30eb
turn: 01a20267-cce1-78d0-bb89-63ca5b66074f inProgress

item: userMessage
error: {"message":"Reconnecting... 2/5","codexErrorInfo":{"responseStreamDisconnected":{"httpStatusCode":401}}, ...}
...
turn finished: failed {"message":"unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, ...","codexErrorInfo":{"httpConnectionFailed":{"httpStatusCode":401}}, ...}

The handshake and the thread work without a login. The turn fails when Codex calls the model, after retries that arrive as error notifications with willRetry: true, so check account/read before you send a turn. I did not run a signed-in turn for this guide. With a login, OpenAI's docs say the same client receives the answer as item/agentMessage/delta notifications and a turn/completed with status completed.

A new thread starts with tight defaults. The thread/start response in my test reported approvalPolicy: "on-request" and a readOnly sandbox with no network access. Pass approvalPolicy, sandboxPolicy, model or cwd on turn/start to change that; the new values stay as the defaults for later turns on the thread. Our post on Codex sandbox and --yolo explains the modes.

How do approvals and events work?

Events are notifications, and approvals are requests that the server sends to your client. The protocol is bidirectional for that reason: your client has to answer messages as well as send them.

After turn/start, the server streams notifications until turn/completed. OpenAI's docs list the ones a client needs most:

  • turn/started and turn/completed, where the final status is completed, interrupted or failed.
  • item/started and item/completed for every item. The docs say to treat item/completed as the authoritative state.
  • item/agentMessage/delta for streamed answer text and item/commandExecution/outputDelta for command output.
  • turn/diff/updated with the unified diff of every file change in the turn, and turn/plan/updated when the agent changes its plan.

An approval arrives as a message with both a method and an id. For a command, the order in the docs is: item/started with the pending commandExecution item, then the request item/commandExecution/requestApproval, then your response, then serverRequest/resolved, then item/completed with status completed, failed or declined. File changes follow the same order with item/fileChange/requestApproval.

Your response is a result with a decision. The schema generated by Codex CLI 0.171.0 accepts accept, acceptForSession, decline and cancel for both kinds. decline lets the agent continue the turn, and cancel interrupts it. A command approval can also carry acceptWithExecpolicyAmendment, which allows matching commands from then on. The client above declines everything.

To stop a turn, send turn/interrupt with the threadId and turnId. In my test the response was {} and the turn ended with turn/completed and status interrupted. To add input to a running turn without starting a new one, send turn/steer with expectedTurnId.

How do you run Codex on a remote server?

Run the app-server on the remote machine with a WebSocket listener and a token, sign Codex in on that machine, and connect from your client over TLS. I tested the setup below on Lizard Sandboxes.

Create the machine and check the version:

lizard sandbox create -t codex -s small --timeout 3000000
lizard sandbox exec <id> -- codex --version

A Small sandbox has 2 vCPU and 4 GB of RAM and costs $0.0162 an hour, billed per second (Lizard pricing, 22 November 2026). The --timeout matters: without it the Lizard CLI gives a new sandbox 5 minutes. On the 7-day trial every sandbox is deleted after 1 hour at most, so a server that stays up longer needs a paid Lizard Pro plan ($19 a month with $19 of usage included). The codex template had Codex CLI 0.159.2 on the day I tested. The client above ran on it unchanged, and npm i -g @openai/codex@latest brought it to 0.171.0.

Start the listener with a capability token:

mkdir -p ~/.codex
openssl rand -hex 32 > ~/.codex/app-server-token
chmod 600 ~/.codex/app-server-token
codex app-server --listen ws://0.0.0.0:4500 \
  --ws-auth capability-token --ws-token-file ~/.codex/app-server-token

Clients send the token as Authorization: Bearer <token> in the WebSocket handshake. In my test a connection with no token or a wrong token was rejected with HTTP 401, and the right token got the initialize response. The listener also serves GET /readyz and GET /healthz (both returned 200), and a request with an Origin header got 403.

One detail differs from OpenAI's docs. The docs say non-loopback listeners "currently allow unauthenticated connections by default during rollout". Codex CLI 0.171.0 did not: without --ws-auth it exited with "refusing to start non-loopback websocket listener 0.0.0.0:4600 without auth". Treat the token as required either way.

The listener speaks plain ws://, so put TLS in front of it. On Lizard, lizard sandbox expose <id> 4500 gives the port an HTTPS URL. The port stays private: requests need the sandbox's access token, which the printed URL carries as lizard_token and --json returns as accessToken. Two checks then apply in a row: without Lizard's token (the X-Lizard-Access-Token header) the URL returned 401, with it but without the Codex bearer token the handshake still returned 401, and with both it returned 101 and the server answered initialize over wss://. On your own server, an SSH tunnel or a reverse proxy with TLS does the same job. The Codex terminal UI can connect to the same listener with codex --remote wss://host:4500 --remote-auth-token-env CODEX_REMOTE_TOKEN, a command from OpenAI's docs that I did not run.

How do you sign in on a headless machine?

Use the device-code flow. From a shell, OpenAI's auth docs give codex login --device-auth. From your client, send account/login/start with {"type":"chatgptDeviceCode"}. In my test the server answered with verificationUrl: "https://auth.openai.com/codex/device" and a userCode, and it sends account/login/completed when the user finishes. The same docs say device-code login has to be enabled in the ChatGPT security settings first, and that an API key goes in with printenv OPENAI_API_KEY | codex login --with-api-key. I ran neither shell command. Codex caches the login in ~/.codex/auth.json or the OS credential store, and OpenAI says to treat that file like a password.

Read OpenAI's note on this before you build a product. The app-server docs say a local or open-source application that uses app-server authentication "can continue using it", and then: "App-server authentication has never been permitted for commercial or hosted services." For those, OpenAI points to Sign in with ChatGPT.

How do you isolate users and keep the server running?

Give each user their own machine. One app-server holds one Codex home with one login and all of its threads, and thread/shellCommand runs "outside the sandbox with full access", in the words of the docs. Two users on one server share files, history and credentials. A microVM per user keeps them apart, and a 30-minute session on a Small sandbox costs $0.0081 at $0.0162 an hour. If those users are your customers, read OpenAI's sign-in note above first: it rules out app-server authentication for commercial and hosted services.

A server started over stdio dies with its client. To keep one running, start the WebSocket listener under systemd, tmux or nohup, or use the built-in daemon: codex app-server daemon start reported "status":"started" with a control socket at ~/.codex/app-server-control/app-server-control.sock in my test. Threads are stored on disk, so a client that reconnects can call thread/list and thread/resume. Both worked after the interrupted turn above.

If you would rather not write a client, Lizard Sandboxes can run Codex for you. lizard agents login chatgpt connects your ChatGPT sign-in to the sandbox's project with a device code, or lizard agents add openai stores an OpenAI API key instead. Then lizard sandbox prompt <id> --agent codex "add a health check endpoint and test it" runs Codex in the sandbox and streams what it does. Add -c <conversation-id> to continue a conversation, and stop a run with lizard sandbox interrupt <id>. The Lizard agents CLI page lists the credentials each agent accepts. I checked these flags with --help and did not run a Codex prompt this way, because the test project had no ChatGPT sign-in.

For hosted options that need no server at all, compare Codex Cloud and other background coding agents.

FAQ

Is the Codex app-server stable? Partly. codex --help in Codex CLI 0.171.0 labels app-server as experimental, and OpenAI's docs call the WebSocket transport "experimental and unsupported". Methods behind capabilities.experimentalApi are rejected unless the client opts in during initialize. Generate the schema for the version you run with codex app-server generate-ts --out ./schemas and pin that version.

Can I use the Codex app-server from Python? Yes. OpenAI's Python SDK (pip install openai-codex, Python 3.10 or later) controls the app-server over JSON-RPC. Any language that can read and write lines of JSON on a child process can also speak the protocol directly.

What happened to codex mcp-server? OpenAI's Codex SDK page says the codex mcp-server command and the standalone codex-mcp-server binary have been removed, and that existing integrations should use the Codex app-server.

Does the app-server run commands without asking? That depends on the approval policy and sandbox policy of the thread. One method needs no thread and no login: command/exec runs a single command under the server sandbox, and in my test it returned exitCode: 0 and the command's stdout.

How do I connect to Codex from my phone? Run the app-server on a machine that stays on and put a web client in front of its token-protected WebSocket listener. Codex CLI 0.171.0 also has an experimental codex remote-control command with start, stop and pair subcommands, which I did not test.

Build with AI. Ship with Lizard

You don't need a platform team to go live. Your whole cloud, one CLI command away.

Start 7-day trial
Services
—
Add-ons
—
Deployments
—
Sandbox starts
—

We use cookies for essential site functionality and analytics. See our Cookie Policy.