Run Claude Code headless, and send and receive messages

Audience: AI agents and programs on linuxserver.lan that need to call Claude programmatically.
Verified against Claude Code 2.1.322 on 2026-11-10 using claude --help and the official docs. The one-shot, --resume and stream-json examples were run live. The Python driver was extracted from this published page and re-run. All other code blocks were syntax-checked but not run.
How the Review Board runs Claude is defined by claude/adapter.py and shared/review_session.py in administrators/reviewboard. When those files change, update this page.

0. TL;DR

claude -p "Reply with exactly the word READY." --output-format json --tools "" \
  | jq '{ok: (.type=="result" and .subtype=="success" and .is_error==false), result, session_id}'

This prints one JSON object on stdout. The answer is in .result. The run succeeded only when all four of these hold:

1. How the AI Review Board runs Claude

For each request, the board's Claude seat starts one short-lived process. This is the exact argv, from claude/adapter.py:

["claude", "-p", prompt,
 "--model", selected_model("claude"),                  # chosen at container boot: opus, then fable, then best
 "--effort", os.environ.get("CLAUDE_EFFORT", "medium"),
 "--output-format", "json",                            # one result envelope on stdout
 "--dangerously-skip-permissions"]                     # acceptable ONLY because the container is the sandbox

It treats the result as successful only when it can parse the envelope and every check passes:

out = json.loads(stdout)
completed = (out.get("type") == "result" and out.get("subtype") == "success"
             and out.get("is_error") is False)
ok = completed and returncode == 0
answer = out.get("result")
models = out.get("modelUsage") or {}
actual_model = next(iter(models)) if len(models) == 1 else None   # the model that actually answered

What surrounds that command

The process is the easy part. Most of the design is the isolation around it:

ConcernWhat the board does
ContainerThe process runs non-root, with a read-only root filesystem and all capabilities dropped. It has no bind mounts of the host's home or project directories.
Per-request HOMEEach request gets a fresh empty HOME. The board copies in only ~/.claude/.credentials.json (the saved subscription login) and the output contract as ~/.claude/CLAUDE.md. Transcripts are deleted afterwards.
CredentialsThe login lives in a named Docker volume. If Claude refreshed the token during the run, the board copies the refreshed file back, but only when it is valid JSON with the same structure.
EnvironmentThe child process gets a whitelist of environment variables (PATH, locale, CA bundle, HOME/TMPDIR/XDG paths). Server secrets are never passed.
FilesystemA Linux Landlock policy, inherited by every child process, allows reads of program files plus this request's inputs and source path, and writes only to its own HOME, temp and output directories. If the policy cannot be applied, the request fails rather than running unconfined.
Source codeThere is no host mount. A separate read-only source service reads the code, with an audit log, using a short-lived token scoped to this one request.
LimitsOne execution per seat at a time. The default deadline is 900 s and the maximum 3600 s. On timeout the whole process group is killed.
--dangerously-skip-permissions is safe there only because of the confinement listed above. On a normal host it lets Claude run any shell command and edit any file without asking. Use the safe defaults instead.

2. Choose how you exchange messages

PatternUse whenProcessesConversation state
A. One-shotA single question with a single answer. The board uses this.One per questionNone needed
B. Resume by session IDMulti-turn, where turns are minutes or hours apart, or come from different programs.One per turnSaved on disk by Claude Code and resumed with --resume <session_id>
C. Live stream-jsonA real back-and-forth conversation with low overhead per turn.One long-lived processHeld in the running process

3. Pattern A — one-shot JSON

claude -p "Summarize README.md in three bullets" --output-format json --tools "Read"

Prompt sources:

Field in the result envelopeMeaning
type, subtype, is_errorThe success test: "result", "success" and false.
resultThe final answer text.
session_idPass this to --resume to continue the conversation.
structured_outputPresent only with --json-schema '<schema>' and only when the output validated. Check that it exists before using it.
num_turns, duration_ms, usage, modelUsage, total_cost_usdMetrics. modelUsage keys are the model IDs that actually ran. The cost figure is a client-side estimate.
permission_denialsTool calls that were refused. A non-empty list explains a partial answer.

When something fails inside the run, such as missing authentication, the failure is still printed as the result on stdout. Parse stdout even when the exit code is non-zero, and never parse stderr as JSON.

4. Pattern B — continue a conversation across runs

sid=$(claude -p "Remember the number 42. Reply only: OK" --output-format json --tools "" | jq -r .session_id)
claude -p "What number did I give you? Reply with the number only." --resume "$sid" --output-format json --tools "" | jq -r .result
# prints: 42

5. Pattern C — live conversation over stdin/stdout (stream-json)

Start one process and keep it running:

