Atlas
TechnicalHow-to

Claude Code -p: JSON Output, Schemas and Cost in Scripts

Script Claude Code with claude -p: get schema-checked JSON, read each run's cost, resume a session and fail a pipeline when output is missing.

1Run claude-p with--output-formatjson2Add--json-schemafor a fixedshape3Checkstructured_out…is present4Logtotal_cost_usdas anestimate

The short version

  • Running claude -p with --output-format json and --json-schema returns machine-readable output in a structured_output field that a script can parse.
  • If a run ends without valid structured output, that field is simply absent, so a script must check for it before using it.
  • Every JSON result carries total_cost_usd, but it is a client-side estimate and not your bill.
  • In scripts and CI, --bare skips auto-discovery of hooks, plugins, MCP servers and CLAUDE.md so runs don't depend on the host, but it ignores your subscription login and needs an API key or a cloud provider's credentials.
  • Resuming a session reports the whole session's cost, so read the latest result instead of adding runs together.
On this page
  1. The short version
  2. What does claude -p do?
  3. How do I get JSON output from Claude Code?
  4. How do I force a schema with --json-schema?
  5. A small script that checks its own output
  6. How do I keep scripted runs from depending on the machine?
  7. How do I read the cost of a run?
  8. Continuing a conversation without double-counting
  9. Keep unattended runs from hanging on a prompt
  10. Fail the pipeline when a plugin or MCP server did not load
  11. SIGTERM, timeouts and background work
  12. How Atlas relates
  13. Conclusion
  14. Questions people ask

If you want to call Claude Code from a script and get something a program can read, run it with claude -p, ask for --output-format json, and add --json-schema when you need a fixed shape. The result arrives as JSON with the session ID, a cost estimate and, when you gave a schema, a structured_output field. This guide shows the pattern, the checks that keep a pipeline from failing silently, and how to track cost.

The focus is the output: how to parse it, how far to trust it and how to count what it cost. Everything below comes from Anthropic's documentation unless it says otherwise.

What does claude -p do?

-p (or --print) runs Claude Code non-interactively: it takes a prompt, does the work and exits. Anthropic's page on running Claude Code programmatically says it exits with code 0 on success and a non-zero code when the run fails, so a script can branch on the exit status. An invalid flag is reported on stderr before the run starts. A failure inside the run, such as missing authentication, is printed as the result on stdout.

The simplest uses are one-liners:

bash
claude -p "What does the auth module do?"

cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt

Piped input is capped at 10MB. Past that, Claude Code exits with an error and a non-zero status. For anything larger, write it to a file and put the path in the prompt.

How do I get JSON output from Claude Code?

--output-format takes three values: text (the default), json and stream-json. With json, the response carries the text in result plus the session ID and metadata:

bash
claude -p "Summarize this project" --output-format json | jq -r '.result'

stream-json gives newline-delimited JSON for real-time streaming. Use it with --verbose and --include-partial-messages if you want tokens as they arrive. The last line of the stream is a result message with the final text, cost and session metadata.

How do I force a schema with --json-schema?

Pass a JSON Schema alongside --output-format json. The structured value comes back in the structured_output field:

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"]}' \
  | jq '.structured_output'

Three details from the docs matter for scripts:

  • If the schema is not valid JSON Schema, claude exits with Error: --json-schema is not a valid JSON Schema and the validator's diagnostic.
  • The format keyword (for example "format": "email") is accepted but treated as an annotation, not enforced. Validate such fields yourself.
  • If a run ends without valid structured output, for example because Claude declined the request, the response has no structured_output field. Check that it is present before using it.

That last point is the one that bites. A successful exit and a missing field can coexist, so test for the field rather than assuming it.

A small script that checks its own output

This is a sketch of the pattern, not an official recipe. It runs once, keeps the whole JSON, refuses to continue if the structured field is missing, and prints the cost:

bash
#!/usr/bin/env bash
set -euo pipefail

SCHEMA='{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'

out=$(claude -p "Extract the main function names from auth.py" \
  --output-format json \
  --json-schema "$SCHEMA")

