FAQ15 min read

Headless Mode and CI/CD - FAQ

SFEIR Institute

TL;DR

Claude Code's headless mode lets you run AI tasks directly in your CI/CD pipelines without human interaction. With the `-p` flag, you launch prompts in a single command, retrieve the output as text, JSON, or streaming, and automate complete workflows in GitHub Actions or GitLab CI. This FAQ guide answers practical questions for integrating Claude Code into your automation chains.

Claude Code's headless mode lets you run AI tasks directly in your CI/CD pipelines without human interaction. With the -p flag, you launch prompts in a single command, retrieve the output as text, JSON, or streaming, and automate complete workflows in GitHub Actions or GitLab CI. This FAQ guide answers practical questions for integrating Claude Code into your automation chains.

Claude Code's headless mode is a non-interactive execution mode that allows you to use the AI agent from the command line without a graphical terminal. This mode is the foundational building block for integrating Claude Code into any continuous integration and deployment pipeline.

Many teams using Claude Code in enterprise leverage headless mode for CI/CD workflows. The -p flag transforms Claude Code into a scriptable tool, capable of processing a prompt and returning a result usable by other tools.

SFEIR Institute trainings

Claude Code Training

1 day · Fundamentals

View program

AI-Augmented Developer

2 days · Intermediate

View program

How to launch Claude Code in a single command with the -p flag?

Use the -p flag followed by your prompt in quotes to run Claude Code without an interactive interface.

The -p flag (for print) sends a single prompt to Claude Code and displays the response directly on standard output. This mode disables all user interaction, making it compatible with shell scripts, CI/CD pipelines, and cron jobs.

$ claude -p "Explain the main() function in src/index.ts"

The command returns the result in plain text by default. The process terminates automatically after the response, with an exit code of 0 on success. Response time varies with prompt complexity and the selected model.

To go further on available options, check out the complete headless mode command reference which details each flag.

FlagEffectExample
-p "prompt"Runs a single promptclaude -p "Summarize this file"
-p + --output-format jsonReturns structured JSONclaude -p "List the bugs" --output-format json
-p + --verboseShows full turn-by-turn outputclaude -p "Analyze" --verbose
-p + --max-turns 3Limits conversation turnsclaude -p "Refactor" --max-turns 3

Key takeaway: the -p flag turns Claude Code into a standard Unix command, compatible with pipes and shell redirections.

How to integrate Claude Code into GitHub Actions?

Add a step in your YAML workflow that installs Claude Code and runs a prompt with the -p flag.

The integration relies on three elements: installing Claude Code via npm, configuring the API key as a GitHub secret, and calling it in headless mode. Here is a working workflow:

name: Claude Code Review
on: [pull_request]

jobs:
 review:
 runs-on: ubuntu-latest
 steps:
 - uses: actions/checkout@v4
 - uses: actions/setup-node@v4
 with:
 node-version: '22'
 - run: npm install -g @anthropic-ai/claude-code
 - name: Code Review
 env:
 ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
 run: |
 claude -p "Review the changes in this PR and list potential bugs" \
 --output-format json > review.json

This workflow runs on each pull request in approximately 30 seconds for an average-sized PR (less than 500 modified lines). You can check the tips for optimizing your headless pipelines to reduce execution times.

For managing permissions and security of your API tokens in a CI context, always store the key in the repository secrets and never in the source code.

Key takeaway: a complete GitHub Actions integration requires Node.js 22+, the npm package, and an API key as a secret. Three lines of configuration are enough.

What output formats are available in headless mode?

Claude Code offers three output formats in headless mode: text, json, and stream-json.

The default format is text, which returns the raw response on stdout. The json format wraps the response in a structured object with metadata. The stream-json format sends tokens one by one in JSON Lines (NDJSON) format, ideal for real-time processing.

# Text format (default)
$ claude -p "Summarize this file" --output-format text

# Structured JSON format
$ claude -p "List the TODOs" --output-format json

# Streaming JSON Lines format
$ claude -p "Generate the docs" --output-format stream-json
FormatUse caseStreaming behavior
textSimple scripts, logsOutput emitted once the response is complete
jsonProgrammatic parsingSingle JSON object at the end of the response
stream-jsonReal-time UI, progress barsTokens streamed incrementally as they are generated

The json format returns an object containing fields such as result, model, and total_cost_usd (the call cost). The json format is commonly used in CI/CD integrations to parse the result with jq or a Python script.

# Extract only the result with jq
$ claude -p "Analyze this code" --output-format json | jq -r '.result'

To understand how to leverage these formats in programmatic multi-turn sessions, check out the dedicated headless mode guide.