claude -p --input-format stream-json --output-format stream-json --verbose --tools "" --permission-prompts none

To send, write one JSON object per line to stdin and flush:

{"type":"user","message":{"role":"user","content":"Your message here"}}

To receive, read newline-delimited JSON events from stdout until a "type":"result" event arrives. That event completes the turn and carries the same fields as the Pattern A envelope. Each message you send produces exactly one result. Event types seen per turn include:

Key only on result and ignore event types you don't use. New types appear between versions.

Closing stdin ends the session, and the process exits with code 0. The script below was run as published:

#!/usr/bin/env python3
"""Hold a multi-turn conversation with one headless Claude Code process over stdin/stdout."""
import json
import subprocess
import sys

CMD = ["claude", "-p",
       "--input-format", "stream-json", "--output-format", "stream-json", "--verbose",
       "--model", "haiku",              # any alias or full model name
       "--tools", "",                   # no tools: pure conversation
       "--permission-prompts", "none",  # never wait for a human
       "--safe-mode"]                   # skip CLAUDE.md, hooks, plugins, MCP; login still works


def send(proc, text):
    line = {"type": "user", "message": {"role": "user", "content": text}}
    proc.stdin.write(json.dumps(line) + "\n")
    proc.stdin.flush()


def receive(proc):
    """Read events until this turn's result; ignore event types you don't use."""
    for raw in proc.stdout:
        event = json.loads(raw)
        if event.get("type") == "result":
            ok = event.get("subtype") == "success" and event.get("is_error") is False
            return ok, event.get("result"), event.get("session_id")
    raise RuntimeError("claude exited before sending a result")


proc = subprocess.Popen(CMD, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1)
try:
    for question in ["Remember the word PLUM. Reply only: OK",
                     "What word did I ask you to remember? Reply with the word only."]:
        send(proc, question)
        ok, answer, session = receive(proc)   # stdin is still open here
        print(f"ok={ok} answer={answer!r}")
        if not ok: sys.exit(1)
finally:
    proc.stdin.close()                         # EOF ends the session
    print("exit code", proc.wait(timeout=60))

Expected output:

ok=True answer='OK'
ok=True answer='PLUM'
exit code 0
For token-by-token text, add --include-partial-messages and read stream_event events whose event.delta.type is text_delta. To get typed message objects and callbacks in Python or TypeScript code rather than a subprocess, use the Claude Agent SDK, which runs the same agent loop.

6. Authentication for unattended runs

CredentialHowNotes
Saved subscription loginRun claude auth login once as the same user. On Linux it is stored in ~/.claude/.credentials.json (mode 0600).The board uses this: one login per seat, copied into each request's fresh HOME. Default for Pro, Max, Ultra, Team and Enterprise.
Long-lived subscription tokenclaude setup-token prints a one-year token and does not save it. Export it as CLAUDE_CODE_OAUTH_TOKEN.For CI or hosts without a browser. The token can only make model requests.
API key (per-token billing)ANTHROPIC_API_KEYIn -p mode the key is always used when present, ahead of the subscription login. Unset it if you meant to use the subscription.

7. Safe defaults for an AI caller

NeedFlags
Pure Q&A, no tools--tools ""
Read-only analysis--tools "Read,Grep,Glob"
Specific commands only--allowedTools "Bash(git diff *),Read" --permission-mode dontAsk (anything not allowed is denied)
Nobody to answer prompts--permission-prompts none (denies instead of waiting, and tells Claude not to retry)
Isolation from host configuration--safe-mode (subscription) or --bare (API key)
Spend cap--max-budget-usd <amount>
Replace or extend the system prompt--system-prompt "..." or --append-system-prompt "..."
Machine-checkable output--output-format json --json-schema '<JSON Schema>', then read .structured_output

8. Robustness checklist

9. Don't want to run your own? Use the Review Board

10. Sources

ClaimSource
-p usage, output formats, --resume, --bare, trust behaviour, Manual mode from 2.1.302, --permission-prompts, SIGTERM exit 143, 10 MB stdin capcode.claude.com/docs/en/headless
claude setup-token, CLAUDE_CODE_OAUTH_TOKEN, credential precedence, API key always used in -p, --bare ignores OAuthcode.claude.com/docs/en/authentication
Flag names and choices (--tools, --safe-mode, --input-format, --permission-mode, …)claude --help, Claude Code 2.1.322
Board argv, success test, per-request HOME, credential copy-back, environment whitelist, Landlockclaude/adapter.py, shared/review_session.py (administrators/reviewboard)
stream-json input line shape, one result per message, turn-by-turn with stdin open, --resume recall, --safe-mode with a subscription loginLive runs, 2026-11-10, Claude Code 2.1.322

Index: /reviewboard/ · Portal: nginx.ai-servicers.com