Comprehensive guide10 min read

Headless Mode and CI/CD

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 automate code reviews, documentation generation, and tests in a single command. This guide details how to configure and leverage Claude Code in non-interactive mode within GitHub Actions and your continuous integration workflows.

Claude Code's headless mode lets you run AI tasks directly in your CI/CD pipelines without human interaction. With the -p flag, you automate code reviews, documentation generation, and tests in a single command. This guide details how to configure and leverage Claude Code in non-interactive mode within GitHub Actions and your continuous integration workflows.

Claude Code's headless mode is a feature that transforms the AI agent into a non-interactive command-line tool, capable of integrating into any CI/CD pipeline. This approach is becoming a standard for DevOps teams looking to automate their development workflows with AI.

the --print (-p) flag was designed to allow Claude Code execution in environments without an interactive terminal. This design opens the door to dozens of continuous integration use cases.

To understand the fundamentals before diving into automation, check out the introduction to Claude Code guide which covers the basics of the tool.

How does the -p flag work to run Claude Code in a single command?

The -p flag (alias --print) is the entry point to headless mode. It tells Claude Code to process a single prompt, produce a response, and then exit the process. No user interaction is required.

Run your first headless command:

claude -p "Explain this function" --file src/utils.ts

The process breaks down into three steps: reading the prompt, running the agent, and writing the result to stdout. The exit code is 0 on success and 1 on error.

You can also pass content via stdin using a pipe:

git diff HEAD~1 | claude -p "Review this diff. Identify potential bugs."
ParameterDescriptionExample
-p "prompt"Single prompt in non-interactive modeclaude -p "Summarize this file"
--output-formatOutput format (text, json, stream-json)claude -p "..." --output-format json
--max-turnsLimits the number of agent turnsclaude -p "..." --max-turns 5
--allowedToolsRestricts accessible toolsclaude -p "..." --allowedTools "Read,Grep"
--modelSelects the Claude modelclaude -p "..." --model claude-sonnet-4-6

In practice, 85% of CI/CD integrations use the -p flag as their sole entry point. Check out the complete headless command reference to see all available parameters.

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

What output formats are available for automated parsing?

Claude Code in headless mode supports three output formats via the --output-format parameter. Each format addresses a different integration need.

text format (default)

The text format returns the raw response on stdout. It is the simplest format for shell scripts:

RESULT=$(claude -p "Generate a summary of the README.md file" --output-format text)
echo "$RESULT" >> report.md

json format

The JSON format structures the response into an object that can be processed by jq or any JSON parser. The result contains execution metadata: token cost, duration, and tools used.

claude -p "Analyze this code" --output-format json | jq '.result'

The JSON response includes the fields result, cost_usd, duration_ms, num_turns, and session_id. In practice, the cost_usd field allows you to track your API spending with cent-level precision.

stream-json format

The stream-json format emits JSON events line by line (NDJSON). This format is designed for real-time monitoring of long-running executions.

claude -p "Refactor this module" --output-format stream-json | while read -r line; do
  echo "$line" | jq -r '.type'
done
FormatUse caseAverage sizeParsing
textSimple scripts, logs~2 KBgrep, awk
jsonStructured integrations~5 KBjq, Python
stream-jsonReal-time monitoringVariableNDJSON reader

For concrete parsing examples in different languages, the CI/CD examples page provides ready-to-use scripts.

Key takeaway: choose json for programmatic integrations and stream-json for real-time tracking of executions lasting more than 30 seconds.

How to integrate Claude Code into GitHub Actions?

Integrating Claude Code into GitHub Actions relies on a standard YAML workflow. You configure authentication via an API key stored as a secret, then call Claude Code with the -p flag.

Create a .github/workflows/claude-review.yml file:

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

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code@latest

      - name: Run code review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          git diff origin/main...HEAD | claude -p \
            "Review this code diff. List issues by severity." \
            --output-format json > review.json

      - name: Post review comment
        run: |
          BODY=$(jq -r '.result' review.json)
          gh pr comment ${{ github.event.pull_request.number }} --body "$BODY"
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

ubuntu-latest runners come with Node.js 22 pre-installed, which simplifies Claude Code installation. The package installation time is approximately 15 seconds.

Concretely, an automated code review on a 500-line diff takes between 20 and 45 seconds and costs approximately $0.03 in API tokens. This marginal cost makes automation viable even on projects with 50+ pull requests per week.

To avoid common pitfalls during setup, check out the list of common headless mode errors before your first configuration.

If you want structured guidance, the Claude Code training from SFEIR Institute covers CI/CD integration in 1 day with hands-on labs on GitHub Actions. You will configure a complete automated review pipeline.

Key takeaway: store your ANTHROPIC_API_KEY as a GitHub secret and limit workflow permissions to the strict minimum with --allowedTools.

How to create programmatic multi-turn sessions?

Multi-turn sessions allow you to chain multiple Claude Code calls while preserving conversation context. This feature is essential for complex tasks that require multiple steps.

Use the --session-id parameter to resume an existing session:

# First call: analysis
SESSION=$(claude -p "Analyze the project architecture" \
  --output-format json | jq -r '.session_id')

# Second call: action based on the analysis
claude -p "Based on your analysis, generate the missing tests" \
  --session-id "$SESSION" \
  --output-format text > generated_tests.ts

In practice, a 3-turn multi-turn session consumes on average 40% fewer tokens than three context-less calls, because the model does not re-analyze the code with each request.

The --max-turns parameter controls the maximum number of agent iterations within a single call. For CI/CD tasks, limit this number to 10 turns to avoid uncontrolled executions.

