using-claude-code-cli

Invoke Claude Code CLI from Python orchestrators and shell scripts. Use when asked to "spawn claude as subprocess", "automate claude cli", "run claude headless", "configure --allowedTools", "set up claude hooks", or "parallel claude invocation". Covers permissions, directory access (--add-dir), hooks, sandbox mode, and async patterns.

Best use case

using-claude-code-cli is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Invoke Claude Code CLI from Python orchestrators and shell scripts. Use when asked to "spawn claude as subprocess", "automate claude cli", "run claude headless", "configure --allowedTools", "set up claude hooks", or "parallel claude invocation". Covers permissions, directory access (--add-dir), hooks, sandbox mode, and async patterns.

Teams using using-claude-code-cli should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/using-claude-code-cli/SKILL.md --create-dirs "https://raw.githubusercontent.com/SpillwaveSolutions/agent_rulez/main/.opencode/skill/using-claude-code-cli/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/using-claude-code-cli/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How using-claude-code-cli Compares

Feature / Agentusing-claude-code-cliStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Invoke Claude Code CLI from Python orchestrators and shell scripts. Use when asked to "spawn claude as subprocess", "automate claude cli", "run claude headless", "configure --allowedTools", "set up claude hooks", or "parallel claude invocation". Covers permissions, directory access (--add-dir), hooks, sandbox mode, and async patterns.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# Using Claude Code CLI

Patterns for programmatically invoking Claude Code CLI from orchestrators, scripts, and automation pipelines.

## Contents

