Headless Claude Code and Agent SDK
Run Claude Code non-interactively and embed its agent loop safely in scripts, CI, and applications.
Claude offers two related automation surfaces:
- Print/headless mode runs the Claude Code CLI non-interactively.
- The Claude Agent SDK embeds the same agent loop in TypeScript or Python.
Headless mode
The smallest invocation is:
claude -p "Read the failing test output, fix the root cause, and rerun that test."For automation that should not inherit repository extensions:
claude --bare -p "Analyze this repository and return a migration plan." \
--tools "Read,Glob,Grep"Ordinary -p can load repository hooks, plugins, MCP servers, memory, and
CLAUDE.md without an interactive trust dialog. --bare gives CI and
untrusted-repository workflows a smaller starting surface. Use --tools to
restrict availability; --allowedTools auto-approves matching tools but does
not itself make every unlisted tool unavailable.
Machine-readable output:
claude --bare -p "Summarize changed packages" --output-format json
claude --bare -p "Run the migration" --output-format stream-json --verboseUse --json-schema when downstream automation requires validated structured
output. See Headless mode.
Claude Agent SDK
Install the current packages:
npm install @anthropic-ai/claude-agent-sdk
pip install claude-agent-sdkThe SDK supports:
- tool allow/deny and custom permission callbacks,
- sandbox settings,
- MCP servers and plugins,
- skills, hooks, and subagents,
- structured output,
- resumable or forked sessions,
- file checkpointing,
- turn and cost budgets,
- model, fallback, thinking, and effort controls.
Use the Agent SDK overview and language references for current types.
Production boundaries
- Set
max_turns,max_budget_usd, or task budgets. - Restrict tools explicitly; an allow list does not always mean unlisted tools are impossible unless permission behavior also denies them.
- Enable sandboxing with
failIfUnavailablewhen isolation is mandatory. - Treat loaded hooks and plugins as executable dependencies.
- Persist session state intentionally and define retention for transcripts.
- Require a deterministic success check outside the model’s final text.
When to choose which
| Need | Use |
|---|---|
| One command in CI or a script | claude -p |
| Minimal extension surface | claude --bare -p |
| Streaming shell pipeline | --output-format stream-json |
| Typed application integration | Claude Agent SDK |
| Simple repeated repository loop | Ralph loop or a routine |