CLClaude Lessons Try the free lessons

Claude Lessons / Guides

Claude Code Headless Mode: Running claude -p in Scripts and CI

claude -p "fix the build" looks like the simplest thing in Claude Code. It is actually the moment the tool stops being a chat window and becomes a program you are responsible for — and the defaults change underneath you when the terminal goes away. An unattended run has nobody to approve a permission prompt, so it now starts in a mode that denies rather than asks. A headless run in an untrusted checkout will execute that repository's hooks with no trust dialog, because there is no dialog to show. Background work gets cut off at ten minutes. This guide covers the non-interactive surface the way you need it to write a build step you can trust: what changes when nobody is watching, the one flag that decides your security posture, and the patterns that survive CI.

Illustration of running an agent from a script without a person watching

What headless mode is

Add -p (or --print) to any claude command and it runs non-interactively: no terminal UI, a result printed to stdout, then exit. It is the same agent loop, the same tools and the same context management as an interactive session.

claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"

Worth knowing where this sits in the documentation, because it explains the naming: the page is called Run Claude Code programmatically and lives under the Agent SDK. The Agent SDK is the thing; claude -p is its CLI surface, and the Python and TypeScript packages are the other two. If you have been treating "headless mode" and "the SDK" as separate products, they are one product with three front doors.

Exit status is the contract your script depends on: 0 on success, non-zero when the run fails. An invalid flag is reported to stderr before the run starts. A failure inside the run — missing authentication, for example — is printed as the result on stdout, which is a distinction worth building into your error handling: a non-zero exit with your expected JSON on stdout is a real possibility.

The basics, and what combines with -p

Not every CLI option combines with -p. The documented conflicts:

The flags you will reach for constantly are --continue, --allowedTools and --output-format. Each gets its own section below.

--bare: the flag that decides your security posture

--bare is presented as a startup-time optimisation, and it is one. It skips auto-discovery of your hooks, skills, custom commands, subagents, installed plugins, MCP servers, auto memory and CLAUDE.md. In a short CI step that discovery can dominate the wall clock.

But its real significance is what it stops from running. Here is the difference:

claude -pclaude --bare -p
Project .claude/settings.json hooksRunSkipped
Project .mcp.json serversConnectedSkipped
Skills, commands, subagents, pluginsLoadedSkipped
CLAUDE.md and auto memoryLoadedSkipped
Settings files and permission rulesReadStill read
Subscription login / keychainUsedNever read — needs ANTHROPIC_API_KEY
Available toolsEverything configuredBash, file read, file edit

Note the two rows that are not simply "off". Bare mode still reads settings files and their permission rules — you do not lose your deny rules by going bare. And bare mode never reads OAuth credentials or the system keychain, so a bare run needs ANTHROPIC_API_KEY in the environment, or an apiKeyHelper in the --settings JSON. Amazon Bedrock, Google Cloud's Agent Platform and Microsoft Foundry keep reading their own provider credentials as usual.

claude --bare -p "Summarize README.md" --allowedTools "Read"

Because bare mode loads nothing by discovery, you pass what you need explicitly:

To loadUse
System prompt additions--append-system-prompt, --append-system-prompt-file
Settings--settings <file-or-json>
MCP servers--mcp-config <file-or-json>
Custom agents--agents <file-or-json>
A plugin--plugin-dir <path>, --plugin-url <url>

One subtlety on --add-dir: in bare mode a directory you add there does contribute skills from its .claude/skills/ folder, but its .claude/commands/ and .claude/agents/ folders are still skipped. Bare is not quite absolute.

Bare mode's limits became strict in v2.1.286. Before that they held only partly: an interactive --bare session connected the MCP servers a normal session would, every --bare session sent system reminders, and background tasks stayed available. If you are relying on --bare as a boundary, be on v2.1.286 or later.

The untrusted-checkout problem

This deserves its own section because it is the thing most likely to bite a team that adopts headless runs in CI, and it is almost absent from third-party write-ups.

Without --bare, a claude -p session runs the hooks in a project's .claude/settings.json and connects the MCP servers in its .mcp.json — even in a folder you have never trusted. A -p session shows no workspace trust dialog and no per-server approval prompt, because there is nobody there to answer one.

Follow that through. A hook is a shell command. An MCP server is a process Claude Code starts. If your CI job checks out a contributor's branch, or a fork's pull request, and then runs claude -p in that checkout, the repository supplies code and your runner executes it — with your runner's credentials. The interactive trust dialog you rely on day to day is precisely the thing that cannot exist here.

So the rule is short:

Permissions when nobody can answer