Key takeaway: choose text for quick debugging, json for programmatic integration, and stream-json for real-time feedback.

How to create programmatic multi-turn sessions?

Use the --resume flag combined with -p to maintain context between multiple successive calls.

A multi-turn session allows you to chain multiple prompts while preserving conversation history. Claude Code stores the context and automatically reloads it when you resume a session with --resume.

# First call: analyze the code (retrieve the session_id)
RESULT=$(claude -p "Analyze the files in src/" --output-format json)
SESSION=$(echo "$RESULT" | jq -r '.session_id')

# Second call: previous context is preserved
$ claude -p "What bugs did you find in the previous analysis?" \
 --resume "$SESSION"

# Third call: request a fix
$ claude -p "Fix the most critical bug" --resume "$SESSION"

The maximum context size depends on the model you select, and token consumption grows with each turn as history accumulates. Keep sessions focused so you stay within the selected model's context window.

Concretely, multi-turn sessions are useful for multi-step workflows: analysis, correction, verification. You will find additional examples in the headless mode cheatsheet with ready-to-copy scripts.

The session mechanism also works in GitHub Actions by passing the session_id between workflow steps via the JSON output.

Key takeaway: the --resume flag transforms isolated calls into a continuous conversation, ideal for multi-step pipelines.

How to parse Claude Code's JSON output in a script?

Combine the --output-format json flag with a parsing tool like jq to extract structured data.

Claude Code's JSON output returns a documented structure with fields such as result (the text response), model (the model used), and total_cost_usd (the call cost), along with a per-model cost breakdown.

# Extract the text result
$ claude -p "Summarize this PR" --output-format json | jq -r '.result'

# Extract the call cost
$ claude -p "Analyze this code" --output-format json | jq '.total_cost_usd'

In Python, parsing is straightforward:

import subprocess
import json

result = subprocess.run(
 ["claude", "-p", "List the modified files", "--output-format", "json"],
 capture_output=True, text=True
)
data = json.loads(result.stdout)
print(f"Response: {data['result']}")
print(f"Cost: {data['total_cost_usd']}$")

For developers discovering the Claude Code command line, the installation and first launch FAQ covers the technical prerequisites. The JSON structure is identical whether you run Claude Code locally or in a Docker container.

Key takeaway: the JSON output follows a documented structure. Use jq in bash or json.loads() in Python to extract fields such as result and total_cost_usd.

What are the advanced CI/CD use cases with Claude Code?

Advanced use cases include automated code review, test generation, automated documentation, and security vulnerability detection.

Teams that automate code review with Claude Code can offload repetitive review work and catch issues earlier in the pipeline. Here are five common use cases:

Use caseCI triggerTypical benefit
Code reviewPull requestFaster, more consistent first-pass review
Test generationPush to branchCoverage for functions that lack tests
Auto documentationMerge to mainUp-to-date docs without manual effort
Vulnerability detectionScheduled (nightly)Earlier detection of security issues
Code migrationManualAssisted bulk refactors and migrations

Concretely, a unit test generation pipeline looks like this:

$ claude -p "Generate unit tests for functions without coverage \
 in src/utils/" --output-format json \
 --max-turns 5 | jq -r '.result' > tests/generated.test.ts

To understand how Claude Code reasons about your source code, check out the article on agentic coding and its principles. Advanced workflows often combine headless mode with the CLAUDE.md memory system to provide project context with each execution.

Key takeaway: automated code review and test generation are two of the highest-value CI/CD use cases, freeing reviewers from repetitive checks.

How to handle errors and return codes in headless mode?

Check the process exit code: 0 indicates success, any other code signals an error.

Claude Code in headless mode follows standard Unix conventions for return codes. An exit code of 0 means the prompt was processed successfully, while any non-zero exit code signals a failure (for example an error or an exceeded input limit). The documentation does not assign a fixed meaning to each non-zero value, so treat anything other than 0 as a failure to handle.

$ claude -p "Analyze this file" --output-format json
if [ $? -eq 0 ]; then
 echo "Success"
else
 echo "Error code: $?"
 exit 1
fi

In a GitHub Actions pipeline, use continue-on-error: true if you want the workflow to continue despite a Claude Code error. Well-formulated prompts and clear context generally reduce the rate of failed runs.

In every case, rely on the process exit code as the primary failure signal: a non-zero code means the run failed. Systematically test the exit code before processing the result, and inspect stderr and the captured output for diagnostic details. The essential slash commands include useful debug options for diagnosing recurring errors.

