Skip to content
headless-mode logo

Headless Mode

headless-mode

Guide for using Claude Code programmatically via CLI flags and SDKs. Use for automation, CI/CD pipelines, scripting, and building tools on top of Claude Code. Covers --print mode, output formats, session management, and SDK integration.

SKILL.md

Full skill instructions

Headless Mode

Run Claude Code programmatically for automation, CI/​CD, and scripting.

Quick Reference

ModeCommandUse Case
CLI (simple)claude -p "prompt"One-shot tasks, scripts
CLI (structured)claude -p "prompt" --output-format jsonParsing responses
TypeScript SDK@anthropic-ai/​claude-codeFull programmatic control
Python SDKclaude-code-sdkPython automation

Core Concept

The -p (or --print) flag runs Claude Code non-interactively. All CLI options work with -p, enabling automated workflows without human interaction.

claude -p "Explain what this project does"

Essential Flags

FlagPurposeExample
-p, --printRun non-interactivelyclaude -p "query"
--output-formatResponse formatjson, stream-json, text
--allowedToolsAuto-approve tools"Bash,Read,Edit"
--max-turnsLimit agent turns--max-turns 5
--continueContinue last sessionclaude -p "..." --continue
--resumeResume specific session--resume $SESSION_ID

Output Formats

Text (Default)

Plain text output for simple tasks:

claude -p "Summarize auth.py"

JSON (Structured)

Get metadata with response:

claude -p "Analyze this code" --output-format json

Returns:

{
  "result": "Analysis text...",
  "session_id": "abc123",
  "usage": { "input_tokens": 100, "output_tokens": 50 }
}

Stream JSON (Real-time)

Newline-delimited JSON for streaming:

claude -p "Generate report" --output-format stream-json

Tool Auto-Approval

Basic Approval

Allow specific tools without prompting:

claude -p "Fix the failing tests" --allowedTools "Bash,Read,Edit"

Granular Bash Commands

Restrict to specific bash patterns:

claude -p "Create a commit for staged changes" \
  --allowedTools "Bash(git diff:*),Bash(git log:*),Bash(git commit:*)"

Skip All Permissions (Dangerous)

Use only in trusted, sandboxed environments:

claude -p "Deploy to staging" --dangerously-skip-permissions

Session Management

Continue Last Session

claude -p "Review this codebase"
claude -p "Focus on the database layer" --continue
claude -p "Summarize findings" --continue

Resume Specific Session

# Capture session ID
session_id=$(claude -p "Start review" --output-format json | jq -r '.session_id')

# Later: resume that session
claude -p "Continue the review" --resume "$session_id"

Fork a Session

Create a new branch from an existing session:

claude -p "Try alternative approach" --resume $SESSION_ID --fork-session

System Prompt Customization

Append Instructions

Keep default behavior, add context:

claude -p "Review this PR" \
  --append-system-prompt "Focus on security vulnerabilities"

Replace System Prompt

Full control over Claude's behavior:

claude -p "Analyze code" \
  --system-prompt "You are a security auditor. Only report vulnerabilities."

Load from File

claude -p "Review code" --system-prompt-file ./​prompts/​security-review.txt

Structured Output (JSON Schema)

Force output to match a schema:

claude -p "Extract function names from utils.py" \
  --output-format json \
  --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'

Response includes structured_output field:

{
  "result": "...",
  "structured_output": {
    "functions": ["parseDate", "formatCurrency", "validateEmail"]
  }
}

Common Patterns

Code Review

gh pr diff "$PR_NUMBER" | claude -p \
  "Review this PR for bugs and improvements" \
  --output-format json

Test Fixing

claude -p "Run tests and fix failures" \
  --allowedTools "Bash,Read,Edit" \
  --max-turns 10

Documentation Generation

claude -p "Generate API documentation for src/​api/" \
  --allowedTools "Read,Glob,Grep,Write"

Batch Processing

