Home › Articles

Run Claude Code, Codex and Cursor headless in CI and scripts

Updated 2026-11-15

In short: all three tools run without a human: claude -p, codex exec and agent -p (Cursor CLI) take a prompt, print the final answer and exit. Authenticate with an API key kept in a CI secret, not a login. Give each run the least it needs: Claude Code with --bare and --allowedTools, Codex with a read-only or workspace-write sandbox, Cursor with permissions deny rules instead of a blanket --force. In GitHub Actions, Claude and Codex have official actions; Cursor documents an install step plus the CLI. Treat everything the agent reads from a pull request as untrusted.

This page puts the non-interactive modes side by side and gives one working workflow per tool. Every flag below comes from the official docs, checked on 2026-11-15. We parsed the three workflow files and the config as YAML and JSON, but did not run them on GitHub or against live accounts, so adjust prompts, tool lists and paths to your repository and test on a branch first.

Side by side

Claude CodeCodexCursor CLI
Headless commandclaude -p "prompt"codex exec "prompt"agent -p "prompt"
Machine-readable output--output-format json or stream-json; --json-schema--json (JSON Lines); --output-schema with -o file--output-format json or stream-json
Writes files by default?Calls that need approval are denied unless allowed with --allowedTools, a permission mode or a hookNo: read-only sandboxEdits inside the workspace run; other actions needing approval are rejected
How to widen it--allowedTools, --permission-mode acceptEdits--sandbox workspace-writepermissions.allow, or --force
API key variableANTHROPIC_API_KEYCODEX_API_KEYCURSOR_API_KEY
GitHub Actionsanthropics/claude-code-action@v1openai/codex-action@v1Install script, then agent -p in a step
Cost and runtime limits--max-turns, --max-budget-usdWorkflow timeouts, --ephemeral for no session filesWorkflow timeouts
Where it can run besides CIAny shellAny shellAny shell; Cloud Agents via the Cursor GitHub app

Claude Code: claude -p

Add -p to any claude command to run it non-interactively. It exits with code 0 on success and a non-zero code on failure, so a script can branch on the status. Piping works as you would expect: cat build-error.txt | claude -p 'concisely explain the root cause of this build error'. Piped stdin is capped at 10MB; past that Claude Code exits with an error, so write big inputs to a file and name the path in the prompt.

Use --bare in CI

Without --bare, claude -p loads what an interactive session would: your hooks, skills, plugins, MCP servers, auto memory and CLAUDE.md, including a project's .claude/settings.json hooks and .mcp.json servers, with no trust dialog and no per-server approval, even in a folder you have never trusted. --bare skips all of that so the run is the same on every machine, and the docs call it the recommended mode for scripted calls (and say it will become the default for -p in a future release). Bare mode never reads OAuth credentials or the system keychain, so set ANTHROPIC_API_KEY. Pass the context you do want with flags such as --append-system-prompt-file, --settings or --mcp-config. Hooks passed that way still do not run in bare mode, so don't use it for a run that needs them. If your repo's rules live in CLAUDE.md, remember bare mode does not load it.

Permissions when nobody can answer

A -p run cannot stop and ask. A call that needs approval is denied unless something approves it: a --allowedTools entry, a permission rule, a PermissionRequest hook or --permission-prompt-tool. With Claude Code v2.1.302 or later, -p runs start in Manual mode when nothing sets a permission mode. Choose the baseline deliberately:

The longer discussion of prompts is in stopping agents asking permission.

Structured output, cost and exit behavior

The GitHub Action

In GitHub Actions, anthropics/claude-code-action@v1 runs Claude Code for you. If the workflow has no prompt input it runs in interactive mode and waits for @claude in a comment; with a prompt it runs in automation mode on any event, including a schedule, and by default writes results to the workflow run log. The quickest setup is /install-github-app from Claude Code, which installs the GitHub App, stores the key as the ANTHROPIC_API_KEY repository secret and opens a pull request with the workflow. By hand you pass the key as anthropic_api_key, or a subscription token (from claude setup-token) as claude_code_oauth_token, and the job needs id-token: write for the default GitHub App authentication. CLI flags go in claude_args. With a plain-text prompt Claude has no shell or GitHub API access until you grant tools there. The action also checks who triggered the run: users need write access to the repo on issue and PR events, and bot actors are rejected unless listed in allowed_bots. On public repos GitHub withholds secrets from fork pull request runs, so a review like this one runs only on branches in the same repository.

This workflow reviews each pull request with read-only tools and a turn cap, and keeps results in the run log:

# .github/workflows/claude-pr-review.yml
# Claude Code in automation mode: a prompt input, so it runs without waiting for an @claude mention.
name: Claude PR review
on:
  pull_request:
    types: [opened, synchronize, ready_for_review, reopened]

