Skip to main content
guidesSource-backed

Headless Claude Code Automation from Scripts and CI

A practical walkthrough of running Claude Code non-interactively with claude -p: bare mode, output formats (text, json, stream-json), JSON schema output, piping stdin, auto-approving tools, and authentication for scripts and CI.

by JPette1783·added 2026-06-05·
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://code.claude.com/docs/en/headless, https://github.com/JSONbored/awesome-claude/blob/main/content/guides/headless-claude-code-automation-from-scripts-and-ci.mdx
Safety notes
Headless runs act without a human present; scope tools tightly with --allowedTools or a locked-down permission mode (dontAsk) so the job cannot run more than intended., Bare mode (--bare) skips auto-discovery of hooks, skills, plugins, MCP servers, and CLAUDE.md, giving reproducible runs; pass only the context you need with explicit flags., Avoid broad Bash permissions in CI; prefer prefix-scoped rules like Bash(git diff *) and pipe data in so the agent does not need read permissions., Constrain which branches and paths the automation can touch, and review its output before it gates merges or deploys.
Privacy notes
Headless runs send the prompt, piped stdin, and repository context to the model provider; review what a job exposes before running it on private code., Bare mode skips OAuth and keychain reads, so authentication must come from ANTHROPIC_API_KEY or an apiKeyHelper; store these as CI secrets, never inline., CI logs can capture command output and the JSON result (including cost metadata); avoid printing secrets and mask sensitive variables.
Author
JPette1783
Submitted by
JPette1783
Claim status
unclaimed
Last verified
2026-06-05

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

63

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Needs review

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    No reviewed flag detected in metadata.

    Pending

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

Copy & paste

Copy-ready — paste the snippet to get started.

Adoption plan

Balanced adoption plan

Current risk score 24/100. Use staged verification before broader rollout.

Risk 24

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    No review metadata found; increase manual validation.

    Pending
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Missing required evidence: Metadata review. Risk score 31.

Risk 31

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Missing

Review metadata is missing.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required gaps: Metadata review

Decision timeline

Decision timeline · balanced

Blocking gaps: Check metadata review status. Risk 28.

Risk 28

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is missing.

Pending

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

Blockers: Check metadata review status

Prerequisite readiness

Prerequisite readiness

3 prerequisites to line up before setup. Have accounts and credentials ready first.

0/3 ready
Account & credentials1Install & runtime1General1

Safety & privacy surface

Safety & privacy surface

4 safety and 3 privacy notes across 5 risk areas. Review closely: credentials & tokens, permissions & scopes, third-party handling.

5 areas
  • SafetyPermissions & scopesHeadless runs act without a human present; scope tools tightly with --allowedTools or a locked-down permission mode (dontAsk) so the job cannot run more than intended.
  • SafetyExecution & processesBare mode (--bare) skips auto-discovery of hooks, skills, plugins, MCP servers, and CLAUDE.md, giving reproducible runs; pass only the context you need with explicit flags.
  • SafetyPermissions & scopesAvoid broad Bash permissions in CI; prefer prefix-scoped rules like Bash(git diff *) and pipe data in so the agent does not need read permissions.
  • SafetyLocal filesConstrain which branches and paths the automation can touch, and review its output before it gates merges or deploys.
  • PrivacyThird-party handlingHeadless runs send the prompt, piped stdin, and repository context to the model provider; review what a job exposes before running it on private code.
  • PrivacyCredentials & tokensBare mode skips OAuth and keychain reads, so authentication must come from ANTHROPIC_API_KEY or an apiKeyHelper; store these as CI secrets, never inline.
  • PrivacyCredentials & tokensCI logs can capture command output and the JSON result (including cost metadata); avoid printing secrets and mask sensitive variables.

Safety notes

  • Headless runs act without a human present; scope tools tightly with --allowedTools or a locked-down permission mode (dontAsk) so the job cannot run more than intended.
  • Bare mode (--bare) skips auto-discovery of hooks, skills, plugins, MCP servers, and CLAUDE.md, giving reproducible runs; pass only the context you need with explicit flags.
  • Avoid broad Bash permissions in CI; prefer prefix-scoped rules like Bash(git diff *) and pipe data in so the agent does not need read permissions.
  • Constrain which branches and paths the automation can touch, and review its output before it gates merges or deploys.

Privacy notes

  • Headless runs send the prompt, piped stdin, and repository context to the model provider; review what a job exposes before running it on private code.
  • Bare mode skips OAuth and keychain reads, so authentication must come from ANTHROPIC_API_KEY or an apiKeyHelper; store these as CI secrets, never inline.
  • CI logs can capture command output and the JSON result (including cost metadata); avoid printing secrets and mask sensitive variables.

Prerequisites

  • Claude Code installed in the environment where the script or CI job runs.
  • An authentication method that works headlessly: ANTHROPIC_API_KEY, a long-lived OAuth token, an apiKeyHelper, or a cloud provider's credentials.
  • jq or similar if you plan to parse JSON output in shell scripts.

Schema details

Install type
copy
Troubleshooting
No
Full copyable content
## Overview