for file in src/​*.ts; do
  claude -p "Add JSDoc comments to $file" \
    --allowedTools "Read,Edit"
done

Key Differences from Interactive Mode

FeatureInteractiveHeadless (-p)
Slash commandsAvailableNot available
Permission promptsInteractiveAuto-approve or skip
OutputFormattedRaw text/​JSON
SessionPersistentOne-shot (unless --continue)

Reference Files

FileContents
CLI-FLAGS.mdComplete CLI flag reference
SDK.mdTypeScript and Python SDK usage
EXAMPLES.mdPractical automation examples

Troubleshooting

No Output

Check if Claude is waiting for permission:

claude -p "query" --verbose

Add --allowedTools or --dangerously-skip-permissions.

JSON Parsing Errors

Use jq to extract fields:

claude -p "query" --output-format json | jq -r '.result'

Session Not Found

Sessions are directory-specific. Run from the same directory or use --session-id with a UUID.

Best Practices

  1. Use JSON output for automation - easier to parse
  2. Limit tools to only what's needed - security first
  3. Set max-turns for predictable execution time
  4. Capture session IDs for multi-turn workflows
  5. Use --append-system-prompt to add context without losing defaults

More DevOps & CI/CD skills

Project scaffolding, deployment configuration, and CI/CD setup for Google ADK agents.

6K 472.6K
View

Set up tracing, logging, and monitoring for deployed ADK agents across Cloud Trace, BigQuery, and third-party platforms.

6K 472.6K
View

Enterprise Azure infrastructure architect generating Bicep or Terraform from workload descriptions.

1.5K 454.3K
View
azure-kubernetes logo
DevOps & CI/CD

azure-kubernetes

Plan and configure production-ready Azure Kubernetes Service clusters with Day-0 and Day-1 best practices.

1.5K 447.1K
View

Raw mechanical interfaces fusing Swiss typographic print with military terminal aesthetics. Rigid grids, extreme type scale contrast, utilitarian color, analog degradation effects. For data-heavy dashboards, portfolios, or editorial sites that need to feel like declassified blueprints.

92.7K 354.9K
View
just-scrape logo
DevOps & CI/CD

just-scrape

Web search, scraping, extraction, crawling, and monitoring via ScrapeGraph AI CLI.

69 245K
View

Skill for working with Firebase Hosting (Classic). Use this when you want to deploy static web apps, Single Page Apps (SPAs), or simple microservices. Do NOT use for Firebase App Hosting.

462 159.7K
View

Deploy and manage web apps with Firebase App Hosting. Use this skill when deploying Next.js/Angular apps with backends.

462 159.1K
View
deploy-to-vercel logo
DevOps & CI/CD

deploy-to-vercel

Deploy applications and websites to Vercel. Use when the user requests deployment actions like "deploy my app", "deploy and give me the link", "push this live", or "create a preview deployment".

31.9K 146.6K
View
programmatic-seo logo
DevOps & CI/CD

programmatic-seo

Build SEO-optimized pages at scale using templates, data, and proven playbook patterns.

53.3K 140.1K
View

Design and build isolated, reusable Convex backend components with clear boundaries and app-facing wrappers.

63 123.5K
View

Deploy and manage projects on Vercel using token-based authentication. Use when working with Vercel CLI using access tokens rather than interactive login — e.g. "deploy to vercel", "set up vercel", "add environment variables to vercel".

31.9K 116.1K
View

Coding & apps AI tools

Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View
I
Coding & apps

Imagica

Build a no-code AI app in minutes.

Freemium
View
E
Coding & apps

Emergent.sh

An IDE for code migration from legacy to modern frameworks through coding agents.

Freemium
View
Wonder Dynamics logo
Coding & apps

Wonder Dynamics

Automate CGI animation in live-action scenes

Paid
View
M
Coding & apps

Mixo

Launch a website in seconds with AI.

Paid
View
AI Code Convert logo
Coding & apps

AI Code Convert

Streamline Your Coding Experience with AI Code Helper

Free
View