# jq -e exits non-zero when the field is null or absent
echo "$out" | jq -e '.structured_output' > functions.json \
  || { echo "no structured_output in the run" >&2; exit 1; }

echo "session: $(echo "$out" | jq -r '.session_id')"
echo "cost estimate: $(echo "$out" | jq -r '.total_cost_usd')"

Because the script captures the response in a variable, one call gives you the data, the session ID and the cost. Do not call the model twice just to get the cost.

How do I keep scripted runs from depending on the machine?

Add --bare. It skips auto-discovery of hooks, skills, custom commands, subagents, installed plugins, MCP servers, auto memory and CLAUDE.md. Without it, claude -p loads them as an interactive session would, including anything configured in the working directory or ~/.claude. So a hook in a teammate's ~/.claude, or an MCP server in the project's .mcp.json, does not run in bare mode, because bare mode never reads them.

bash
claude --bare -p "Summarize README.md" --allowedTools "Read"

Two consequences to plan for:

  1. Bare mode does not use your subscription login. It never reads OAuth credentials or the system keychain, so you need ANTHROPIC_API_KEY (created in the Claude Console), or an apiKeyHelper in the --settings JSON. Amazon Bedrock, Google Cloud's Agent Platform and Microsoft Foundry still read their own provider credentials.
  2. You pass context explicitly. Use --append-system-prompt or --append-system-prompt-file, --settings, --mcp-config, --agents and --plugin-dir as needed. Hooks passed through --settings still do not run in bare mode, so do not use it for a run that needs them.

Bare mode also limits the session itself: Claude has the Bash, file read and file edit tools, it cannot run background commands or background subagents, and a command that reaches its timeout stops instead of moving to the background.

The docs call --bare the recommended mode for scripted and SDK calls and say it will become the default for -p in a future release.

Without --bare, a -p session runs the hooks in a project's .claude/settings.json and connects the servers in .mcp.json, even in a folder you have never trusted, with no trust dialog and no per-server approval prompt. If your script checks out code you do not control, read the docs' section on what runs before you trust a folder first.

How do I read the cost of a run?

With --output-format json, the response includes total_cost_usd and a per-model cost breakdown. The Agent SDK's cost tracking page adds the caveats worth repeating to your team:

  • total_cost_usd is a client-side estimate computed from a price table bundled at build time. It can drift from your actual bill if pricing changes, the installed version does not recognise a model, or billing rules apply that the client cannot model. Anthropic says not to bill end users or make financial decisions from it. Use it for development insight and approximate budgeting.
  • Subagent spend is included in total_cost_usd and in the per-model breakdown (modelUsage), but not in usage, which counts only the top-level loop. For whole-tree accounting, use the first two.
  • Success and error results both carry the cost, so log it for failed runs too. On an error_max_budget_usd result, usage leaves out the response that crossed the budget while total_cost_usd includes it, so prefer total_cost_usd.
  • Output tokens on individual assistant messages are a placeholder; read them from the result.

The headless page also names a --max-budget-usd cap. When a run reaches it, Claude Code stops remaining background work rather than waiting. Set it in unattended jobs so a loop cannot run up spend, and treat it as a guard rail, not an invoice.

Continuing a conversation without double-counting

--continue picks up the most recent conversation; --resume takes a session ID. Capture the ID from the JSON:

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

The two commands can run from different directories, because Claude Code finds the session by ID in any project on the machine. On cost, a resumed run reports the conversation's whole total, earlier runs included. So for a chain of resumed calls, read the latest result for the session total. Adding the runs together double-counts. Independent calls, with no --continue or --resume, each report only themselves, and you add them yourself. The docs note that before v2.1.277 a resumed session started its totals at zero, so check your version if numbers look low.

Keep unattended runs from hanging on a prompt

A scripted run that needs a permission nobody can grant should be denied, not left waiting. The docs give a few ways to do this:

bash
# Baseline mode: deny everything that would otherwise prompt
claude -p "Apply the lint fixes" --permission-mode dontAsk --allowedTools "Read,Edit"