jobs:
  review:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    concurrency:
      group: claude-review-${{ github.event.pull_request.number }}
      cancel-in-progress: true
    permissions:
      contents: read
      pull-requests: read
      id-token: write   # needed for the action's default GitHub App authentication
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            Review the changes in this pull request against the base branch.
            Report bugs, missing tests and risky changes, one finding per line
            as path:line followed by the problem. If there are none, say so.
          claude_args: |
            --max-turns 8
            --allowedTools "Read,Bash(git diff *),Bash(git log *)"

If you would rather call the CLI yourself, the npm package is npm install -g @anthropic-ai/claude-code@latest and needs Node.js 22 or later; then run claude --bare -p in a step with the key in that step's env.

Codex: codex exec

codex exec "prompt" streams progress to stderr and prints only the final agent message to stdout, so codex exec "generate release notes for the last 10 commits" | tee release-notes.md works. If stdin is piped and you also pass a prompt, the prompt is the instruction and the piped content is extra context. --ephemeral keeps session files off disk, and codex exec resume --last "fix the race conditions you found" continues a previous run in a two-stage pipeline. Codex insists on a Git repository; --skip-git-repo-check overrides that only when you are sure the environment is safe.

Sandbox and approvals in CI

For how the sandbox treats the network, see when the sandbox blocks npm install.

JSON output

--json turns stdout into a JSON Lines stream of events such as thread.started, turn.completed, turn.failed, item.* and error. For a stable final shape, give --output-schema ./schema.json a JSON Schema and write the result with -o ./out.json (--output-last-message), which also still prints it.

Keep the API key away from your code

OpenAI's guidance is stricter than "put it in a secret". Do not set OPENAI_API_KEY or CODEX_API_KEY as a job-level environment variable in a workflow that checks out or runs repository code: build scripts, tests, dependency hooks or a compromised action in the same job can read it. Outside GitHub Actions, set CODEX_API_KEY inline for the one invocation, as in CODEX_API_KEY=<key> codex exec --json "triage open bug reports". For GitHub Actions, use openai/codex-action@v1 instead of installing and authenticating the CLI yourself: it installs Codex, starts a Responses API proxy for the key and runs codex exec under the permissions you set. Use API keys rather than ChatGPT-managed login in CI; the docs reserve that for trusted runners and say not to use it for public or open-source repositories.

The GitHub Action

Inputs map to codex exec options: prompt or prompt-file (exactly one), sandbox, output-file, codex-args (for example ["--ephemeral"] or --output-schema), codex-version to pin the CLI, plus model and effort. The last Codex message is the final-message output. Safety inputs matter: safety-strategy defaults to drop-sudo, which removes sudo for the rest of the job; unprivileged-user runs Codex as a named account; Windows runners need unsafe. Only users with write access can trigger it unless you list others in allow-users or allow-bots. The docs warn that read-only alone does not protect secrets, and advise running Codex as the last step of a job and sanitizing pull request text before it reaches the prompt. This workflow reviews a PR read-only, then a second job with only the write permissions it needs posts the comment, so the job holding the key never gets write access:

# .github/workflows/codex-pr-review.yml
# Codex via openai/codex-action: the action installs the CLI, keeps the key behind a proxy,
# and runs codex exec with the sandbox you choose.
name: Codex PR review
on:
  pull_request:
    types: [opened, synchronize, reopened]

jobs:
  codex:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    permissions:
      contents: read
    outputs:
      final_message: ${{ steps.run_codex.outputs.final-message }}
    steps:
      - uses: actions/checkout@v5
        with:
          ref: refs/pull/${{ github.event.pull_request.number }}/merge
          fetch-depth: 0
          persist-credentials: false
      - name: Run Codex
        id: run_codex
        uses: openai/codex-action@v1
        with:
          openai-api-key: ${{ secrets.OPENAI_API_KEY }}
          prompt-file: .github/codex/prompts/review.md
          sandbox: read-only
          output-file: codex-output.md
      - uses: actions/upload-artifact@v4
        with:
          name: codex-review
          path: codex-output.md

  post_feedback:
    runs-on: ubuntu-latest
    needs: codex
    if: needs.codex.outputs.final_message != ''
    permissions:
      issues: write
      pull-requests: write
    steps:
      - uses: actions/github-script@v7
        env:
          CODEX_FINAL_MESSAGE: ${{ needs.codex.outputs.final_message }}
        with:
          github-token: ${{ github.token }}
          script: |
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.payload.pull_request.number,
              body: process.env.CODEX_FINAL_MESSAGE,
            });