Claude Code runs non-interactively when you pass `-p` (or `--print`) with a
prompt. This headless mode is how you use Claude Code in scripts, build steps,
and CI pipelines: pipe data in, get structured output back, and pre-approve the
tools the job needs. It uses the same agent loop and tools as an interactive
session.

## Basic usage

```bash
claude -p "What does the auth module do?"
```

All CLI options work with `-p`, including `--continue`, `--allowedTools`, and
`--output-format`.

## Bare mode for reproducible runs

`--bare` skips auto-discovery of hooks, skills, plugins, MCP servers, auto
memory, and CLAUDE.md, so a job behaves the same on every machine. Pass only the
context you need:

```bash
claude --bare -p "Summarize this file" --allowedTools "Read"
```

In bare mode, authentication must come from `ANTHROPIC_API_KEY` or an
`apiKeyHelper` in `--settings`; it skips OAuth and keychain reads. Load extra
context with flags like `--append-system-prompt`, `--settings`, `--mcp-config`,
`--agents`, or `--plugin-dir`. Bare mode is the recommended mode for scripted
calls.

## Pipe data through Claude

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

Piped stdin is capped at 10MB; for larger inputs, write to a file and reference
its path in the prompt.

## Structured output

```bash
# JSON with result, session id, and metadata (including total_cost_usd)
claude -p "Summarize this project" --output-format json | jq -r '.result'

# Conform to a 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"]}' \
  | jq '.structured_output'
```

Use `--output-format stream-json --verbose --include-partial-messages` for
newline-delimited streaming events.

## Auto-approve tools safely

```bash
claude --bare -p "Run the test suite and summarize any failures" \
  --permission-mode dontAsk \
  --allowedTools "Bash(npm test),Bash(git diff *)"
```

For a locked-down CI baseline, use `--bare` so repository-local instructions,
hooks, skills, plugins, MCP servers, and CLAUDE.md cannot change the run. Pass a
permission mode: `--permission-mode dontAsk` denies anything not in your allow
rules or the read-only command set. `--allowedTools` uses permission-rule syntax,
so `Bash(git diff *)` allows a prefix (note the space before `*`). Avoid broad
rules such as `Bash,Read,Edit` in CI because they allow arbitrary shell commands
and broad repository reads or edits.

## Continue conversations

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

Note: user-invoked skills like `/code-review` are interactive-only; in `-p` mode,
describe the task directly.

## Source

- Run Claude Code programmatically: https://code.claude.com/docs/en/headless

About this resource

Overview

Claude Code runs non-interactively when you pass -p (or --print) with a prompt. This headless mode is how you use Claude Code in scripts, build steps, and CI pipelines: pipe data in, get structured output back, and pre-approve the tools the job needs. It uses the same agent loop and tools as an interactive session.

Basic usage

claude -p "What does the auth module do?"

All CLI options work with -p, including --continue, --allowedTools, and --output-format.

Bare mode for reproducible runs

--bare skips auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md, so a job behaves the same on every machine. Pass only the context you need:

claude --bare -p "Summarize this file" --allowedTools "Read"

In bare mode, authentication must come from ANTHROPIC_API_KEY or an apiKeyHelper in --settings; it skips OAuth and keychain reads. Load extra context with flags like --append-system-prompt, --settings, --mcp-config, --agents, or --plugin-dir. Bare mode is the recommended mode for scripted calls.

Pipe data through Claude

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

Piped stdin is capped at 10MB; for larger inputs, write to a file and reference its path in the prompt.

Structured output

# JSON with result, session id, and metadata (including total_cost_usd)
claude -p "Summarize this project" --output-format json | jq -r '.result'

# Conform to a 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"]}' \
  | jq '.structured_output'

Use --output-format stream-json --verbose --include-partial-messages for newline-delimited streaming events.

Auto-approve tools safely

claude --bare -p "Run the test suite and summarize any failures" \
  --permission-mode dontAsk \
  --allowedTools "Bash(npm test),Bash(git diff *)"

For a locked-down CI baseline, use --bare so repository-local instructions, hooks, skills, plugins, MCP servers, and CLAUDE.md cannot change the run. Pass a permission mode: --permission-mode dontAsk denies anything not in your allow rules or the read-only command set. --allowedTools uses permission-rule syntax, so Bash(git diff *) allows a prefix (note the space before *). Avoid broad rules such as Bash,Read,Edit in CI because they allow arbitrary shell commands and broad repository reads or edits.

Continue conversations

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

Note: user-invoked skills like /code-review are interactive-only; in -p mode, describe the task directly.

Source

Source citations

Add this badge to your README

