1# Headless mode1# Run Claude Code programmatically
2 2
3> Run Claude Code programmatically without interactive UI3> Use the Agent SDK to run Claude Code programmatically from the CLI, Python, or TypeScript.
4 4
5## Overview5The [Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview) gives you the same tools, agent loop, and context management that power Claude Code. It's available as a CLI for scripts and CI/CD, or as [Python](https://platform.claude.com/docs/en/agent-sdk/python) and [TypeScript](https://platform.claude.com/docs/en/agent-sdk/typescript) packages for full programmatic control.
6 6
7The headless mode allows you to run Claude Code programmatically from command line scripts and automation tools without any interactive UI.7<Note>
8 The CLI was previously called "headless mode." The `-p` flag and all CLI options work the same way.
9</Note>
8 10
9## Basic usage11To run Claude Code programmatically from the CLI, pass `-p` with your prompt and any [CLI options](/en/cli-reference):
10
11The primary command-line interface to Claude Code is the `claude` command. Use the `--print` (or `-p`) flag to run in non-interactive mode and print the final result:
12 12
13```bash theme={null}13```bash theme={null}
14claude -p "Stage my changes and write a set of commits for them" \14claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
15 --allowedTools "Bash,Read" \
16 --permission-mode acceptEdits
17```15```
18 16
19## Configuration Options17This page covers using the Agent SDK via the CLI (`claude -p`). For the Python and TypeScript SDK packages with structured outputs, tool approval callbacks, and native message objects, see the [full Agent SDK documentation](https://platform.claude.com/docs/en/agent-sdk/overview).
20 18
21Headless mode leverages all the CLI options available in Claude Code. Here are the key ones for automation and scripting:19## Basic usage
22
23| Flag | Description | Example |
24| :------------------------- | :---------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------ |
25| `--print`, `-p` | Run in non-interactive mode | `claude -p "query"` |
26| `--output-format` | Specify output format (`text`, `json`, `stream-json`) | `claude -p --output-format json` |
27| `--resume`, `-r` | Resume a conversation by session ID | `claude --resume abc123` |
28| `--continue`, `-c` | Continue the most recent conversation | `claude --continue` |
29| `--verbose` | Enable verbose logging | `claude --verbose` |
30| `--append-system-prompt` | Append to system prompt (only with `--print`) | `claude --append-system-prompt "Custom instruction"` |
31| `--allowedTools` | Tools that execute without prompting for permission (use `--tools` to restrict available tools) | `claude --allowedTools mcp__slack mcp__filesystem`<br /><br />`claude --allowedTools "Bash(npm install),mcp__filesystem"` |
32| `--disallowedTools` | Tools removed from the model's context (cannot be used) | `claude --disallowedTools mcp__splunk mcp__github`<br /><br />`claude --disallowedTools "Bash(git commit),mcp__github"` |
33| `--mcp-config` | Load MCP servers from a JSON file | `claude --mcp-config servers.json` |
34| `--permission-prompt-tool` | MCP tool for handling permission prompts (only with `--print`) | `claude --permission-prompt-tool mcp__auth__prompt` |
35 20
36For a complete list of CLI options and features, see the [CLI reference](/en/cli-reference) documentation.21Add the `-p` (or `--print`) flag to any `claude` command to run it non-interactively. All [CLI options](/en/cli-reference) work with `-p`, including:
37 22
38## Multi-turn conversations23* `--continue` for [continuing conversations](#continue-conversations)
24* `--allowedTools` for [auto-approving tools](#auto-approve-tools)
25* `--output-format` for [structured output](#get-structured-output)
39 26
40For multi-turn conversations, you can resume conversations or continue from the most recent session:27This example asks Claude a question about your codebase and prints the response:
41 28
42```bash theme={null}29```bash theme={null}
43# Continue the most recent conversation30claude -p "What does the auth module do?"
44claude --continue "Now refactor this for better performance"
45
46# Resume a specific conversation by session ID
47claude --resume 550e8400-e29b-41d4-a716-446655440000 "Update the tests"
48
49# Resume in non-interactive mode
50claude --resume 550e8400-e29b-41d4-a716-446655440000 "Fix all linting issues" --no-interactive
51```31```
52 32
53## Output Formats33## Examples
54 34
55### Text Output (Default)35These examples highlight common CLI patterns.
56 36
57```bash theme={null}37### Get structured output
58claude -p "Explain file src/components/Header.tsx"
59# Output: This is a React component showing...
60```
61 38
62### JSON Output39Use `--output-format` to control how responses are returned:
63 40
64Returns structured data including metadata:41* `text` (default): plain text output
42* `json`: structured JSON with result, session ID, and metadata
43* `stream-json`: newline-delimited JSON for real-time streaming
65 44
66```bash theme={null}45```bash theme={null}
67claude -p "How does the data layer work?" --output-format json46claude -p "Summarize this project" --output-format json
68```
69
70Response format:
71
72```json theme={null}
73{
74 "type": "result",
75 "subtype": "success",
76 "total_cost_usd": 0.003,
77 "is_error": false,
78 "duration_ms": 1234,
79 "duration_api_ms": 800,
80 "num_turns": 6,
81 "result": "The response text here...",
82 "session_id": "abc123"
83}
84```47```
85 48
86### Streaming JSON Output49### Auto-approve tools
87 50
88Streams each message as it is received:51Use `--allowedTools` to let Claude use certain tools without prompting. This example runs a test suite and fixes failures, allowing Claude to execute Bash commands and read/edit files without asking for permission:
89 52
90```bash theme={null}53```bash theme={null}
91claude -p "Build an application" --output-format stream-json54claude -p "Run the test suite and fix any failures" \
55 --allowedTools "Bash,Read,Edit"
92```56```
93 57
94Each conversation begins with an initial `init` system message, followed by a list of user and assistant messages, followed by a final `result` system message with stats. Each message is emitted as a separate JSON object.58### Run slash commands
95
96## Input Formats
97 59
98### Text Input (Default)60Run [slash commands](/en/slash-commands) non-interactively. This example generates a commit for staged changes using the `/commit` slash command:
99 61
100```bash theme={null}62```bash theme={null}
101# Direct argument63claude -p "/commit"
102claude -p "Explain this code"
103
104# From stdin
105echo "Explain this code" | claude -p
106```64```
107 65
108### Streaming JSON Input66### Customize the system prompt
109 67
110A stream of messages provided via `stdin` where each message represents a user turn. This allows multiple turns of a conversation without re-launching the `claude` binary and allows providing guidance to the model while it is processing a request.68Use `--append-system-prompt` to add instructions while keeping Claude Code's default behavior. This example pipes a PR diff to Claude and instructs it to review for security vulnerabilities:
111
112Each message is a JSON 'User message' object, following the same format as the output message schema. Messages are formatted using the [`jsonl`](https://jsonlines.org/) format where each line of input is a complete JSON object. Streaming JSON input requires `-p` and `--output-format stream-json`.
113 69
114```bash theme={null}70```bash theme={null}
115echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"Explain this code"}]}}' | claude -p --output-format=stream-json --input-format=stream-json --verbose71gh pr diff "$1" | claude -p \
72 --append-system-prompt "You are a security engineer. Review for vulnerabilities." \
73 --output-format json
116```74```
117 75
118## Agent Integration Examples76See [system prompt flags](/en/cli-reference#system-prompt-flags) for more options including `--system-prompt` to fully replace the default prompt.
119
120### SRE Incident Response Bot
121 77
122```bash theme={null}78### Continue conversations
123#!/bin/bash
124
125# Automated incident response agent
126investigate_incident() {
127 local incident_description="$1"
128 local severity="${2:-medium}"
129
130 claude -p "Incident: $incident_description (Severity: $severity)" \
131 --append-system-prompt "You are an SRE expert. Diagnose the issue, assess impact, and provide immediate action items." \
132 --output-format json \
133 --allowedTools "Bash,Read,WebSearch,mcp__datadog" \
134 --mcp-config monitoring-tools.json
135}
136
137# Usage
138investigate_incident "Payment API returning 500 errors" "high"
139```
140 79
141### Automated Security Review80Use `--continue` to continue the most recent conversation, or `--resume` with a session ID to continue a specific conversation. This example runs a review, then sends follow-up prompts:
142 81
143```bash theme={null}82```bash theme={null}
144# Security audit agent for pull requests83# First request
145audit_pr() {84claude -p "Review this codebase for performance issues"
146 local pr_number="$1"85
147 86# Continue the most recent conversation
148 gh pr diff "$pr_number" | claude -p \87claude -p "Now focus on the database queries" --continue
149 --append-system-prompt "You are a security engineer. Review this PR for vulnerabilities, insecure patterns, and compliance issues." \88claude -p "Generate a summary of all issues found" --continue
150 --output-format json \
151 --allowedTools "Read,Grep,WebSearch"
152}
153
154# Usage and save to file
155audit_pr 123 > security-report.json
156```89```
157 90
158### Multi-turn Legal Assistant91If you're running multiple conversations, capture the session ID to resume a specific one:
159 92
160```bash theme={null}93```bash theme={null}
161# Legal document review with session persistence94session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
162session_id=$(claude -p "Start legal review session" --output-format json | jq -r '.session_id')95claude -p "Continue that review" --resume "$session_id"
163
164# Review contract in multiple steps
165claude -p --resume "$session_id" "Review contract.pdf for liability clauses"
166claude -p --resume "$session_id" "Check compliance with GDPR requirements"
167claude -p --resume "$session_id" "Generate executive summary of risks"
168```96```
169 97
170## Best Practices98## Next steps
171
172* **Use JSON output format** for programmatic parsing of responses:
173
174 ```bash theme={null}
175 # Parse JSON response with jq
176 result=$(claude -p "Generate code" --output-format json)
177 code=$(echo "$result" | jq -r '.result')
178 cost=$(echo "$result" | jq -r '.cost_usd')
179 ```
180
181* **Handle errors gracefully** - check exit codes and stderr:
182
183 ```bash theme={null}
184 if ! claude -p "$prompt" 2>error.log; then
185 echo "Error occurred:" >&2
186 cat error.log >&2
187 exit 1
188 fi
189 ```
190
191* **Use session management** for maintaining context in multi-turn conversations
192
193* **Consider timeouts** for long-running operations:
194 99
195 ```bash theme={null}100<CardGroup cols={2}>
196 timeout 300 claude -p "$complex_prompt" || echo "Timed out after 5 minutes"101 <Card title="Agent SDK quickstart" icon="play" href="https://platform.claude.com/docs/en/agent-sdk/quickstart">
197 ```102 Build your first agent with Python or TypeScript
103 </Card>
198 104
199* **Respect rate limits** when making multiple requests by adding delays between calls105 <Card title="CLI reference" icon="terminal" href="/en/cli-reference">
106 Explore all CLI flags and options
107 </Card>
200 108
201## Related Resources109 <Card title="GitHub Actions" icon="github" href="/en/github-actions">
110 Use the Agent SDK in GitHub workflows
111 </Card>
202 112
203* [CLI usage and controls](/en/cli-reference) - Complete CLI documentation113 <Card title="GitLab CI/CD" icon="gitlab" href="/en/gitlab-ci-cd">
204* [Common workflows](/en/common-workflows) - Step-by-step guides for common use cases114 Use the Agent SDK in GitLab pipelines
115 </Card>
116</CardGroup>
205 117
206 118
207---119---