CtrlK
BlogDocsLog inGet started
Tessl Logo

headless-sdk-automation

This skill should be used when the user asks to automate Claude Code headlessly, run claude -p in CI or scripts, parse json or stream-json output, use --bare, configure non-interactive permissions, compare CLI vs TypeScript or Python Agent SDK usage, wire MCP or hooks for automation, resume sessions programmatically, or harden reproducible Claude Code automation.

SKILL.md
Quality
Evals
Security

Headless SDK Automation

Design, audit, and harden Claude Code automation that runs without the interactive terminal loop. Use this skill for claude -p, --output-format json, --output-format stream-json, --bare, CI (Continuous Integration / Integración Continua) and script wrappers, session continuation, permission modes, settings/model flags, MCP (Model Context Protocol) and hook behavior, and TypeScript or Python Agent SDK (Software Development Kit) boundaries. [DOC]

Boundary: if the user is not automating Claude Code or the Agent SDK, and instead needs a hand-managed Claude Platform Messages API client loop for tool_use/tool_result correlation, stop handling, strict schemas, fine-grained tool streaming, prompt caching, or retries, route to claude-api-tool-runtime. [CONFIG]

Lineage note: this is a Claude-native port whose technical body is kept in English to match the upstream CLI flags, --option names, and official docs verbatim; the Contract section uses neutral Latin-American Spanish per house style. [DOC]

Treat the active Claude Code version and official docs as runtime authority. If the installed CLI, SDK package versions, auth route, settings scope, MCP config, or hook behavior cannot be verified, write coverage_gap instead of assuming it. [DOC][INFERENCIA]

Supporting files:

  • references/cli-headless-patterns.md - CLI flags, JSON/streaming patterns, --bare, CI examples, and session controls. [DOC]
  • references/sdk-boundaries.md - When to choose CLI, TypeScript SDK, or Python SDK; query() vs client sessions; structured output boundaries. [DOC]
  • references/security-reproducibility.md - Permission, settings, MCP, hooks, auth, and reproducibility controls. [DOC][INFERENCIA]
  • references/official-source-map.md - Source URLs, checked-date notes, and local runtime evidence. [CONFIG]
  • assets/headless-run-checklist.md - Preflight and closeout checklist for scriptable runs. [CONFIG]
  • assets/ci-script-template.sh - Portable shell template for a locked-down claude -p --bare invocation. [CONFIG]
  • assets/headless-output.schema.json - Example JSON Schema for validated structured output. [CONFIG]
  • scripts/check.sh - Deterministic package check for required terms, assets, evals, and JSON fixtures. [CONFIG]

Inputs Expected

  • Automation target: one-off shell call, CI check, local batch script, SDK service, hook, MCP-backed run, or session-resume workflow.
  • Runtime facts: claude --version, operating directory, trust/auth route, provider, model or alias, and SDK package versions when relevant.
  • I/O (Input/Output / Entrada-Salida) contract: stdin size, file inputs, expected output format, JSON schema, streaming parser, and failure handling.
  • Permission boundary: allowed tools, denied tools, --permission-mode, settings scope, MCP config, secrets policy, and whether writes are allowed.
  • Reproducibility boundary: --bare decision, explicit context flags, settings sources, session persistence, logs, and cost/turn budget.

Outputs Expected

  • A CLI command, CI snippet, SDK design, or audit report with evidence tags.
  • A clear route decision: CLI claude -p, TypeScript Agent SDK, Python Agent SDK, or "do not automate yet".
  • Parser contract for text, json, or stream-json, including exact fields to consume and events to ignore.
  • Permission/settings/model plan that avoids implicit local state unless it is intentionally required.
  • Security and reproducibility checklist with residual coverage_gap items.

Core Rules

Use claude -p or claude --print for non-interactive runs that should return through stdout and exit. Prefer it for shell scripts, CI jobs, simple reviewers, typed extraction, and resumable follow-up prompts where a subprocess boundary is acceptable. [DOC]

Use --bare for CI and reproducible scripts unless the task explicitly depends on project/user hooks, MCP servers, plugins, auto memory, or discovered CLAUDE.md context. In bare mode, pass context explicitly with --system-prompt, --append-system-prompt, --settings, --mcp-config, --agents, --plugin-dir, --plugin-url, or prompt file references. [DOC]

Use --output-format json when the caller needs one final object with result, session metadata, usage/cost, or structured_output. Pair it with --json-schema for machine-consumed decisions. Use jq or a typed parser; never scrape plain prose when JSON is available. [DOC][INFERENCIA]

Use --output-format stream-json --verbose when the caller needs progress, retries, init metadata, hook events, partial tokens, or a real-time UI. Treat each line as an event object and filter by type, subtype, and nested event fields. Do not assume every line is assistant text. [DOC]

Select the least permissive permission mode that satisfies the run. Prefer dontAsk plus narrow permissions.allow rules for locked-down CI; use acceptEdits only when file writes are expected and reviewed; reserve bypassPermissions or --dangerously-skip-permissions for isolated containers or VMs (Virtual Machines / Máquinas Virtuales). [DOC][INFERENCIA]

