skip to content

Unattended Automation

Running Claude Code with nobody at the keyboard: headless -p runs, CI jobs and PR review, scheduled prompts and routines, and the Agent SDK. Asked because unattended agents need set permissions.

part ofClaude Coderead it →
on this pageshow

explore

questions

23

What is the Claude Agent SDK, and when would you embed it in an application instead of scripting `claude -p`?

level: juniorimportance: must knowfreq 15%

answer

  1. same loop, packaged as a library
  2. two packages, one per language
  3. renamed from the Claude Code SDK
  4. bundles a native Claude Code binary
  5. callbacks need a host process

basics

~20 s

The Claude Agent SDK runs Claude Code's agent loop, built-in tools, permissions, hooks and sessions as a Python or TypeScript library. Embed it when your service needs approval callbacks, in-process custom tools or typed messages; script claude -p for shell jobs.

solid answer

~50 s

The Agent SDK (`@anthropic-ai/claude-agent-sdk` for TypeScript, `claude-agent-sdk` for Python, renamed from the Claude Code SDK) gives your own code the same tools, agent loop and context management that power Claude Code. It does not reimplement that loop: both packages normally bundle a native Claude Code binary and drive it, so you get `Read`, `Edit`, `Bash` and the other built-in tools, permission rules, hooks, sessions and the `.claude/` configuration. You call `query()` and iterate typed messages until a result message arrives. Choose it over `claude -p` when the agent lives inside a service you operate and you need what a flag cannot express: a `canUseTool` approval callback, hook callbacks in your own process, custom tools built with `tool()` and `createSdkMcpServer`, or sessions you resume and fork from code. From any other language, the docs point you to `claude -p` with JSON output instead.

go deeper

for a junior

Recall the two package names, that the SDK was renamed from the Claude Code SDK, and that query() streams typed messages ending in a result message.

for a middle

Explain that the SDK drives a bundled Claude Code binary, so built-in tools, permissions, hooks and .claude/ configuration come with it, and contrast query() with Python's ClaudeSDKClient.

for a senior

Justify the library-or-CLI choice by where decisions must live: runtime approvals, in-process tools and hook logic argue for the SDK; a fixed allowlist in a shell job argues for claude -p.

for a principal

Weigh operating a library inside your own service, with its binary, credentials and upgrades tied to your release cycle, against running a CLI job the platform team can version and sandbox separately.