On Claude Code v2.1.302 or later, claude -p runs start in Manual mode when nothing else sets a permission mode. In Manual mode a call that needs approval is denied unless something approves it. That is the correct default for an unattended process — and it is why a run you expected to edit files quietly reports that it could not do anything.

Three ways to give it room, in increasing order of bluntness.

1. List the tools

claude -p "Run the test suite and fix any failures" \
  --allowedTools "Bash,Read,Edit"

--allowedTools pre-approves specific tools. Reads and edits then proceed without prompting, apart from reads from network paths. Calls to tools you did not list still run if they need no approval at all.

One sharp edge: in a run that starts in auto mode, Claude Code drops a bare Bash entry as a broad allow rule, and lets the auto-mode classifier evaluate each command instead. So --allowedTools "Bash" plus --permission-mode auto does not mean "all shell commands allowed" — it means "classifier decides".

2. Set a baseline mode

ModeWhat it does in a headless run
--permission-mode auto A classifier reviews most actions instead of you. The usual choice for unattended work that needs real latitude
--permission-mode dontAsk Denies every call that would otherwise prompt — a locked-down CI run. Actions needing no approval still run, as do anything matching --allowedTools or permissions.allow. Note that a mod you installed can still approve some calls
--permission-mode acceptEdits Claude writes files without prompting and common filesystem commands (mkdir, touch, mv, cp) are auto-approved. Other shell commands and network requests still need an explicit allow

Even under dontAsk, a defined set stays denied no matter what allows it: AskUserQuestion, connector tools your organization set to ask, MCP tools marked requiresUserInteraction, and reads from network paths. For how auto mode actually decides, see our auto mode guide.

3. Supply an approver

A PermissionRequest hook or an MCP tool passed with --permission-prompt-tool can answer requests programmatically. This is how you encode "allow writes under src/, deny everything else" as logic rather than as a flag list.

Turning prompts off properly

There is a dedicated flag for "nobody is available to answer", and it is not the same as a permission mode:

claude -p "Update the dependency pins and run the tests" \
  --permission-mode auto --permission-prompts none

--permission-prompts none matters most when your run has a permission host — an Agent SDK app with a canUseTool callback, or an MCP tool passed with --permission-prompt-tool. Without the flag (or the permissions.denyInsteadOfPrompting setting), your run waits for that host to answer each request. In a scheduled job, that is a hang.

With the flag: the run does not consult the host, anything that would prompt is denied unless a PermissionRequest hook allows it, Claude is told that nobody can approve and not to retry, and the run continues. Claude Code also removes the tools that need a person, such as AskUserQuestion, so Claude cannot call them, and cancels any MCP elicitation request that no Elicitation hook answers.

With --output-format stream-json, denials appear as permission_denied system messages and the final result message lists them in permission_denials — which is the field to log if you want to know why a job did less than you hoped.

--permission-prompts requires v2.1.259 or later; earlier versions reject it with an unknown-option error. The flag lasts one run — to make it permanent, set permissions.denyInsteadOfPrompting to true in user or managed settings.

Output formats and structured output

--output-format takes three values:

To constrain the shape of the answer, combine json with --json-schema:

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"]}'

The validated object arrives in structured_output, beside the usual metadata. Three things to handle:

Parsing with jq is the expected shape:

claude -p "Summarize this project" --output-format json | jq -r '.result'

Streaming

claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages

Each line is a JSON event, and the last line is a result message with the final response text, cost and session metadata — so a consumer can read the stream for progress and still take the authoritative answer from the final line.

If your consumer reads slowly, Claude Code waits for the queued output to drain before exiting, scaling the wait with how much is still queued, capped at 30 seconds. A slow reader can therefore lose the tail of a very chatty stream.

Piping data in

Non-interactive mode reads stdin, which is often the cleanest way to give Claude context without giving it tools:

cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt

The pattern generalises nicely into a project-specific linter. Piping the diff in means Claude needs no Bash permission to read it, which is a genuinely good habit for a locked-down run:

{
  "scripts": {
    "lint:claude": "git diff main | claude -p \"you are a typo linter. for each typo in this diff, report filename:line on one line and the issue on the next. return nothing else.\""
  }
}

Piped stdin is capped at 10MB. Past the cap Claude Code exits with a clear error and a non-zero status. For larger inputs, write the content to a file and reference the path in your prompt instead. And if Claude Code cannot read stdin at all — the starting process disconnected its end — it prints a warning to stderr and continues with the prompt from the command line, which can look like your piped data was silently ignored.

Unattended runs reward people who can specify

Headless mode removes the conversation. What is left is whatever you managed to write down: the task, the boundaries, the definition of done. Writing a prompt that survives having nobody to clarify it is a skill, and it is what the free lessons practise.