Show that Headless Claude Code Automation from Scripts and CI is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/guides/headless-claude-code-automation-from-scripts-and-ci.svg)](https://heyclau.de/entry/guides/headless-claude-code-automation-from-scripts-and-ci)

How it compares

Headless Claude Code Automation from Scripts and CI side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

2 trust signals differ across this comparison (Source provenance, Submitter).

Field

A practical walkthrough of running Claude Code non-interactively with claude -p: bare mode, output formats (text, json, stream-json), JSON schema output, piping stdin, auto-approving tools, and authentication for scripts and CI.

Open dossier

Automate business and engineering processes with Claude Code: headless `claude -p` runs, GitHub Actions, scheduled routines, and in-session loops, with permission and output-format guidance.

Open dossier

Configure Claude Code auto mode hard-deny rules that block high-risk actions unconditionally, complement soft-deny prompts and team permission policy.

Open dossier

A practical walkthrough of Claude Code channels: how an MCP-server channel pushes messages, alerts, and webhooks into a running session, how to install and enable Telegram, Discord, or iMessage, sender allowlists, and enterprise controls.

Open dossier
Next steps
Trust
Review statusNot reviewedNot reviewedNot reviewedNot reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceDiffersSource-backedSource-backedSubmission linkedSource submissionSource-backed
SubmitterDiffersJPette1783kiannidevJPette1783
Install riskReview firstReview firstReview firstReview first
Notes Safety ✓ Privacy ✓ Safety ✓ Privacy ✓ Safety ✓ Privacy ✓ Safety ✓ Privacy ✓
Brand
Categoryguidesguidesguidesguides
SourceSource-backedSource-backedSource-backedSource-backed
AuthorJPette1783JSONboredkiannidevJPette1783
Added2026-06-052025-10-272026-06-132026-06-05
Platforms
Harness
Source repo
Safety notesHeadless runs act without a human present; scope tools tightly with --allowedTools or a locked-down permission mode (dontAsk) so the job cannot run more than intended. Bare mode (--bare) skips auto-discovery of hooks, skills, plugins, MCP servers, and CLAUDE.md, giving reproducible runs; pass only the context you need with explicit flags. Avoid broad Bash permissions in CI; prefer prefix-scoped rules like Bash(git diff *) and pipe data in so the agent does not need read permissions. Constrain which branches and paths the automation can touch, and review its output before it gates merges or deploys.Automated runs can execute Bash and edit/write files. Scope `--allowedTools` and `--permission-mode` tightly; `dontAsk` denies anything outside your allow rules. Routines run with no approval prompts, so limit repositories, connectors, and network access to what each task actually needs.Hard-deny rules block regardless of user intent or allow exceptions—misconfiguration can halt legitimate workflows. Auto mode classifiers can still fail open with evaluation errors; hard deny is not a substitute for branch protection and CI gates. Do not rely on auto mode alone for secrets handling; deny credential reads and outbound bulk transfers explicitly.Channel input is untrusted external content; treat incoming messages as data, not as instructions that should widen permissions. Events only arrive while the session is open; for unattended use, --dangerously-skip-permissions bypasses prompts and should be used only in trusted environments. Each channel keeps a sender allowlist; only paired/allowlisted IDs can push messages, and anyone who can reply can also approve permission relays if enabled, so allowlist only trusted senders.
Privacy notesHeadless runs send the prompt, piped stdin, and repository context to the model provider; review what a job exposes before running it on private code. Bare mode skips OAuth and keychain reads, so authentication must come from ANTHROPIC_API_KEY or an apiKeyHelper; store these as CI secrets, never inline. CI logs can capture command output and the JSON result (including cost metadata); avoid printing secrets and mask sensitive variables.Headless and CI runs read your codebase and any piped stdin; GitHub Actions and routines need an `ANTHROPIC_API_KEY` or provider credentials stored as secrets, never hardcoded in workflow files. Routine actions appear under your linked GitHub and connector identities, so commits, PRs, and connector writes are attributed to you.Auto mode classifiers evaluate tool names, arguments, and session context that may include file paths and repository metadata. Denial messages and debug logs can retain snippets of blocked commands; restrict log access on shared machines. Managed settings sync may expose rule text to all enrolled clients—avoid embedding internal codenames you do not want widely visible.A channel is an MCP server you configure with your own credentials; tokens are stored locally (for example ~/.claude/channels/telegram/.env). Incoming and outgoing messages pass through the third-party platform (Telegram, Discord, Apple Messages); review what data flows there. The iMessage channel reads your Messages database and requires Full Disk Access; understand that exposure before enabling it.
Prerequisites
  • Claude Code installed in the environment where the script or CI job runs.
  • An authentication method that works headlessly: ANTHROPIC_API_KEY, a long-lived OAuth token, an apiKeyHelper, or a cloud provider's credentials.
  • jq or similar if you plan to parse JSON output in shell scripts.
— none listed
  • Claude Code with auto mode available on your provider and organization policy.
  • Permission to edit project or managed settings.json for the target repositories.
  • A list of actions that must never run without explicit human approval.
  • Pilot engineers who can trigger both allowed and blocked auto mode actions safely.
  • Claude Code v2.1.80 or later, authenticated through claude.ai or a Console API key (channels are not available on Bedrock, Vertex AI, or Foundry).
  • Bun installed, since the channel plugins are Bun scripts.
  • On Team, Enterprise, or managed Console orgs, an admin must enable channels first.
Install
Config
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.