## What the Agent SDK is The **Claude Agent SDK** is Claude Code packaged as a library. An *agent* here means a program that completes a task by planning its own steps and calling tools that read files, run commands or edit code. The SDK gives Python and TypeScript applications the same **built-in tools**, the same **agent loop** (model call, tool call, tool result, next model call) and the same context management that the Claude Code terminal uses. It is not a second implementation. Both SDKs bundle a native Claude Code binary for the platform and run it on your behalf, which is why everything that works in Claude Code is available: permission rules and modes, hooks, subagents, MCP servers, sessions, skills and `CLAUDE.md`. If the bundled binary is missing (the TypeScript optional dependency was skipped, or pip installed a Python source distribution with no platform wheel), you point the SDK at a separately installed `claude` binary. ## The packages and the rename | Language | Package today | Former name | |---|---|---| | TypeScript / JavaScript | `@anthropic-ai/claude-agent-sdk` | `@anthropic-ai/claude-code` | | Python | `claude-agent-sdk` (import `claude_agent_sdk`) | `claude-code-sdk` (import `claude_code_sdk`) | The product was renamed from the **Claude Code SDK** to reflect that it builds agents beyond coding. The rename came with breaking changes, so a migration is more than an import edit; the migration guide lists them. ## What a call looks like The entry point is **`query()`**. You pass a prompt and an options object (`ClaudeAgentOptions` in Python, a plain `options` object in TypeScript) and iterate the result as an async stream of typed messages: assistant text, tool calls, tool results, system messages and finally a **result message** carrying the outcome, cost and `session_id`. - **TypeScript:** `for await (const message of query({ prompt, options }))`. - **Python:** `async for message in query(prompt=..., options=...)`. - **Python `ClaudeSDKClient`:** a client object that keeps one session across several `client.query()` calls and supports interrupts; the TypeScript SDK has no such object and uses `continue: true` or `resume` on later `query()` calls instead. Authentication is an API key in `ANTHROPIC_API_KEY` (or a cloud-provider configuration). The SDK does not read `.env` files on its own, and third-party products built on it may not offer claude.ai login unless Anthropic has approved it. ## Library or CLI: how to choose | You need | Reach for | |---|---| | A nightly shell job, a Makefile step, any language other than Python or TypeScript | `claude -p` with `--output-format json` | | An approval decision made by your code or your users at runtime | SDK `canUseTool` callback | | Policy code that inspects or rewrites every tool call in-process | SDK hook callbacks | | Your own functions exposed as tools without running a separate server | SDK `tool()` plus `createSdkMcpServer` | | Multi-turn conversations, resume and fork driven by application state | SDK sessions | The deciding question is **where the decisions live**. `claude -p` takes everything up front as flags and settings files, then runs to completion; nothing in your program can answer a permission prompt or inject logic mid-run except through hooks configured on disk. The SDK keeps your process in the loop, so permission decisions, hook logic and custom tools are ordinary functions in your codebase, with types, tests and access to your application's state. ## A worked choice Suppose a team builds an internal **pull-request summary service**: a web handler receives a PR number, checks out the branch, asks the agent to read the diff and write release-note bullets, and stores the result. 1. The service is already written in TypeScript, so the SDK fits the runtime. 2. It needs a custom `get_pr_diff` tool backed by the internal git host, which `tool()` and `createSdkMcpServer` provide in-process. 3. It must refuse any write or `git push`, which is a permission and hook concern the SDK lets the service decide in code. 4. It records `session_id` from the result message so a reviewer can ask a follow-up later with `resume`. The same job as a cron script with no custom tools and a fixed tool allowlist would be simpler as `claude -p`. ## Misunderstandings to avoid - The SDK is not a thin wrapper over the Messages API; it ships the built-in tools and the permission system. - Choosing the SDK does not lose `CLAUDE.md`, skills or project hooks: by default `query()` loads the same filesystem settings as the CLI. - Python is a first-class SDK, not a shell-out wrapper around TypeScript. - The raw tool loop on the Messages API, where you execute `tool_use` blocks yourself, is a different and lower-level route that you would only take if you wanted none of Claude Code's harness.

  • Does a host running the Claude Agent SDK need Claude Code installed separately?
    Usually not. Both SDKs bundle a native Claude Code binary: TypeScript as a platform optional dependency such as `@anthropic-ai/claude-agent-sdk-darwin-arm64`, Python inside platform wheels. If the package manager skipped optional dependencies, TypeScript throws `Native CLI binary for <platform>-<arch> not found` and you set `pathToClaudeCodeExecutable`. A Python source install without a wheel finds a natively installed `claude` on `PATH`.
  • In the Python SDK, when do you use ClaudeSDKClient rather than query()?
    `query()` starts a new session per call by default and suits one-off tasks; it does not support interrupts, and continuing needs `continue_conversation` or `resume`. `ClaudeSDKClient` keeps one session across several `client.query()` calls, supports interrupts and suits chat-style applications where the next prompt depends on the last answer. TypeScript has no client object; it uses `continue: true` or `resume`.
  • Can a product built on the Agent SDK let its users sign in with their claude.ai subscription?
    Not by default. The overview states that, unless previously approved, Anthropic does not allow third-party developers to offer claude.ai login or rate limits in their products, including agents built on the SDK. Such products authenticate with an API key, `ANTHROPIC_API_KEY`, or a cloud-provider configuration.

  • The Agent SDK is a thin Messages API wrapper with no built-in tools.
  • New projects should still install claude-code-sdk; the new name is cosmetic.
  • Only TypeScript has an Agent SDK, so Python services must shell out to claude -p.
  • Embedding the SDK means losing CLAUDE.md, skills and project hooks.
  • Any product built on the SDK may offer claude.ai login to its users.
open as a page

What does `claude -p` do, and how does a shell script feed it input and tell whether the run succeeded?

level: juniorimportance: must knowfreq 30%

basics

~10 s

claude -p (alias --print) runs Claude Code non-interactively: it takes the prompt plus any piped stdin, runs the agent loop, prints the result to stdout, and exits 0 on success or non-zero on failure.