Start the free lessons

Background work at exit

After Claude finishes its turn and stdin has closed, a claude -p run can stay open waiting for background work Claude started. This is the single most confusing area of headless behaviour, because the run sometimes exits "early" and sometimes hangs much longer than you expected.

The default rule: unless a background command that the main conversation started is still running, Claude Code stops whatever is still running after 10 minutes of continuous idle waiting and drops its partial result. Change the cap with CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS, or set it to 0 to wait without one.

Background workHow the run waits
Background commands from the main conversation Waits until the command exits or reaches its time limit, then takes one more turn with the outcome. The 10-minute cap does not end this wait
Background subagents and workflows Waits until each finishes, or the 10-minute cap ends it
Monitor watches Waits until the watch times out (five minutes after Claude starts it, by default) or the cap ends it, whichever comes first. Claude keeps responding to what the watch reports
Pending /loop wakeups In a run whose prompt was passed as text, waits for each wakeup and runs its iteration until the loop ends — even past the 10-minute cap

When stderr is a terminal and the run has waited five seconds, Claude Code prints a line starting Waiting for background work to finish naming the work. Usefully, with json or stream-json output that line prints only when stdout is not a terminal, so the JSON your script parses never carries it.

The exit-code-0 trap. When a subagent's long command moves to the background at its timeout, a claude -p run can exit with code 0 before the command finishes — a green CI step for work that never completed. Raise the default timeout above the command's run time with BASH_DEFAULT_TIMEOUT_MS, for example BASH_DEFAULT_TIMEOUT_MS=300000 for five minutes; for a background subagent command over ten minutes, raise the 10-minute cap as well.

Two more exits to know. If the run hits its --max-budget-usd cap, Claude Code stops the remaining background work instead of waiting. And a -p run never waits for MCP work in the background: an MCP task on a remote server keeps going (resume the session to follow it, rather than firing a fresh one-shot run), while an MCP call that automatic backgrounding moved has its result lost.

Stopping a run: signals and exit codes

The two signals behave differently, and the difference matters to a process supervisor:

SignalWhat happens
SIGTERM (kill, a supervisor) Claude Code exits with code 143. The in-progress turn is left unfinished and no result is recorded for it
SIGINT Ends the turn instead of abandoning it. Use this — or the Agent SDK's interrupt() — before stopping the process if you want the turn concluded

On SIGTERM, Claude Code terminates the process tree of any still-running Bash command, runs SessionEnd hooks, and exits. While exiting it starts no new tool call, sends no new model request, and runs no hook other than SessionEnd. A command that was running is recorded as killed. A permission prompt that was waiting is left unanswered — though if your program closes the session through the Agent SDK, the SDK ends Claude Code's input first, which cancels the prompt cleanly.

On resume, Claude Code leaves the interrupted turn as it is and your next prompt drives the conversation. To have it continue the interrupted turn instead, set CLAUDE_CODE_RESUME_INTERRUPTED_TURN=1.

A small robustness note: if the working directory of a -p session is deleted mid-session, the session keeps running. A turn starting while the directory is missing emits a warning message in stream-json output, and shell commands fail until the directory exists again.

Continuing conversations

Headless runs are not forced to be one-shot. --continue picks up the most recent conversation:

claude -p "Review this codebase for performance issues"
claude -p "Now focus on the database queries" --continue
claude -p "Generate a summary of all issues found" --continue

For several conversations in flight, capture and reuse the session ID:

session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Continue that review" --resume "$session_id"

The two commands can run from different directories — Claude Code finds a session by its ID in any project on the machine. You can also pass --resume the absolute path to a session's .jsonl transcript file and it continues the conversation stored there, which is a handy escape hatch when you have the file but not the ID.

On v2.1.257 or later, --continue will open a background session that has finished, but not one that is still running. If you are orchestrating several headless runs, prefer explicit --resume <id> over --continue; "most recent" is ambiguous the moment you have concurrency. For the broader picture on keeping a long task coherent, see our context management guide.

Tracking cost and capping spend

With --output-format json, the response payload includes total_cost_usd and a per-model cost breakdown, so a scripted caller can track spend without touching a dashboard.

Two caveats that matter if you log these numbers:

For a hard stop rather than a measurement, --max-budget-usd caps the run — and remember it also stops outstanding background work rather than waiting for it. Our token usage and costs guide goes deeper on what actually drives the number.

A CI step that holds up

Pulling the above together, a headless step in CI wants roughly this shape:

git diff origin/main | claude --bare -p \
  "Review this diff. Report only correctness bugs, as filename:line plus one line each. If there are none, return exactly: OK" \
  --permission-mode dontAsk \
  --permission-prompts none \
  --allowedTools "Read" \
  --output-format json \
  --max-budget-usd 2 \
  | jq -r '.result'