# Auto mode, and deny anything that would fall back to a prompt
claude -p "Update the dependency pins and run the tests" \
  --permission-mode auto --permission-prompts none

--permission-prompts none needs Claude Code v2.1.259 or later and lasts for one run. To make it permanent, set permissions.denyInsteadOfPrompting to true in user or managed settings. With stream-json, denials appear as permission_denied system messages, and the final result lists them in permission_denials. Since v2.1.302, claude -p runs start in Manual mode when nothing sets a permission mode, so a call that needs approval is denied unless a hook or a permission prompt tool approves it.

Scope --allowedTools narrowly. The docs' commit example allows only Bash(git diff *), Bash(git log *), Bash(git status *) and Bash(git commit *). The space before the * matters: without it, Bash(git diff*) would also match git diff-index.

Fail the pipeline when a plugin or MCP server did not load

Claude Code skips invalid --mcp-config entries and the run still exits cleanly. If your job depends on an MCP server or plugin, read the system/init event in stream-json output:

  • plugin_errors lists plugin load failures and is omitted when there are none. A plugin that failed to load is also absent from plugins.
  • mcp_server_errors lists skipped --mcp-config entries and is omitted when empty, so a CI gate can fail on a non-empty array.
  • When stderr is redirected or captured by a CI runner, Claude Code prints no startup warning about skipped MCP entries, so mcp_server_errors is the only report.

A missing tool otherwise shows up later as a vaguely wrong answer.

SIGTERM, timeouts and background work

If a supervisor stops a run with SIGTERM, Claude Code exits with code 143 and records no result for the unfinished turn. Send SIGINT first if you want the turn to end cleanly. After the turn finishes, a -p run can stay open for background commands and subagents, and by default drops background work after 10 minutes of idle waiting; CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS changes that cap. If a subagent's long command moves to the background at its timeout, the run can exit 0 before the command finishes. Raise BASH_DEFAULT_TIMEOUT_MS above the command's run time, for example BASH_DEFAULT_TIMEOUT_MS=300000 for five minutes.

How Atlas relates

Atlas runs its engineers as Claude Code sessions on the user's own Claude plan, shows each task's cost counted once, shows Claude usage on its Home screen, and offers an optional daily budget that warns at 50% and 80% and pauses at 100%. Checking that an engineer's tools loaded at startup is coming to Atlas, built in, so it needs no setup on your side. Until then, the system/init check in your own scripts is the route. You can read more on the Atlas home page.

Conclusion

Treat claude -p like any other program in your pipeline. Ask for JSON, give it a schema, check that structured_output exists, log total_cost_usd while remembering it is an estimate, and use --bare when the result must not depend on whose machine it runs on. Pair that with a narrow --allowedTools list and a deny-instead-of-prompt setting, and an unattended run either finishes with data you can use or fails in a way you can see.

Questions people ask

How do I get JSON output from claude -p?

Run claude -p with --output-format json. The response includes the text in a result field, the session ID and metadata. Add --json-schema to get a structured_output field that follows your schema.

Why is structured_output missing from the result?

If a run ends without valid structured output, for example because Claude declined the request, the response has no structured_output field. Check that the field is present before your script uses it.

Is total_cost_usd what I will be billed?

No. Anthropic describes total_cost_usd as a client-side estimate from a bundled price table, which can drift from your actual bill. Use it for development insight and approximate budgeting, not for billing.

Does --bare use my Claude subscription?

No. Bare mode never reads OAuth credentials or the system keychain, so it needs an ANTHROPIC_API_KEY, an apiKeyHelper, or a cloud provider's own credentials.

How do I continue a session from a script?

Capture session_id from the JSON output and pass it to --resume, or use --continue for the most recent conversation. A resumed run reports the whole session's cost, so read the latest result rather than summing runs.

Sources

  1. Run Claude Code programmatically (Anthropic docs)
  2. Track cost and usage (Claude Agent SDK docs)

Researched and drafted with Claude, then checked against the sources above. Atlas is an independent product, not affiliated with Anthropic or OpenAI. Claude and Claude Code are trademarks of Anthropic; Codex is a product of OpenAI.