Exit codeMeaningRecommended action
0SuccessProcess the response
Any non-zero codeFailure (error, exceeded input limit)Check the prompt, logs, stderr, and ANTHROPIC_API_KEY

Note: exit code 124 comes from the external GNU timeout wrapper when you guard a call with it (for example timeout 60 claude -p "..."), not from claude itself.

Key takeaway: always handle the return code in your scripts. An unchecked $? can mask silent errors in your pipeline.

How to limit API costs in a CI/CD pipeline?

Configure the --max-turns flag and monitor the total_cost_usd field of the JSON output to control your budget.

Each headless mode call consumes billed tokens, so the per-call cost depends on the prompt size, the model, and current pricing. The --max-turns flag limits the number of agent iterations, which caps consumption.

# Limit to 3 turns maximum
$ claude -p "Refactor src/utils.ts" --max-turns 3 --output-format json

# Extract the cost for monitoring
$ claude -p "Review this PR" --output-format json | jq '.total_cost_usd'

Here is how to approach budgeting your pipelines:

  • Estimate cost from the actual token usage reported in total_cost_usd, not from fixed assumptions
  • Heavier tasks (security analysis, large migrations) cost more than a focused code review
  • Cap iterations with --max-turns to keep per-call cost predictable
  • Multiply your measured per-call cost by your weekly run count to project the trend

SFEIR Institute recommends centralizing cost monitoring in a dashboard. Aggregate the total_cost_usd values from each execution into a CSV file or database to track the trend.

To deepen configuration and best practices, discover the Claude Code training from SFEIR. In one day, you will practice CI/CD integration with concrete labs and learn to optimize your prompts to reduce token consumption.

Key takeaway: use --max-turns to cap costs and monitor total_cost_usd in each JSON response for precise budget tracking.

How to use Claude Code in headless mode with Docker?

Run Claude Code in a Docker container by passing the API key as an environment variable.

Running in Docker guarantees a reproducible environment for your CI/CD pipelines. A Node.js Alpine base image keeps the footprint small, and installing Claude Code adds the npm package plus its platform-specific binary on top.

FROM node:22-alpine
RUN npm install -g @anthropic-ai/claude-code
WORKDIR /app
COPY . .
ENTRYPOINT ["claude", "-p"]
$ docker build -t claude-ci .
$ docker run -e ANTHROPIC_API_KEY="sk-..." claude-ci "Analyze the code in /app/src"

This approach isolates Claude Code from the host system. Each execution starts in a clean environment, eliminating cache or residual dependency issues. Build time depends on your runner and network, and caching the install layer keeps rebuilds fast.

For teams getting started with containerizing their AI tools, the AI-Augmented Developer training from SFEIR covers AI tool integration in DevOps workflows over two days, with hands-on exercises on Docker and CI pipelines.

Check out the complete headless mode guide for advanced Docker configuration options, including volume mounting and cache management.

Key takeaway: Docker + Claude Code in headless mode = reproducible environment; pass the API key via -e and mount your source code as a volume.

Can you combine headless mode with the CLAUDE.md file?

Yes, Claude Code automatically loads the CLAUDE.md file from the current directory, even in headless mode.

The CLAUDE.md file is a project memory mechanism that provides persistent context to Claude Code. In headless mode, this file is read with each call if it is present in the working directory. This allows you to standardize project instructions for all CI/CD calls.

# CLAUDE.md (at the project root)
- Code convention: strict TypeScript, ESLint Airbnb
- Tests: Vitest, minimum 80% coverage
- Never modify files in /config/production/
# Claude Code will automatically read CLAUDE.md
$ cd /my-project && claude -p "Generate tests for src/auth.ts"

In practice, teams that use CLAUDE.md in CI/CD get results that are more consistent with their code standards, because each run shares the same project context. You will find configuration details in the CLAUDE.md memory system FAQ.

The CLAUDE.md file also supports security instructions. Add directives like "Never expose secrets" or "Do not modify production files" to secure your automated pipelines.

Key takeaway: place a CLAUDE.md file at the root of your repo so that each headless execution automatically respects your project conventions.

How to automate code review on every pull request?

Create a GitHub Actions workflow triggered on the pull_request event that runs Claude Code on the diff.

The automated review analyzes the PR diff and produces a structured comment. The average execution time is 30 to 60 seconds for a PR of less than 500 lines.

name: AI Code Review
on:
 pull_request:
 types: [opened, synchronize]