Every flag there is load-bearing:

Then check the exit status and the payload, since an in-run failure prints on stdout. If you want this to gate a pull request rather than live in your own pipeline, the managed agents in our Claude Ship guide do the same job with inline comments and organization billing.

When to move to the Python or TypeScript SDK

Stay on the CLI when a shell pipeline is the natural shape. Move to the packages when you need something a process boundary makes awkward:

The migration is not a rewrite: the options object is the same configuration surface the flags expose. If you are building on top of this, the Agent SDK documentation has dedicated pages for hosting, secure deployment, observability with OpenTelemetry and cost tracking — the SDK is where the production concerns actually live.

Common mistakes

FAQ

What is Claude Code headless mode?

Headless mode is Claude Code running non-interactively: you add the -p flag (or --print) with a prompt, Claude does the work without a terminal UI, prints a result to stdout, and exits. It reads stdin, so you can pipe a build log or a diff into it, and it exits 0 on success and non-zero on failure so scripts can branch on the status. It is the same agent loop, tools and context management as an interactive session, exposed for scripts, build steps, CI jobs and scheduled work. The docs file it under the Agent SDK, because claude -p is the CLI surface of that SDK; the Python and TypeScript packages are the other two.

Does claude -p run my repository's hooks and MCP servers?

Yes, unless you pass --bare, and this is the most important security fact about headless mode. Without --bare, a claude -p session runs the hooks in a project's .claude/settings.json and connects the MCP servers in its .mcp.json even in a folder you have never trusted. A -p session shows no workspace trust dialog and no per-server approval prompt, because there is nobody there to answer one. Piping an untrusted repository through a headless run therefore executes code that the repository supplies. Add --bare in CI and any time the checkout is not yours: it skips auto-discovery of hooks, skills, custom commands, subagents, plugins, MCP servers, auto memory and CLAUDE.md.

Why does my claude -p run deny every tool call?

Because on Claude Code v2.1.302 or later, claude -p runs start in Manual mode when nothing else sets a permission mode, and in Manual mode a call that needs approval is denied unless something approves it. Nothing can prompt you in a headless run. Fix it in one of three ways: list the tools you want with --allowedTools "Read,Edit,Bash"; set a baseline with --permission-mode, such as auto for classifier review, acceptEdits for writes, or dontAsk for a locked-down run; or supply an approver, either a PermissionRequest hook or an MCP tool passed with --permission-prompt-tool. Calls that need no approval at all, such as reads in your working directory and the read-only command set, run either way.

How do I get JSON out of claude -p?

Pass --output-format json for a structured envelope whose result field holds the text, alongside the session_id and usage metadata including total_cost_usd and a per-model cost breakdown. To constrain the shape of the answer itself, add --json-schema with a JSON Schema definition; the validated object then arrives in a structured_output field. Two cautions: if a run ends without valid structured output, for example because Claude declined, there is no structured_output field at all, so check it is present before using it; and Claude Code treats the schema's format keyword as an annotation and does not enforce it. For token-by-token output use --output-format stream-json with --verbose and --include-partial-messages.

Why did my claude -p run exit before the background work finished?

A headless run waits for background work Claude started, but the wait is capped. By default Claude Code stops whatever is still running after 10 minutes of continuous idle waiting and drops its partial result; raise or remove the cap with CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS, setting it to 0 to wait without one. A background command the main conversation started is the exception, and suspends the cap until it exits or hits its time limit. A separate trap: when a subagent's long command moves to the background at its timeout, the run can exit with code 0 before it finishes, so raise BASH_DEFAULT_TIMEOUT_MS above the command's run time. A -p run never waits for MCP work in the background, and a backgrounded MCP call's result is lost.

Is headless mode the same as the Agent SDK?

They are two surfaces of one thing. The Agent SDK gives you the same tools, agent loop and context management that power Claude Code, and claude -p is its CLI surface, documented on the page called Run Claude Code programmatically. Reach for the CLI when a shell pipeline is the natural shape: pipe something in, get text or JSON out, branch on the exit code. Move to the Python or TypeScript packages when you need things a process boundary makes awkward — a canUseTool callback that decides approvals in your own code, native message objects rather than parsed JSON lines, custom in-process tools, interrupt() on a running turn, or session persistence to your own storage.

Automation is downstream of judgment

A headless run does exactly what you specified, to whatever was in the repository, with nobody to catch the misunderstanding. Everything useful about it depends on skills you build interactively first: scoping a task, bounding what an agent may touch, and verifying what came back. That is what the free lessons are for.

Start the free lessons