open as a page

How does anthropics/claude-code-action@v1 choose between @claude interactive mode and automation mode, and what changes between the two?

level: middleimportance: must knowfreq 26%

basics

~20 s

The action's prompt input decides: without it, Claude waits for the trigger phrase, @claude by default, and replies in a comment; with it, Claude runs on the workflow's event and reports in the workflow run log by default.

open as a page

In a Claude Agent SDK service, why does the canUseTool callback never see some tool calls, and where must a check that sees every call live?

level: seniorimportance: must knowfreq 10%

basics

~20 s

canUseTool is the last step of the SDK's permission flow, so calls already approved by a hook, a mode such as acceptEdits or bypassPermissions, or an allow rule never reach it. A check for every call belongs in a PreToolUse hook callback.

open as a page

A nightly `claude -p` lint-triage job must neither stall on a permission prompt nor run commands nobody approved; how do you set its permissions?

level: seniorimportance: must knowfreq 20%

basics

~20 s

Pass the mode explicitly, usually --permission-mode dontAsk with narrowly scoped --allowedTools rules, so anything unlisted is denied rather than prompted; add --permission-prompts none (2.1.259+) when a permission host could otherwise wait, and never a bare Bash allow.

open as a page

In Claude Code, how do /loop, Desktop scheduled tasks and cloud routines differ, and which one survives a closed laptop?

level: seniorimportance: must knowfreq 20%

basics

~20 s

/loop fires only inside an open CLI session; a Desktop scheduled task starts local sessions while the app runs and the computer is awake; a routine runs in the cloud, so only a routine survives a closed laptop.

open as a page

What does the Claude Code GitHub Action do, and what does /install-github-app set up in a repository?

level: juniorimportance: should knowfreq 30%

basics

~20 s

anthropics/claude-code-action@v1 runs Claude Code inside a repository's GitHub Actions workflows, answering @claude mentions or running a set prompt. /install-github-app installs the Claude GitHub App, saves an auth secret and opens a pull request adding the workflow.

open as a page

In Claude Code, what do `/loop 5m check the deploy`, `/loop check the deploy` and a bare `/loop` each do?

level: juniorimportance: should knowfreq 16%

basics

~20 s

/loop 5m check the deploy runs on a fixed cron schedule; /loop check the deploy lets Claude choose a one-minute-to-one-hour delay after each run; a bare /loop self-paces through loop.md or the built-in maintenance prompt.

open as a page

How do you give a Claude Agent SDK agent an in-process custom tool with tool() and createSdkMcpServer, and which name do you pre-approve?

level: middleimportance: should knowfreq 8%

basics

~10 s

Define the tool with tool() (Python @tool) as name, description, schema and async handler, wrap it with createSdkMcpServer, pass it under a key in mcpServers, and pre-approve mcp__<key>__<tool> in allowedTools.

open as a page

How do `--max-turns` and `--max-budget-usd` cap a `claude -p` run, and what does each count or leave out?

level: middleimportance: should knowfreq 12%

basics

~20 s

--max-turns limits agentic turns and exits with an error when reached; --max-budget-usd stops the run once estimated spend, subagents included, hits the cap. Both are print-mode only; neither has a default, and resumed spend is not counted.

open as a page

In `claude -p`, when do you choose `--output-format json`, `stream-json` or `--json-schema`, and what does a script read from each?

level: middleimportance: should knowfreq 15%

basics

~10 s

Use json for one final object a script parses (result, session_id, total_cost_usd), stream-json for newline-delimited events while the run progresses, and --json-schema with json output when you need validated data in structured_output.

open as a page

In the Claude Agent SDK, how does a PreToolUse hook callback block or rewrite a tool call, and what silently stops it working?

level: seniorimportance: should knowfreq 6%

basics

~20 s

Register the callback under options.hooks.PreToolUse with a matcher on the tool name. Return hookSpecificOutput with permissionDecision deny and a reason to block, or updatedInput to rewrite; return an empty object to let the call proceed.

open as a page

Claude Code Review left an Important finding on a pull request, yet the PR merged under branch protection. Why, and how would you gate merges on its findings?

level: seniorimportance: should knowfreq 9%

basics

~20 s

