Claude Code headless mode is the same agent without the chat window. You run claude -p "prompt", it does the work, prints the result and exits with a status code your script can check. This post covers the flags that matter when you use Claude Code headless in shell scripts, cron jobs and CI: output formats, permissions, bare mode, budgets and authentication.
All flags here are checked against Anthropic's CLI reference and the headless guide. Some behavior depends on your Claude Code version, and I note the version where the docs do.
What is Claude Code headless mode?
Headless, or non-interactive, mode is what you get when you add -p (long form --print) to any claude command. Anthropic now documents it as the CLI form of the Agent SDK: the same tools, agent loop and context handling, available as a command for scripts, or as Python and TypeScript packages when you need more control.
claude -p "What does the auth module do?"
A few facts that shape how you script it:
- Exit code
0means success and non-zero means the run failed, soif claude -p ...; thenworks. - An invalid flag is reported on stderr before the run starts. A failure inside the run, such as missing authentication, is printed as the result on stdout.
- It reads stdin, so you can pipe data in. Piped input is capped at 10 MB. For anything bigger, write it to a file and mention the path in the prompt.
cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt
On my server, the one I set up with claude-code-vps, I run interactive agents in tmux panes with claudegrid when I want to watch and steer them. The full setup is in how I run multiple Claude Code agents in parallel on a server. claude -p covers the other kind of job: one prompt, nobody watching, a result that a script reads.
How do I get JSON output from Claude Code headless?
--output-format takes three values:
| Value | What you get |
|---|---|
text | Plain text, the default |
json | One JSON object with the result, session ID and metadata |
stream-json | Newline-delimited JSON events as they happen |
With json, the text answer is in result, and the payload also carries session_id and total_cost_usd. The cost is a client-side estimate and can differ from your bill.
claude -p "Summarize this project" --output-format json | jq -r '.result'
When a script needs a fixed shape, add --json-schema. The validated output lands in structured_output:
claude -p "Extract the main function names from auth.py" \
--output-format json \
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
| jq '.structured_output'
If Claude declines or the run ends without valid structured output, the field is missing. Check for it before you use it. An invalid schema makes claude exit with Error: --json-schema is not a valid JSON Schema.
For live output, the docs pair stream-json with --verbose, and --include-partial-messages adds token-level events:
claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages | \
jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'
The last line of the stream is a result message with the final text, cost and session metadata. The first is usually a system/init event listing the model, tools, MCP servers and plugins, which is handy in CI: its plugin_errors and mcp_server_errors arrays let a job fail when something didn't load.
Permissions in headless mode
In headless mode nobody is there to answer a permission prompt, so what matters is what happens to a tool call that would normally ask.
In Claude Code v2.1.302 or later, a claude -p run with no permission mode set starts in Manual mode (default in config). A call that needs approval is denied unless an allow rule, a hook or a --permission-prompt-tool approves it. Reads in your working directories still run, since they need no approval.
You have three levels of control.
Allow specific tools with --allowedTools. It uses permission rule syntax, so you can scope Bash to commands:
claude -p "Look at my staged changes and create an appropriate commit" \
--allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"
The space before * matters. Bash(git diff *) matches git diff with or without arguments, while Bash(git diff*) would also match git diff-index.
Block or remove tools with --disallowedTools (deny rules, for example "Bash(rm *)" or "mcp__*") or restrict the built-in set with --tools "Read,Grep".
Set a baseline with --permission-mode:
| Mode | What runs without asking | Fits |
|---|---|---|
default | Reads and actions that need no approval | Read-only reports |
acceptEdits | File edits and common filesystem commands like mkdir and mv | Applying fixes in a checkout |
dontAsk | Only pre-approved tools. Anything that would prompt is denied | Locked-down CI |
auto | Most actions, reviewed by a separate classifier model | Longer unattended tasks |
bypassPermissions | Everything | Isolated containers and VMs only |
--dangerously-skip-permissions is the same as --permission-mode bypassPermissions. The docs say to use it only in isolated environments like containers, VMs or dev containers without internet access, where Claude Code can't damage the host. I'd take that literally.
For scheduled jobs there is also --permission-prompts none (v2.1.259 or later). It tells Claude that nobody can approve a request, so it shouldn't retry, and it removes tools that need a person, such as AskUserQuestion:
claude -p "Update the dependency pins and run the tests" --permission-mode auto --permission-prompts none
Bare mode: the safer default for scripts
Without extra flags, claude -p loads everything an interactive session would: your hooks, skills, plugins, MCP servers, auto memory and CLAUDE.md, from both the project and ~/.claude. That includes a project's .claude/settings.json hooks and .mcp.json servers, even in a folder you've never trusted, and a -p run shows no trust dialog.
--bare skips all of that auto-discovery and starts faster. Claude gets Bash, file read and file edit tools, and you pass in exactly what the run needs:
claude --bare -p "Summarize README.md" --allowedTools "Read"
| To load | Use |
|---|---|
| Extra system prompt | --append-system-prompt, --append-system-prompt-file |
| Settings | --settings <file-or-json> |
| MCP servers | --mcp-config <file-or-json> |
| Subagents | --agents <file-or-json> |
| A plugin | --plugin-dir <path> |
Anthropic calls --bare the recommended mode for scripted and SDK calls and says it will become the default for -p in a future release. The catch is authentication: bare mode never reads OAuth credentials or the keychain, so it needs ANTHROPIC_API_KEY or an apiKeyHelper in the --settings JSON.
Keeping a headless run bounded
A script shouldn't be able to run forever or spend without limit. These flags are print-mode only:
claude -p "Fix the failing test in tests/auth.test.ts" \
--allowedTools "Read,Edit,Bash(npm test *)" \
--max-turns 10 \
--max-budget-usd 2 \
--no-session-persistence
--max-turnslimits agentic turns. There is no limit by default.--max-budget-usdstops the run once estimated spend reaches the amount. Spend can pass the cap, so leave headroom.--no-session-persistencekeeps the session off disk, so it can't be resumed.--modelpicks the model, and--fallback-model sonnet,haikugives a chain to try when the primary is overloaded or unavailable.
To continue work across runs, save the session ID and resume it:
session_id=$(claude -p "Start a review of src/" --output-format json | jq -r '.session_id')
claude -p "Now focus on the database queries" --resume "$session_id"
--continue picks up the most recent conversation instead.
Skills work too. Put /skill-name in the prompt string and Claude Code expands it before running. If you stack several, only the first loads in -p, with the rest of the line as its arguments. A skill that runs in a subagent with context: fork is waited for instead of running in the background. My post on Claude Code skills covers how to write one.
Authentication on a server or in CI
There is no browser on a CI runner, so /login is out. Two options from the authentication docs:
- API key: set
ANTHROPIC_API_KEYwith a key from the Claude Console. This is the one that works with--bare. - Subscription token: run
claude setup-tokenonce on a machine with a browser. It requires a Claude subscription, goes through the same approval as/loginand prints a one-year OAuth token without saving it anywhere. Set it asCLAUDE_CODE_OAUTH_TOKENwhere the job runs. Bare mode doesn't read this variable.
Either way, keep the value in your CI's secret store and never in the repository.
Claude Code headless in GitHub Actions
The simplest route is Anthropic's Claude Code GitHub Action. Running /install-github-app inside Claude Code sets up the GitHub app, the secret and a workflow for you, on github.com repositories. With a prompt input the action runs in automation mode on any event, including a schedule, and claude_args passes CLI flags through:
name: Daily Report
on:
schedule:
- cron: "0 9 * * *"
jobs:
report:
runs-on: ubuntu-latest
permissions:
contents: read
issues: read
id-token: write
steps:
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
prompt: "Generate a summary of yesterday's commits and open issues"
claude_args: |
--allowedTools "mcp__github__list_commits,mcp__github__list_issues"
With a plain-text prompt, Claude has no shell or GitHub API access until you grant the tools it needs, as --allowedTools does here. For a subscription token, swap the anthropic_api_key line for claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}.
If you'd rather call the CLI yourself on a runner or your own server, install it with the native installer and run claude -p like any other command:
curl -fsSL https://claude.ai/install.sh | bash
git diff origin/main | claude --bare -p "Review this diff for bugs. Reply with file:line and the issue, nothing else." \
--output-format json --max-turns 5 | jq -r '.result'
This one uses --bare, so the job needs ANTHROPIC_API_KEY in its environment. Piping the diff in means Claude doesn't need Bash permission to read it.
Stopping a run cleanly
If a supervisor stops claude -p with SIGTERM, it exits with code 143, kills the process tree of any running Bash command, runs SessionEnd hooks and leaves the turn unfinished with no result. Send SIGINT first if you want the turn to end properly. After the turn, a run may stay open to wait for background work Claude started. By default Claude Code stops waiting after 10 minutes of idle time, and CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS changes that cap.
If you need this wired into a product or pipeline, I take on that kind of work. See hire.
FAQ
Is Claude Code headless mode the same as the Agent SDK?
Anthropic documents claude -p as the Agent SDK used through the CLI. The Python and TypeScript packages add things like tool approval callbacks and native message objects.
Why are my tool calls denied in claude -p?
Recent versions start -p runs in Manual mode, where anything that needs approval is denied. Add --allowedTools entries or pick a mode with --permission-mode.
How do I get only the answer text from a headless run?
Use --output-format json and read the result field with jq -r '.result', or keep the default text format.
Can I use my Claude subscription in CI?
Yes, through claude setup-token and the CLAUDE_CODE_OAUTH_TOKEN variable. That token doesn't work with --bare, which needs an API key.
Do skills and CLAUDE.md load in headless mode?
Yes, unless you pass --bare. User-invoked skills work when the prompt starts with /skill-name.