Use TypeScript or Python Agent SDK when the caller needs native message objects, callbacks, long-running application control, tool approval handling, MCP/custom tools, structured output in code, or continuous sessions. Keep ordinary shell checks on CLI until SDK control materially reduces risk or complexity. [DOC][INFERENCIA]

Treat hooks and MCP as explicit runtime dependencies. --bare skips auto-discovered hooks and MCP servers, so pass --mcp-config and avoid relying on user-local hooks. To observe hooks in streaming output, use --include-hook-events with stream-json and a parser that ignores unrelated events. [DOC]

Procedure

1. Gate Runtime

Run or request claude --version; capture SDK versions with npm view @anthropic-ai/claude-agent-sdk version --json or the active package manager when SDK code is in scope. Read claude --help for installed flags and check official docs for doc-only or newer flags. Note that some flags (e.g. --max-turns, --system-prompt-file) exist at runtime even when absent from --help; probe them with an actual flag-parse rather than assuming they are missing, and reserve coverage_gap for flags that genuinely error as unknown. Mark mismatches as coverage_gap. [CÓDIGO][DOC]

2. Choose Interface

Choose CLI for shell-native, single exchange, CI, stdout parsing, or simple resume. Choose TypeScript SDK for Node services, typed async generators, bundled native CLI handling, and Zod schemas. Choose Python SDK for Python services, ClaudeSDKClient continuous sessions, Pydantic schemas, or custom tool decorators. [DOC][INFERENCIA]

3. Design Command Or SDK Options

State --bare, --model, --effort, --permission-mode, --settings, --setting-sources, --allowedTools, --disallowedTools, --tools, --mcp-config, --strict-mcp-config, --max-budget-usd, --max-turns, --no-session-persistence, --session-id, --resume, or --continue decisions when relevant. Keep prompt and settings stable and reviewable. [DOC]

4. Define I/O Contract

For stdin, keep within documented caps or write large input to a file and reference the path. For JSON, define the schema and parse structured_output or result. For streaming, define accepted event types, retry handling, final-result detection, and logs. [DOC][INFERENCIA]

5. Harden Security And Reproducibility

Apply assets/headless-run-checklist.md. Deny secrets, avoid broad Bash or MCP allows, pin settings sources, capture session IDs, record system/init metadata when streaming, and keep auth out of command history. [CONFIG][INFERENCIA]

6. Validate

Run scripts/check.sh for this skill package. For produced automation, run a dry-run or harmless prompt first, parse the output with the intended parser, and fail closed on malformed JSON, missing session IDs, permission prompts, auth errors, or unexpected local customization. [CÓDIGO][INFERENCIA]

Quality Criteria

  • Route decision names CLI, TypeScript SDK, Python SDK, or no automation.
  • --bare is selected or rejected with a reproducibility reason.
  • Output format and parser contract are explicit.
  • Permission mode, allowed/denied tools, settings sources, model, and MCP policy are stated.
  • Hooks, MCP, sessions, and persistence behavior are included when relevant.
  • Security controls cover secrets, destructive tools, auth route, and workspace trust.
  • Reproducibility controls cover versions, explicit context, budgets, and logs.
  • Residual unknowns are reported as coverage_gap.

Usage

  • /headless-sdk-automation
  • wrap claude -p in a CI script and parse JSON
  • audit this stream-json parser for Claude Code
  • compare CLI vs TypeScript Agent SDK for this automation
  • make this --bare Claude Code run reproducible
  • For direct Claude Platform Messages API tool loops, use claude-api-tool-runtime instead. [CONFIG]

Related katas (toolkit)

  • katas-headless-code-review

Contract

  • Aceptación: patrón Agent SDK reproducible (py/ts) con verificación post-ejecución. [EXPLICIT]
  • Límites: patrón de automatización; no sustituye CI/CD del proyecto. [EXPLICIT]
  • Casos borde: flags menos comunes pendientes vs cli-reference [coverage_gap]. [EXPLICIT]
  • Supuestos: agentes agent-sdk-dev presentes [CÓDIGO][DOC]. [SUPUESTO]
  • Trade-off: headless escala sin UI a cambio de menos interactividad/observabilidad. [EXPLICIT]

Packet

Capas del packet, cargables bajo demanda (disciplina ICM: una capa por vez, nunca todas juntas): references/ guías de profundidad (cargar UNA por etapa) · knowledge/ cuerpo de conocimiento · prompts/ prompts listos · examples/ salida de ejemplo · agents/ subagentes del packet · templates/ plantilla de output · scripts/ automatización local · assets/ recursos estáticos.

Repository
JaviMontano/claude-plugins
Last updated
First committed

Is this your skill?

If you maintain this skill, you can claim it as your own. Once claimed, you can manage eval scenarios, bundle related skills, attach documentation or rules, and ensure cross-agent compatibility.