Put your review instructions in .github/codex/prompts/review.md. OpenAI's non-interactive page also has a longer pattern that reproduces a CI failure, saves Codex's changes as a patch artifact, and lets a separate job open the pull request.

Cursor: agent -p

The Cursor CLI's command is agent, and -p (--print) is print mode for scripts. Install it with curl https://cursor.com/install -fsS | bash (macOS, Linux, WSL) or the PowerShell line in the docs for Windows. Output is text by default; --output-format json prints one object when the run finishes, with the answer in result, and stream-json emits newline-delimited events (add --stream-partial-output for deltas). On failure the process exits non-zero and writes the error to stderr with no JSON, so check the exit code before parsing. --output-format works only with -p.

Approvals in print mode

Print mode follows the same approval rules as an interactive session but cannot stop to ask. Without --force, file edits inside the workspace, allowlisted or sandboxed shell commands, and anything covered by permissions.allow run; writes outside the workspace or to protected paths such as .vscode/ and .git/hooks/, and shell commands, MCP tools and web fetches that are not allowed, are rejected. --force (alias --yolo) runs every action without approval except what permissions.deny and team policies block. A CLI config with approvalMode set to unrestricted does the same without the flag. Cursor recommends the restricted approach for production CI: let the agent change files, and do commits, pushes and PR comments in ordinary deterministic steps. Enforce it with permission tokens in .cursor/cli.json (or ~/.cursor/cli-config.json), where deny rules beat allow rules:

{
  "permissions": {
    "allow": [
      "Read(**/*.md)",
      "Write(README.md)",
      "Write(docs/**/*)"
    ],
    "deny": [
      "Shell(git)",
      "Shell(gh)",
      "Read(.env*)",
      "Write(.env*)",
      "Write(package.json)"
    ]
  }
}

Team admins can switch on Disable CLI headless mode, which makes agent -p exit with an error. The docs call this a usage policy rather than a security boundary. Other useful flags from the parameter reference: --sandbox enabled|disabled, --trust (trust the workspace without prompting, headless only), --approve-mcps, --workspace <path>, --model, and --mode plan|ask.

Authentication and GitHub Actions

Create a user API key in the Cursor Dashboard under API Keys, store it as a repository secret (gh secret set CURSOR_API_KEY --repo OWNER/REPO or the GitHub UI), and expose it as CURSOR_API_KEY on the step that runs the agent. --api-key also works but puts the key on the command line, so prefer the variable. Cursor's docs show the basic setup as an install step that appends $HOME/.cursor/bin to $GITHUB_PATH, then agent -p "..." with the secret in env. This workflow follows the restricted pattern: the agent edits Markdown, and the job saves the diff as an artifact for a human or a later job to apply:

# .github/workflows/cursor-docs-fix.yml
# Cursor CLI in print mode, "restricted autonomy": the agent only edits files;
# CI does everything else. Pair with .cursor/cli.json (cursor-cli.json in this article).
name: Cursor docs fix
on:
  workflow_dispatch:

jobs:
  fix:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v6
        with:
          persist-credentials: false
      - name: Install Cursor CLI
        run: |
          curl https://cursor.com/install -fsS | bash
          echo "$HOME/.cursor/bin" >> "$GITHUB_PATH"
      - name: Run Cursor Agent
        env:
          CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }}
        run: |
          agent -p "Fix typos and broken Markdown formatting in README.md and docs/. \
          Only modify files in the working directory. Do NOT create branches, \
          commit, push or comment; a later step handles that."
      - name: Save the diff
        run: |
          git diff --binary > cursor-docs.patch
          git diff --stat
      - uses: actions/upload-artifact@v4
        with:
          name: cursor-docs-patch
          path: cursor-docs.patch

Cursor's other route is not the CLI: the Cursor GitHub app connects your repositories so Cloud Agents and Bugbot can work on them, which an admin sets up from the dashboard Integrations page.

Gotchas that bite in CI

SymptomLikely cause
Claude run is denied a commandNothing approved it. Add it to --allowedTools with the right pattern, or pick a permission mode
Claude behaves differently in CI than locallyWithout --bare it loads whatever hooks, MCP servers and CLAUDE.md that machine has
Claude bare run says it is not authenticatedBare mode ignores OAuth and the keychain; set ANTHROPIC_API_KEY
Codex run changes nothingRead-only sandbox by default; add --sandbox workspace-write
Codex refuses to startNot inside a Git repository (checkout first), or --skip-git-repo-check
Codex action fails after dropping sudoPermission errors on the checkout; grant write access before the action or use unprivileged-user
Cursor run rejects a shell commandNot on the allowlist; add it to permissions.allow rather than reaching for --force
Cursor JSON parse failsThe run failed: no JSON is printed on failure, only stderr and a non-zero exit
Job hangs or overrunsSet a workflow timeout-minutes; for Claude also --max-turns and --max-budget-usd