- [Quick Start Checklist](#quick-start-checklist)
- [Essential Commands](#essential-commands)
- [Core CLI Flags](#core-cli-flags)
- [Sandbox Mode](#sandbox-mode)
- [Validation](#validation)
- [Troubleshooting](#troubleshooting)
- [When Not to Use](#when-not-to-use)

## Quick Start Checklist

Copy and track as you work:

```
CLI Automation Setup:
- [ ] 1. Identify required tools, add to --allowedTools
- [ ] 2. List directories Claude needs, add to --add-dir
- [ ] 3. Choose pattern: sync, async, or parallel (see references/)
- [ ] 4. Configure hooks if logging/monitoring needed
- [ ] 5. Enable sandbox mode for untrusted operations
- [ ] 6. Add fallback strategy if using OpenCode backup
- [ ] 7. Test with simple prompt before full automation
- [ ] 8. Validate setup (see Validation section)
```

## Essential Commands

**Minimal automation:**
```bash
claude -p "Your prompt" --allowedTools Write Read Edit --max-turns 5
```

**Full automation:**
```bash
claude \
  --model sonnet \
  --add-dir /path/to/skills \
  --add-dir /path/to/templates \
  --allowedTools Write Read Edit Bash Task \
  --output-format json \
  -p "Your automation prompt"
```

**With settings JSON:**
```bash
claude --settings '{"hooks":{},"sandbox":{"enabled":true}}' -p "prompt"
```

## Core CLI Flags

| Flag | Purpose | Example |
|------|---------|---------|
| `-p` | Non-interactive mode (required) | `claude -p "query"` |
| `--allowedTools` | Pre-approve tools | `--allowedTools Write Read Bash` |
| `--add-dir` | Grant directory access | `--add-dir ../lib` |
| `--settings` | Pass hooks/permissions JSON | `--settings ./settings.json` |
| `--model` | Select model | `--model sonnet` |
| `--output-format` | Output: text, json, stream-json | `--output-format json` |
| `--max-turns` | Limit agentic turns | `--max-turns 5` |

**Recommended tools for automation:**
- Core: `Write`, `Read`, `Edit`, `Glob`, `Grep`, `LS`
- Automation: `Bash`, `Task`, `Skill`
- Web: `WebFetch`, `WebSearch`

**MCP tools require full path:**
```bash
--allowedTools "mcp__perplexity-ask__perplexity_ask"
--allowedTools "mcp__context7__get-library-docs"
```

See [references/cli-reference.md](references/cli-reference.md) for complete flag documentation.

## Sandbox Mode

Enable sandbox for safe file operations:

**Via settings JSON:**
```bash
claude --settings '{"sandbox":{"enabled":true,"autoAllowBashIfSandboxed":true}}' -p "prompt"
```

**Via stdin (pass /sandbox before prompt):**
```python
stdin_content = "/sandbox\nYour actual prompt"
subprocess.run(["claude", "-p"], input=stdin_content, text=True)
```

See [references/hooks-examples.md](references/hooks-examples.md) for full sandbox options.

## Validation

Before full automation, verify setup works:

```bash
# 1. Test tool pre-approval (should complete without prompts)
claude -p "Create file test.txt with 'hello'" --allowedTools Write

# 2. Test directory access
claude -p "List files in /path/to/dir" --add-dir /path/to/dir --allowedTools LS

# 3. Test JSON output
claude -p "Return {\"status\": \"ok\"}" --output-format json | jq .

# 4. Test hooks (check log file after)
claude --settings '{"hooks":{...}}' -p "Simple task" --allowedTools Read
```

If any step fails, see [Troubleshooting](#troubleshooting).

## Troubleshooting

| Problem | Solution |
|---------|----------|
| Permission prompts appearing | Verify tool names match exactly (case-sensitive); MCP tools need full path |
| Hooks not firing | Check script is executable (`chmod +x`), has shebang, timeout not exceeded |
| Subprocess hangs | Add timeout; check if waiting for permission (missing --allowedTools) |
| Working directory issues | Use absolute paths in --add-dir; set cwd in subprocess |
| JSON parse errors | Use --output-format json; see [json-extraction.md](references/json-extraction.md) |

## When Not to Use

This skill is for **subprocess invocation**. Do not use for:
- Interactive Claude sessions (use Claude directly)
- API integration (use Claude SDK/API)
- MCP server setup (use `claude mcp` command)

## Reference Files

| File | Contents |
|------|----------|
| [cli-reference.md](references/cli-reference.md) | Complete CLI commands and flags |
| [subprocess-patterns.md](references/subprocess-patterns.md) | Python sync/async/parallel patterns |
| [hooks-examples.md](references/hooks-examples.md) | Hook scripts and settings JSON |
| [json-extraction.md](references/json-extraction.md) | Parsing JSON from CLI output |
| [orchestrator_example.py](references/orchestrator_example.py) | Complete Python orchestrator class |

## OpenCode CLI Fallback

When using OpenCode as fallback, note key differences:

| Feature | Claude CLI | OpenCode CLI |
|---------|------------|--------------|
| Headless | `claude -p "prompt"` | `opencode run "prompt"` |
| Model | `--model sonnet` | `--model provider/model` |
| Settings | `--settings JSON` | Not supported |
| Add dirs | `--add-dir /path` | Not supported |

**Try-Claude-then-OpenCode pattern:**
```python
import subprocess

def invoke_with_fallback(prompt: str, timeout: int = 300) -> str:
    """Try Claude CLI first, fall back to OpenCode on failure."""
    try:
        result = subprocess.run(
            ["claude", "-p", prompt, "--allowedTools", "Write", "Read"],
            capture_output=True, text=True, timeout=timeout
        )
        if result.returncode == 0:
            return result.stdout
    except (subprocess.TimeoutExpired, FileNotFoundError):
        pass  # Fall through to OpenCode

    result = subprocess.run(
        ["opencode", "run", prompt],
        capture_output=True, text=True, timeout=timeout
    )
    return result.stdout
```

See [subprocess-patterns.md](references/subprocess-patterns.md) for advanced patterns.

Related Skills

mastering-hooks

40
from SpillwaveSolutions/agent_rulez

Master RuleZ, the high-performance AI policy engine for development workflows. Use when asked to "install rulez", "create hooks", "debug hooks", "hook not firing", "configure context injection", "validate hooks.yaml", "PreToolUse", "PostToolUse", "block dangerous commands", "multi-platform hooks", "Gemini CLI hooks", "Copilot hooks", "OpenCode hooks", "dual-fire events", or "cross-platform rules". Covers installation, rule creation, multi-platform adapters, troubleshooting, and optimization.

release-rulez

40
from SpillwaveSolutions/agent_rulez

RuleZ release workflow automation. Use when asked to "release RuleZ", "create a release", "prepare release", "tag version", "hotfix release", or "publish RuleZ". Covers version management from Cargo.toml, changelog generation from conventional commits, PR creation, tagging, hotfix workflows, and GitHub Actions release monitoring.

vercel-react-best-practices

40
from SpillwaveSolutions/agent_rulez

React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.

project-memory

40
from SpillwaveSolutions/agent_rulez

Set up and maintain a structured project memory system in docs/project_notes/ that tracks bugs with solutions, architectural decisions, key project facts, and work history. Use this skill when asked to "set up project memory", "track our decisions", "log a bug fix", "update project memory", or "initialize memory system". Configures both CLAUDE.md and AGENTS.md to maintain memory awareness across different AI coding tools.

pr-reviewer

40
from SpillwaveSolutions/agent_rulez

Comprehensive GitHub Pull Request code review skill. Use when asked to "review this PR", "code review", "review pull request", "check this PR", or when a GitHub PR URL is provided. Fetches PR metadata, diff, comments, commits, and related issues using gh CLI. Creates organized review workspace, analyzes code against industry-standard criteria, and optionally adds inline comments to the PR.

plantuml

40
from SpillwaveSolutions/agent_rulez

Generate PlantUML diagrams from text descriptions and convert them to PNG/SVG images. Use when asked to "create a diagram", "generate PlantUML", "convert puml to image", "extract diagrams from markdown", or "prepare markdown for Confluence". Supports all PlantUML diagram types including UML (sequence, class, activity, state, component, deployment, use case, object, timing) and non-UML (ER diagrams, Gantt charts, JSON/YAML visualization, mindmaps, WBS, network diagrams, wireframes, and more).

mastering-typescript

40
from SpillwaveSolutions/agent_rulez

Master enterprise-grade TypeScript development with type-safe patterns, modern tooling, and framework integration. This skill provides comprehensive guidance for TypeScript 5.9+, covering type system fundamentals (generics, mapped types, conditional types, satisfies operator), enterprise patterns (error handling, validation with Zod), React integration for type-safe frontends, NestJS for scalable APIs, and LangChain.js for AI applications. Use when building type-safe applications, migrating JavaScript codebases, configuring modern toolchains (Vite 7, pnpm, ESLint, Vitest), implementing advanced type patterns, or comparing TypeScript with Java/Python approaches.

mastering-python-skill

40
from SpillwaveSolutions/agent_rulez

Modern Python coaching covering language foundations through advanced production patterns. Use when asked to "write Python code", "explain Python concepts", "set up a Python project", "configure Poetry or PDM", "write pytest tests", "create a FastAPI endpoint", "run uvicorn server", "configure alembic migrations", "set up logging", "process data with pandas", or "debug Python errors". Triggers on "Python best practices", "type hints", "async Python", "packaging", "virtual environments", "Pydantic validation", "dependency injection", "SQLAlchemy models".

mastering-github-cli

40
from SpillwaveSolutions/agent_rulez

GitHub CLI (gh) command reference for repository search, code discovery, CI/CD monitoring, workflow authoring, and automation. Triggers on "gh" commands, "github cli", searching repos for files/directories (.skilz, .cursor, .codex, Dockerfile), monitoring GitHub Actions workflows, checking PR CI status, downloading artifacts, creating PRs/issues/repos from command line, triggering workflows, forking repos, batch operations, "write a workflow", "github actions", "CI/CD pipeline", "workflow yaml", and "matrix builds". Use for gh search, gh run, gh pr, gh issue, gh repo, gh workflow, gh api, workflow authoring, and automating GitHub operations.

mastering-git-cli

40
from SpillwaveSolutions/agent_rulez

Git CLI operations, workflows, and automation for modern development (2025). Use when working with repositories, commits, branches, merging, rebasing, worktrees, submodules, or multi-repo architectures. Includes parallel agent workflow patterns, merge strategies, conflict resolution, and large repo optimization. Triggers on git commands, version control, merge conflicts, worktree setup, submodule management, repository troubleshooting, branch strategy, rebase operations, cherry-pick decisions, and CI/CD git integration.

documentation-specialist

40
from SpillwaveSolutions/agent_rulez

This skill should be used when creating professional software documentation (SRS, PRD, OpenAPI, user manuals, tutorials, runbooks) from templates (greenfield) or reverse-engineering documentation from existing code like Spring Boot or FastAPI (brownfield). Also handles documentation audits/reviews, format conversion (Markdown, DOCX, PDF), and diagram generation (C4, Mermaid, PlantUML, ER, sequence). Use when asked to "create documentation", "document my code", "write SRS", "generate PRD", or "documentation specialist".

design-doc-mermaid

40
from SpillwaveSolutions/agent_rulez

Create Mermaid diagrams (activity, deployment, sequence, architecture) from text descriptions or source code. Use when asked to "create a diagram", "generate mermaid", "document architecture", "code to diagram", "create design doc", or "convert code to diagram". Supports hierarchical on-demand guide loading, Unicode semantic symbols, and Python utilities for diagram extraction and image conversion.