Learning resourcesReviewed · Anthropic

Run Claude Code programmatically

This guide teaches developers to automate Claude Code in scripts and CI, but default startup can load project hooks and servers without a trust prompt. It explains non-interactive commands, bare mode, tool permissions, structured output, streaming and session continuation, with specific warnings about incomplete results and background work.

Researched 15 Nov 2026

In short.

This guide explains Claude Code automation for developers building scripts and continuous integration jobs, with the catch that unattended execution requires deliberate configuration and permission handling. It documents claude -p, recommends --bare for scripted calls, and explains JSON output, streaming events, session reuse and process shutdown. Its most useful details concern failures that ordinary exit-code checks can miss. Installation instructions, actual billing rates, licensing terms and measured reliability are not established by this page. No commands or SDK calls were executed.

Researched and written by an AI model and checked by a second AI model. How it works

Coverage comprises the complete documentation page at [https://code.claude.com/docs/en/headless.md], including its examples, bare-mode exceptions, permission notices, output formats, background-task behavior, shutdown handling and version qualifications. Linked pages, SDK packages and external services are excluded. No commands or SDK calls were executed; described behavior is supported by documentation, while actual performance, compatibility, task outcomes and costs remain unverified.

The overview

Identity

Run Claude Code programmatically is a Claude Code documentation guide at [https://code.claude.com/docs/en/headless.md]. Its main subject is the command-line interface to the Agent SDK, invoked with claude -p or --print to run without an interactive terminal conversation.

The page describes the Agent SDK as providing Claude Code's tools, agent loop and context management. Python and TypeScript packages are introduced as other interfaces, but their documentation is on separate pages.

Assessment

This is a useful integration reference for turning Claude Code tasks into shell commands and automated jobs. It goes beyond prompt examples to explain authentication, tool approvals, output parsing, startup configuration and process lifecycle.

Its strongest practical contribution is explaining why a successful process exit does not necessarily prove that every requested operation completed. Missing structured output, skipped MCP server configurations and unfinished subagent commands require additional checks. The page supplies documented behavior rather than measured success rates or independent performance results.

Users

The guide fits developers who want code explanations, build-log analysis, diff review or code changes inside scripts and continuous integration pipelines. Beginners need familiarity with terminal commands, files, environment variables and permissions. Experienced developers get details for JSON consumers, streaming event handlers, session management and unattended permission handling.

Developers needing native Python or TypeScript message objects and tool-approval callbacks receive pointers to the SDK packages, rather than implementation instructions for those packages on this page.

Capabilities

Documented patterns include answering questions about a codebase, explaining piped build logs, reviewing diffs, editing files, running tests and creating commits when permissions allow. Commands can read standard input and redirect their response into a file. --continue reuses the most recent conversation, while --resume targets a session ID or an absolute transcript-file path.

Output choices are text, JSON and newline-delimited streaming JSON. JSON can carry a schema-constrained response, session metadata and cost estimates. Streaming can expose partial text, retry events, subagent messages, loaded plugins, MCP server status and permission denials.

Using it

Requirements

The examples assume an installed claude command, access to the relevant project files and valid provider credentials. Installation steps, supported operating systems and hardware requirements are not supplied. In bare mode, Anthropic API access requires ANTHROPIC_API_KEY or an apiKeyHelper supplied through settings; subscription OAuth credentials and the system keychain are not read. Other named providers retain their own credential handling.

Features have different version requirements. --permission-prompts none requires v2.1.259 or later. The documented default to Manual permission mode, when nothing sets a mode, applies from v2.1.302. The page does not establish one minimum version covering every example and behavior.

Mechanism

The -p flag runs a prompt non-interactively through Claude Code's agent loop. The process exits with code 0 on success and a non-zero code on failure. Invalid flags are reported on standard error before execution; failures inside a run, including missing authentication, are reported as the result on standard output.

With --output-format json, ordinary response text appears in result. Combining it with --json-schema places a successful schema-constrained response in structured_output, which can be absent and must be checked. JSON Schema format values such as email are annotations rather than enforced validation. Token streaming uses --output-format stream-json with --verbose and --include-partial-messages.

SIGTERM produces exit code 143 and leaves the active turn unfinished without recording a result for it. The page recommends SIGINT or the SDK interrupt() method to end the turn before stopping the process.

Setup

The page recommends --bare for scripts and SDK calls. Bare mode skips automatic discovery of hooks, skills, plugins, MCP servers, auto memory and CLAUDE.md. Required settings, prompt additions, servers, agents or plugins can be supplied explicitly through flags. Hooks remain disabled even when included in supplied settings or plugins.

Without --bare, a -p run can execute project hooks and connect project MCP servers even in a folder that has never been trusted, without workspace or per-server approval dialogs. Inspecting the project configuration before allowing that startup behavior is therefore a practical prerequisite.

--allowedTools pre-approves matching calls; it does not define the complete set of tools that can run. Unlisted calls needing no approval can still proceed. For unattended jobs, --permission-prompts none prevents waiting for a permission host, while existing rules, permission modes and applicable hooks still determine approvals.

Example

The page's small bare-mode example is: claude --bare -p "Summarize README.md" --allowedTools "Read". It asks for a file summary and pre-approves the Read tool. For Anthropic API access, the environment must already contain appropriate credentials because bare mode does not use the subscription login.

A structured-output example uses claude -p "Summarize this project" --output-format json. A consuming script would read result for the response and session_id for later continuation. These are documentation examples; no execution or resulting summary was observed.

Assessment & evidence

Limitations

Piped input is capped at 10 MB; the documented alternative for larger material is to reference a file. Not every CLI flag combines with -p. Bare mode removes background commands and background subagents, omits system reminders such as file-change notices, and disables hooks. It still exposes shell and file tools, so it is not a read-only boundary. An --add-dir directory is a discovery exception: its skills can load, although the available-skills reminder is omitted.

Outside bare mode, background work can keep a run open. The default 10-minute idle waiting ceiling has exceptions, including commands started by the main conversation and pending loop wakeups. A subagent's long command can remain unfinished when the CLI exits with code 0. The run does not wait for background MCP work: remote tasks may continue, while results from automatically backgrounded MCP calls are lost.

MCP configuration validation can skip a server while the overall run continues and exits cleanly. When standard error is redirected or captured, the warning is omitted there, making the structured mcp_server_errors field important. The page supplies no measured accuracy, latency or reliability guarantees.

Reasoning

The documented combination of explicit startup configuration, tool permissions and machine-readable output makes this guide relevant to automation that needs observable outcomes. Bare mode reduces dependence on incidental machine configuration, but does not establish deterministic model answers or enforce read-only access.

A practical implication of the documented failure cases is that integration success needs several checks together: process status, expected response fields, permission denials, startup errors and completion of required work. Exit code 0 alone is insufficient for workflows involving skipped integrations or background operations.

Alternatives

The page identifies Python and TypeScript Agent SDK packages as alternatives to shell integration when an application needs native message objects, structured outputs and tool-approval callbacks. The CLI examples are more directly applicable to pipes, shell scripts and build commands. The linked package documentation is outside this page, so package setup, compatibility and comparative cost or performance are not assessed.

Evidence

The evidence is the complete documentation page at [https://code.claude.com/docs/en/headless.md]. It supports descriptions of commands, flags, output fields, version thresholds and documented failure behavior. Its examples are illustrative instructions rather than observed execution results.

Linked SDK guides, CLI references, permission documentation, provider pages and pricing material were not assessed. No commands or SDK calls were executed, so practical compatibility, task quality, actual spending and operational reliability remain unverified.

Access & freshness

Costs

The page provides no model rates, subscription prices, typical task costs or measured spending. Actual cost is unknown. JSON output includes total_cost_usd and a per-model breakdown, but these are client-side estimates that can differ from the bill. Continued or resumed conversations report cumulative conversation spending, including earlier runs.

A --max-budget-usd cap is mentioned: reaching it stops remaining background work rather than waiting. The page does not establish the cap's billing precision or suitability as an account-wide spending limit. Bare mode's exclusion of subscription login should be considered when choosing authentication and budgeting.

Rights

The page does not state documentation or software licensing terms, redistribution permissions, output ownership, commercial-use conditions or data-retention commitments. Those matters remain unknown from this source. Public access to the guide does not establish permission to redistribute its captured text or the software it describes.

Freshness

The supplied page was captured on 2026-11-15 at 03:35:35.235 UTC. A publication date, last-update date and latest available Claude Code version are not established. The page says bare mode is recommended and will become the default for -p in a future release; that statement does not establish that it is already the default.

Version-dependent changes include fuller bare-mode restrictions from v2.1.286, text output for each background-triggered turn from v2.1.295, and the documented Manual-mode default from v2.1.302. Installed-version compatibility needs separate confirmation.

Actions

Before adopting these patterns, check the installed CLI version and credentials, then begin with a small file-reading task using --bare and explicitly chosen permissions. Decide whether the job needs hooks, background work or subscription authentication, since bare mode changes those capabilities. Use --permission-prompts none where nobody can answer requests.

For an automated integration, parse standard output and standard error separately, check required JSON fields, and inspect permission denials plus plugin and MCP startup errors. Define completion and timeout rules for any background work, and track cumulative cost estimates without treating them as final billing. Confirm pricing, licensing and data-handling terms separately because this page does not establish them.

Evidence for this report

selected-page.txtselected · checked 2026-11-15