Treat PR text as untrusted

A headless agent reads whatever you hand it: pull request titles, issue bodies, commit messages and files from a fork. OpenAI's checklist says to sanitize those inputs against prompt injection and to review HTML comments and hidden text before they reach Codex, and the same advice applies to the other two tools. Run on trusted events, give the job only the permissions it needs, and keep write steps in a separate job from the one holding the API key, as the Codex example above does. For keeping secrets out of the agent's reach in the first place, see stopping agents reading .env files.

A command cheat sheet

The documented entry points in one script (read-only runs unless noted). It passes bash -n but needs the three CLIs and keys to run:

#!/usr/bin/env bash
# The documented non-interactive entry points, side by side. Run from a git repository.
# Each one prints a final answer to stdout; check the exit status in CI.
set -euo pipefail

# Claude Code: --bare skips hooks, plugins, MCP, auto memory and CLAUDE.md (needs ANTHROPIC_API_KEY)
claude --bare -p "Summarize README.md" --allowedTools "Read" --max-turns 5 --output-format json | jq -r '.result'

# Codex: read-only sandbox by default; the final message goes to stdout, progress to stderr
codex exec --ephemeral --sandbox read-only "summarize the repository structure" | tee summary.md

# Codex, edits allowed inside the workspace, structured final answer
codex exec --sandbox workspace-write "Extract project metadata" --output-schema ./schema.json -o ./project-metadata.json

# Cursor CLI: print mode; anything that needs approval is rejected unless allowed (no --force)
agent -p --output-format json "What does this codebase do?" | jq -r '.result'

A ten-minute CI checklist

  1. Pick the tool and run it once locally with the same flags, in a throwaway branch.
  2. Create an API key for CI only and store it as a repository secret. Never commit it, and never put it in a job-level env next to code you do not control.
  3. Start with the narrowest permissions: Claude --allowedTools, Codex read-only, Cursor permissions.deny rules and no --force.
  4. Add a timeout, a turn or budget cap where the tool has one, and concurrency so a busy PR does not start ten runs.
  5. Check the exit status, and for JSON output check the field you rely on exists.
  6. Have the agent propose (comment, artifact, patch), and let a normal job commit or merge.

FAQ

How do I run Claude Code non-interactively?

Add -p (or --print) to claude, for example claude -p "Summarize README.md". It prints the answer and exits with code 0 on success and a non-zero code when the run fails. In CI add --bare so it skips hooks, plugins, MCP servers, auto memory and CLAUDE.md, and set ANTHROPIC_API_KEY, because bare mode never reads your subscription login. Use --output-format json for a result with metadata, and --max-turns to cap the run.

Does codex exec change files in CI by default?

No. codex exec runs in a read-only sandbox unless you pass --sandbox workspace-write (edits inside the workspace) or --sandbox danger-full-access (broader access, which OpenAI says to use only in a controlled environment such as an isolated runner or container). The old --full-auto flag is no longer supported.

Which environment variable holds the API key for each tool?

Claude Code reads ANTHROPIC_API_KEY (the GitHub Action takes it as the anthropic_api_key input). Codex reads CODEX_API_KEY for codex exec, and openai/codex-action takes openai-api-key. The Cursor CLI reads CURSOR_API_KEY, or --api-key. In GitHub Actions, keep each one in a repository secret and expose it only to the step that needs it.

Is --force safe in CI for Cursor's CLI?

Only with narrow permissions. In print mode the agent edits workspace files and runs allowlisted commands without --force, and rejects anything that would need approval. --force (or --yolo) runs every action without approval except what permissions.deny and team policies block, so put deny rules for git, gh and secrets in .cursor/cli.json first, or have the agent only edit files and let later CI steps commit.

How do I get JSON out of each tool?

Claude Code: --output-format json returns an object with the text in result, and with --json-schema the data is in structured_output. Codex: --json streams JSON Lines events, and --output-schema with -o writes a schema-shaped final answer to a file. Cursor: --output-format json prints one object with the answer in result; on failure it exits non-zero and prints no JSON.

Sources

Official docs, checked 2026-11-15.

Get the free rules sampler + new tips by email

Confirm your email and we'll send you straight to the sampler download. Then one short email every two weeks covering tool format changes (Cursor, Claude Code, Codex, Windsurf, Copilot), new rules and kit updates. No spam.

We store only your email, with our email provider Resend. See the privacy policy.

Unsubscribe anytime from any email. Rather skip email? Get the sampler on GitHub or download the zip directly.