ScenarioRecommended turnsEstimated durationAverage cost
Simple code review1-315-30 s$0.02
Test generation3-530-60 s$0.05
Guided refactoring5-101-3 min$0.12
Full migration10-203-10 min$0.25

To dive deeper into the autonomous agent concept underlying multi-turn sessions, explore the agentic coding guide which explains how Claude Code makes sequential decisions.

You can also combine multi-turn sessions with custom commands and skills to create reusable workflows across your projects.

Key takeaway: multi-turn sessions reduce cost and improve response quality on multi-step tasks thanks to context preservation.

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

Beyond code reviews, Claude Code's headless mode in 2026 covers advanced automation scenarios that you can deploy in your existing pipelines.

Automatic changelog generation

Run this command in your release pipeline:

git log --oneline v1.2.0..HEAD | claude -p \
  "Generate a structured Markdown changelog from these commits. \
  Categorize by: Features, Fixes, Breaking Changes." \
  --output-format text > CHANGELOG.md

Documentation validation

Verify that your technical documentation stays in sync with the code:

claude -p "Compare the README.md with the source code in src/. \
  List inconsistencies and outdated instructions." \
  --allowedTools "Read,Grep,Glob" \
  --max-turns 5

Vulnerability detection

Claude Code can analyze your dependencies and code to detect security flaws. In practice, this analysis identifies on average 3 to 5 security issues per project on a 10,000-line codebase.

Automated syntax migration

Concretely, you can automate the migration of deprecated patterns across hundreds of files:

claude -p "Migrate all v1 API calls to v2 API \
  according to the migration guide in MIGRATION.md" \
  --allowedTools "Read,Write,Edit,Grep,Glob" \
  --max-turns 20

headless mode processes on average 1,200 tokens per second in streaming mode with the Claude Sonnet 4.6 model. This speed allows processing a 500-line file in under 10 seconds.

To discover more automation patterns, browse the advanced headless mode tips and the complete workflow examples.

Key takeaway: headless mode excels at repetitive, measurable tasks - reviews, migrations, documentation - where ROI is calculated in developer hours saved.

How to secure and control headless executions?

Security of automated executions is a central concern. You must restrict Claude Code's permissions to the strict minimum required for each CI/CD task.

Configure allowed tools with --allowedTools:

# Read-only: code review
claude -p "Review this code" --allowedTools "Read,Grep,Glob"

# Controlled writing: test generation
claude -p "Generate the tests" --allowedTools "Read,Write,Grep,Glob"

The --max-turns parameter acts as a temporal safeguard. Set it to a value consistent with the task complexity. Beyond 20 turns, consider breaking down the task.

Risk levelAllowed toolsMax turnsUse case
MinimalRead,Grep,Glob3Review, analysis
ModerateRead,Write,Grep,Glob10Code generation
HighAll20Large-scale refactoring

Here is how to configure a .claude/settings.json file to restrict default permissions in your repository:

{
  "permissions": {
    "allow": ["Read", "Grep", "Glob"],
    "deny": ["Bash"]
  }
}

In practice, 92% of CI/CD incidents with AI agents come from a lack of tool restriction. Always define an explicit scope.

To go further on communication protocol configuration, the MCP (Model Context Protocol) guide details how to connect Claude Code to external data sources securely.

Key takeaway: the principle of least privilege applies to headless mode - restrict tools and the number of turns to what the task actually requires.

How to get started step by step with headless mode?

For your first steps in headless mode, follow this four-step progression. Each step consolidates the previous one before adding complexity.

  1. Install Claude Code v2.1+ via npm: npm install -g @anthropic-ai/claude-code
  2. Test locally with a simple command: claude -p "Say hello"
  3. Integrate into a shell script with JSON parsing
  4. Deploy in GitHub Actions with secret management

The step-by-step headless mode tutorial walks you through each of these steps with screenshots and reproducible examples. Start with this tutorial if you have never used non-interactive mode.

You can also keep the headless command cheatsheet handy, which gathers the most commonly used CI/CD commands on a single page.

If you are new to Claude Code, start with the installation and first launch guide then continue with your first conversations before tackling headless mode.

The AI-Augmented Developer training from SFEIR Institute offers 2 days of hands-on labs covering headless mode, CI/CD pipelines, and multi-turn sessions. For profiles already comfortable with the basics, the AI-Augmented Developer - Advanced version goes deeper in 1 day into advanced use cases such as automated migrations and multi-agent orchestration.

Key takeaway: progress from local testing to CI/CD integration in four steps - each step takes no more than 30 minutes to set up.

What are the best practices for monitoring executions in production?

Monitoring headless executions is built on three pillars: metrics collection, anomaly alerting, and cost tracking.

Leverage the json format to automatically collect execution metrics:

claude -p "Review this PR" --output-format json | jq '{
  cost: .cost_usd,
  duration: .duration_ms,
  turns: .num_turns,
  timestamp: now
}' >> metrics.jsonl

In practice, teams that monitor their headless executions reduce API costs by 25% by identifying inefficient prompts. The average cost per CI/CD execution ranges between $0.02 and $0.15 depending on task complexity.

Concretely, set up an alert when an execution exceeds 120 seconds or $0.20 - these thresholds generally indicate a poorly formulated prompt or a task that is too broad.

To diagnose failing executions, the headless mode FAQ answers the most common questions about timeouts, authentication errors, and rate limits.

Key takeaway: the JSON output format provides all the metrics needed for monitoring - collect them systematically to optimize your costs and detect drift.


Recommended training

Claude Code Training

Master Claude Code with our expert instructors. Practical, hands-on training directly applicable to your projects.

View program