# Headless Mode and Agent SDK

> Use the Agent SDK to run Claude Code programmatically from the CLI, Python, or TypeScript.

The Agent SDK 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 and TypeScript packages for full programmatic control.

**Note**: The CLI was previously called "headless mode." The `-p` flag and all CLI options work the same way.

## Basic Usage

Pass `-p` (or `--print`) with your prompt and any CLI options:

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

All CLI options work with `-p`, including:
- `--continue` for continuing conversations
- `--allowedTools` for auto-approving tools
- `--output-format` for structured output

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

## Output Formats

Use `--output-format` to control how responses are returned:

| Format        | Description                                    |
| :------------ | :--------------------------------------------- |
| `text`        | Plain text output (default)                    |
| `json`        | Structured JSON with result, session ID, metadata |
| `stream-json` | Newline-delimited JSON for real-time streaming |

### JSON Output
```bash
claude -p "Summarize this project" --output-format json
```

### JSON with Schema
Get output conforming to a specific schema:
```bash
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"]}'
```

### Parsing with jq
```bash
# Extract the text result
claude -p "Summarize this project" --output-format json | jq -r '.result'

# Extract structured output
claude -p "Extract function names from auth.py" \
  --output-format json \
  --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
  | jq '.structured_output'
```

## Auto-Approve Tools

Use `--allowedTools` to let Claude use certain tools without prompting:

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

### Create a Commit
```bash
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 `:*` suffix enables prefix matching, so `Bash(git diff:*)` allows any command starting with `git diff`.

**Note**: User-invoked skills like `/commit` and built-in commands are only available in interactive mode. In `-p` mode, describe the task you want to accomplish instead.

## Customize the System Prompt

### Append to Default Prompt
Use `--append-system-prompt` to add instructions while keeping Claude Code's default behavior:

```bash
gh pr diff "$1" | claude -p \
  --append-system-prompt "You are a security engineer. Review for vulnerabilities." \
  --output-format json
```

### Replace the System Prompt
Use `--system-prompt` to fully replace the default prompt.

## Continue Conversations

### Continue Most Recent
Use `--continue` to continue the most recent conversation:

```bash
# First request
claude -p "Review this codebase for performance issues"

# Continue the most recent conversation
claude -p "Now focus on the database queries" --continue
claude -p "Generate a summary of all issues found" --continue
```

### Resume Specific Session
If running multiple conversations, capture the session ID:

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

## CI/CD Examples

### GitHub Actions
```yaml
- name: Code Review with Claude
  run: |
    claude -p "Review the changes in this PR and suggest improvements" \
      --allowedTools "Read,Grep,Glob" \
      --output-format json > review.json
```

### GitLab CI/CD
```yaml
code_review:
  script:
    - |
      claude -p "Analyze the code changes and check for security issues" \
        --allowedTools "Read,Grep,Glob" \
        --output-format json
```

### Automated Testing
```bash
#!/bin/bash
# Run tests and have Claude fix failures

claude -p "Run the test suite, analyze any failures, and fix the issues" \
  --allowedTools "Bash(npm:*),Read,Edit" \
  --output-format json
```

### Generate Documentation
```bash
claude -p "Generate API documentation for the src/api directory" \
  --allowedTools "Read,Write,Glob" \
  --output-format text > docs/API.md
```

## Python and TypeScript SDKs

For more programmatic control with:
- Structured outputs
- Tool approval callbacks
- Native message objects
- Event streaming

See the full Agent SDK documentation at https://platform.claude.com/docs/en/agent-sdk/overview

### Python Example
```python
from claude_code_sdk import Agent

agent = Agent()
result = agent.run("Explain what this code does", files=["main.py"])
print(result.text)
```

### TypeScript Example
```typescript
import { Agent } from '@anthropic-ai/claude-code-sdk';

const agent = new Agent();
const result = await agent.run("Explain what this code does", { files: ["main.py"] });
console.log(result.text);
```

## Useful Patterns

### Piping Input
```bash
cat error.log | claude -p "Analyze this error log and suggest fixes"
```

### Environment Variables for Authentication
```bash
export ANTHROPIC_API_KEY="your-key"
claude -p "Your prompt here"
```

### Batch Processing
```bash
for file in src/*.py; do
  claude -p "Review $file for security issues" \
    --allowedTools "Read" \
    --output-format json >> reviews.jsonl
done
```

## Grid Integration Opportunities

<!-- Placeholder for Grid-specific integration notes -->
