headless-testing
Overview
Claude Code can run in “headless” (non-interactive) mode using the -p/--print flag. This is essential for testing agents during development since agent changes require a session restart.
Task 2 Confirmation: ✅ Verified
Claude can run in headless mode via CLI:
claude -p "What is 2+2?"# Output: 4Basic Usage
Simple Prompt
claude -p "Your prompt here"The response is printed to stdout and the command exits immediately.
Advanced Options
Output Formats
Text (default)
claude -p "Explain recursion"JSON
claude -p "List three colors" --output-format jsonStreaming JSON
claude -p "Write a story" --output-format stream-jsonModel Selection
# Use Haiku for fast, simple tasksclaude -p "Fix this typo: recieve" --model haiku
# Use Opus for complex reasoningclaude -p "Analyze this architecture" --model opus
# Use Sonnet (default, balanced)claude -p "Review this code" --model sonnetTool Control
Restrict to specific tools:
claude -p "Read file.txt" --tools "Read,Grep"Disable all tools:
claude -p "Just answer this question" --tools ""Allow specific tool patterns:
claude -p "Use git" --allowed-tools "Bash(git:*)"Deny specific tools:
claude -p "No file edits" --disallowed-tools "Edit,Write"System Prompts
Add custom system prompt:
claude -p "Explain OOP" --system-prompt "You are a teacher explaining to beginners"Append to default system prompt:
claude -p "Review code" --append-system-prompt "Focus on security issues"Conversation Continuity
Continue most recent conversation:
claude -p "Tell me a joke"claude -p "Explain it" --continueResume specific session:
claude -p "Continue working" --resume <session-id>Fork conversation (new session ID):
claude -p "Try different approach" --resume <session-id> --fork-sessionPermission Modes
# Auto-accept all editsclaude -p "Fix bugs" --permission-mode acceptEdits
# Skip all permissions (use in trusted sandboxes only)claude -p "Make changes" --permission-mode bypassPermissions
# Don't ask for permissionsclaude -p "Just tell me" --permission-mode dontAsk
# Plan modeclaude -p "Plan implementation" --permission-mode planMCP Configuration
Load specific MCP config:
claude -p "Query database" --mcp-config ./custom-mcp.jsonUse only specified config:
claude -p "Use only this MCP" --mcp-config ./mcp.json --strict-mcp-configSettings Override
Load settings from file:
claude -p "Run with custom settings" --settings ./test-settings.jsonLoad settings from JSON string:
claude -p "Test" --settings '{"verbose":true}'Agent Development Workflow
The Problem
Agent files (.claude/agents/*.md) are loaded when Claude Code starts. Changes to agent files require restarting the session to take effect in interactive mode.
The Solution: Headless Testing
You can test agent changes without restarting the interactive session:
# 1. Edit your agent filevim .claude/agents/my-agent.md
# 2. Test in headless mode (loads fresh agent definitions)claude -p "Test my agent functionality"
# 3. Iterate rapidlyvim .claude/agents/my-agent.mdclaude -p "Test again with different input"
# 4. Once satisfied, restart interactive session for production useTesting Workflow Example
# Create a test agentcat > .claude/agents/test-reviewer.md << 'EOF'---name: test-reviewerdescription: Reviews code for test coverage issuestools: Read, Grepmodel: haiku---
You review code and identify missing test coverage.Focus on functions without corresponding tests.EOF
# Test the agent in headless modeclaude -p "Review test coverage in src/"
# Refine the agent based on resultsvim .claude/agents/test-reviewer.md
# Test againclaude -p "Review test coverage in src/ and suggest specific test cases"
# Continue iterating...Practical Testing Patterns
Quick Validation
# Test that agent loads without errorsclaude -p "Hello" --output-format jsonAgent-Specific Testing
# Test agent with typical taskclaude -p "Review this file for security issues" --tools "Read,Grep"Output Verification
# Capture output for analysisclaude -p "Generate report" --output-format json > output.jsoncat output.json | jq '.response'Integration Testing
# Test with specific MCP serversclaude -p "Query temporal bridge" --mcp-config test-mcp.jsonPerformance Testing
# Time the executiontime claude -p "Complex analysis task"Regression Testing
# Save baseline outputclaude -p "Test case 1" > baseline.txt
# After changes, compareclaude -p "Test case 1" > current.txtdiff baseline.txt current.txtPiping and Scripting
Input from stdin
cat prompt.txt | claude -pPipe to other tools
claude -p "List files" | grep ".ts$"Scripted testing
#!/bin/bashfor test_case in test_cases/*.txt; do echo "Testing: $test_case" claude -p "$(cat $test_case)" --output-format json > "results/$(basename $test_case).json"doneJSON processing
claude -p "Generate JSON data" --output-format json | jq '.result'Environment Setup for Testing
Test Configuration File
{ "model": "haiku", "verbose": false, "tools": ["Read", "Grep"], "permissionMode": "bypassPermissions"}Usage:
claude -p "Test" --settings test-config.jsonTest MCP Configuration
{ "mcpServers": { "test-server": { "command": "node", "args": ["test-mcp-server.js"] } }}Usage:
claude -p "Test MCP" --mcp-config test-mcp.jsonDirectory Isolation
# Test in isolated directorymkdir test-envcd test-envcp ../.claude/agents/my-agent.md .claude/agents/claude -p "Test in isolation"cd ..Debugging
Enable debug mode
# All debug outputclaude -p "Debug this" --debug
# Specific categoriesclaude -p "Debug API" --debug api
# Multiple categoriesclaude -p "Debug" --debug "api,hooks"
# Exclude categoriesclaude -p "Debug" --debug "!statsig,!file"Verbose output
claude -p "Show details" --verboseMCP debugging
claude -p "Test MCP" --debug mcpBest Practices
1. Fast Iteration
Use headless mode for rapid agent development:
- Edit agent
- Test in headless mode
- Iterate quickly
- Only restart interactive session when satisfied
2. Use Appropriate Models
haiku: Fast testing of simple agent logicsonnet: Realistic testing of balanced agentsopus: Test complex reasoning capabilities
3. Isolate Tests
- Use specific tool restrictions
- Test one capability at a time
- Use minimal prompts for focused testing
4. Capture Results
- Save outputs for comparison
- Use JSON format for structured testing
- Build regression test suites
5. Security
- Use
--dangerously-skip-permissionsonly in sandboxes - Test permission handling separately
- Verify tool restrictions work as expected
Common Issues
Agent Not Found
Problem: Agent changes not reflected Solution: Headless mode loads fresh agent definitions - this shouldn’t happen
Tool Access Denied
Problem: Agent can’t use required tools
Solution: Add tools to agent tools: field or use --tools flag in testing
Session Conflicts
Problem: Headless and interactive sessions conflict
Solution: Use --session-id to separate test sessions
Output Format Issues
Problem: Can’t parse output
Solution: Use --output-format json for structured output
Summary
Headless mode (claude -p) is a powerful tool for agent development:
- ✅ Confirmed working: Basic functionality verified
- ⚡ Fast iteration: No session restarts needed for testing
- 🔧 Flexible: Many configuration options
- 📊 Scriptable: Easy to automate testing
- 🔒 Isolated: Test without affecting interactive sessions
Use it to rapidly develop and test agents before deploying them in interactive sessions.