jobs:
 review:
 runs-on: ubuntu-latest
 steps:
 - uses: actions/checkout@v4
 with:
 fetch-depth: 0
 - uses: actions/setup-node@v4
 with:
 node-version: '22'
 - run: npm install -g @anthropic-ai/claude-code
 - name: Review PR
 env:
 ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
 run: |
 DIFF=$(git diff origin/main...HEAD)
 echo "$DIFF" | claude -p "Analyze this diff and list: \
 1. Potential bugs \
 2. Security issues \
 3. Improvement suggestions" \
 --output-format json | jq -r '.result' > review.md
 - name: Post Comment
 uses: actions/github-script@v7
 with:
 script: |
 const fs = require('fs');
 const review = fs.readFileSync('review.md', 'utf8');
 github.rest.issues.createComment({
 owner: context.repo.owner,
 repo: context.repo.repo,
 issue_number: context.issue.number,
 body: `## AI Review\n${review}`
 });

This workflow uses fetch-depth: 0 to access the full diff history. Adapt the prompt to your conventions by referencing the rules in your CLAUDE.md.

Explore conversations with Claude Code to learn how to formulate effective review prompts that maximize feedback relevance.

Key takeaway: automate code review with a 30-line YAML workflow. The diff is passed via pipe and the result is posted as a PR comment.

What are the technical prerequisites for headless mode?

Headless mode requires Node.js 18 or higher, the @anthropic-ai/claude-code npm package, and a valid Anthropic API key.

Here is the complete list of prerequisites:

  • Node.js: version 18+ (recommended: Node.js 22 LTS)
  • npm: bundled with Node.js 18+
  • Claude Code: latest stable version
  • API key: ANTHROPIC_API_KEY environment variable
  • Operating system: Linux, macOS, or Windows (WSL2)
  • Minimum RAM: 4 GB or more (per Claude Code system requirements)
  • Network: outbound HTTPS access to api.anthropic.com
# Check prerequisites
$ node --version # v22.x.x expected
$ npm --version # bundled with Node.js, version number displayed
$ claude --version # a version number is displayed

The installation and first launch FAQ details the complete procedure, including special cases like installation behind an enterprise proxy. Full installation takes less than 2 minutes on a standard connection.

For developers who want to go further, the AI-Augmented Developer - Advanced training from SFEIR (1 day) dives deep into CI/CD architectures with integrated AI, prompt tuning for pipelines, and advanced monitoring strategies.

Key takeaway: Node.js 22 + npm + Anthropic API key: check these three elements before any CI/CD integration.

How to secure the API key in a CI/CD environment?

Store the API key exclusively in your CI platform's secret manager (GitHub Secrets, GitLab CI Variables, AWS Secrets Manager).

The Anthropic API key (ANTHROPIC_API_KEY) grants access to your account and your quota. In headless mode, it must be injected as an environment variable without ever appearing in the source code, logs, or build artifacts.

# GitHub Actions - key stored in repo secrets
env:
 ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
# GitLab CI - key defined in Settings > CI/CD > Variables
variables:
 ANTHROPIC_API_KEY: $CI_ANTHROPIC_KEY

Secret leaks in CI/CD often come from unfiltered logs. Enable automatic secret masking in your CI platform to limit log verbosity.

For a complete view of security best practices with Claude Code, check out the permissions and security FAQ. The security rules defined in your CLAUDE.md also apply in headless mode.

Key takeaway: never store an API key in plain text in the code. Use your CI platform's native secrets and enable masking in the logs.

Are there rate limiting constraints in headless mode?

The Anthropic API applies rate limits that depend on your account and plan. The exact requests-per-minute and tokens-per-minute thresholds vary by tier, so consult the Anthropic rate-limits documentation for the current per-tier numbers rather than assuming fixed values.

In headless mode within a CI/CD pipeline, you can hit these limits if multiple jobs run in parallel. Rate limiting is applied at the API key level, not at the machine or container level. For the current per-tier thresholds, refer to the Anthropic rate limits documentation.

Implement a retry mechanism with exponential backoff to handle 429 (Too Many Requests) errors:

MAX_RETRIES=3
for i in $(seq 1 $MAX_RETRIES); do
 claude -p "Review this code" --output-format json && break
 echo "Rate limited, retry $i/$MAX_RETRIES..."
 sleep $((2 ** i))
done

In practice, a moderate CI/CD workload (for example a project with a few dozen PRs per week and a handful of jobs per PR) typically stays well within standard plan limits, but you should verify against your own tier. Find more optimization tips in the headless mode tips.

Key takeaway: monitor your quotas via the Anthropic dashboard and implement retry with exponential backoff to absorb CI/CD load spikes.

Recent articles about Claude

Recommended training

Claude Code Training

Master Claude Code fundamentals in 1 day with our expert instructors. 60% hands-on practice on real-world cases.

Discover the training