Code Review never approves or blocks a pull request: its Claude Code Review check run always ends neutral, so branch protection cannot fail on it. To gate merges, your own CI parses the check run's severity counts and fails on Important.

open as a page

Who can trigger a run of anthropics/claude-code-action@v1, and how do you widen that set safely for outside contributors or bots?

level: seniorimportance: should knowfreq 14%

basics

~20 s

Before Claude starts, the action checks the triggering actor: on issue and PR events the user needs write access, and bot actors are rejected unless listed in allowed_bots. allowed_non_write_users, with your own github_token, admits named users without write access.

open as a page

What does `claude -p --bare` skip at startup, and why do Claude Code's docs recommend it for scripts and CI?

level: seniorimportance: should knowfreq 11%

basics

~20 s

--bare skips auto-discovery of hooks, skills, custom commands, subagents, plugins, MCP servers, auto memory and CLAUDE.md, so a scripted run starts faster, behaves the same on every machine and runs no repository config it was not handed.

open as a page

A Claude Code session schedules `0 9 * * *` with CronCreate; it fires around 9:20 daily and is gone a week later — why?

level: seniorimportance: should knowfreq 8%

basics

~10 s

Recurring CronCreate tasks get a deterministic jitter of up to 30 minutes after the scheduled time, and they expire seven days after creation, firing one final time before deleting themselves.

open as a page

After migrating from claude-code-sdk to the Claude Agent SDK, which defaults changed, and how do you restore Claude Code's behaviour?

level: middleimportance: nice to knowfreq 5%

basics

~20 s

Since Agent SDK v0.1.0 the packages and Python's ClaudeCodeOptions are renamed, and query() uses a minimal system prompt instead of Claude Code's; request the claude_code preset to restore it. Filesystem settings still load by default.

open as a page

How do you run Claude Code in a GitLab CI/CD job, and why doesn't an @claude comment start that job by itself?

level: middleimportance: nice to knowfreq 7%

basics

~20 s

In GitLab you add a job to .gitlab-ci.yml that installs Claude Code and runs claude -p with pre-approved tools, using a masked ANTHROPIC_API_KEY variable. A comment starts nothing until your webhook listener calls the pipeline trigger API.

open as a page

In Claude Code Review, how do REVIEW.md and CLAUDE.md differ in shaping what a pull request review flags?

level: middleimportance: nice to knowfreq 6%

basics

~20 s

CLAUDE.md is project context for every Claude Code task, and Code Review flags new violations of it as nits. REVIEW.md, at the repository root, is review-only instruction for the reviewing agents: severity definitions, nit caps, skip rules, mandatory checks.

open as a page

In a multi-step `claude -p` script, why capture `session_id` and pass `--resume` rather than chaining calls with `--continue`?

level: middleimportance: nice to knowfreq 7%

basics

~20 s

--continue picks the most recent conversation in the current directory, so concurrent jobs can grab each other's session; --resume with the session_id read from --output-format json targets exactly one conversation, from any directory on the machine.

open as a page

Why does a Claude Code Desktop scheduled task sometimes run hours late or not at all, and why can an unattended run stall?

level: middleimportance: nice to knowfreq 6%

basics

~20 s

Desktop tasks fire only while the app runs and the computer is awake; a slept-through time is skipped and one catch-up runs on wake for the latest miss. A Manual-mode run stalls on any unapproved tool until someone answers.

open as a page

A Claude Agent SDK service on a shared host picks up a developer's CLAUDE.md, hooks and allow rules; why, and how do you isolate it?

level: seniorimportance: nice to knowfreq 4%

basics

~20 s

Omitting settingSources loads user, project and local settings, CLAUDE.md, skills and hooks, exactly like the CLI. Pass settingSources: [], then switch off auto memory and claude.ai connectors separately; managed policy and ~/.claude.json are still read.

open as a page

How do a Claude Code routine's schedule, API and GitHub triggers start a run, and what bounds what that run can do?

level: seniorimportance: nice to knowfreq 5%

basics

~20 s

Each trigger starts a fresh cloud session: a schedule (hourly minimum), a bearer-token POST to /fire, or a GitHub pull request or release event. Runs have no permission-mode picker, so repositories, environment and connectors bound them.

open as a page