Python SDK wrapping Claude CLI - Use Skills, Hooks, Slash Commands, Agents without official SDK
Project description
Claude CLI SDK
A Python library that wraps Claude CLI as a subprocess, providing SDK-like usage. Use all Claude CLI features including Skills, Hooks, Slash Commands, and Agents without requiring an official SDK.
Installation
pip install claude-cli-sdk
Prerequisites: Claude CLI must be installed and available in your PATH.
Quick Start
Async Usage
import asyncio
from claude_cli_sdk import Claude
async def main():
async with Claude() as claude:
result = await claude.run("What is Python?")
print(result.text)
asyncio.run(main())
Sync Usage
from claude_cli_sdk import ClaudeSync
claude = ClaudeSync()
result = claude.run("Hello!")
print(result.text)
Features
| Feature | Description |
|---|---|
| Skills | Call registered skills via --setting-sources |
| Hooks | Auto-load hooks from settings |
| Agents (Task tool) | Use Explore, Plan, and other agents |
| Slash Commands | Execute custom slash commands |
| MCP Servers | Configure via --mcp-config |
| CLAUDE.md | Auto-load project context |
| Streaming | Real-time event streaming |
| Cancellation | Cancel long-running operations |
Usage Examples
Configuration
from claude_cli_sdk import Claude, ClaudeConfig, PermissionMode
config = ClaudeConfig(
model="sonnet", # Model to use
permission_mode=PermissionMode.ACCEPT_EDITS, # Auto-approve edits
allowed_tools=["Read", "Write", "Bash"], # Allowed tools
max_turns=5, # Max conversation turns
timeout=120.0, # Timeout in seconds
cwd="/path/to/project", # Working directory
system_prompt="You are a helpful assistant" # Custom system prompt
)
async with Claude(config) as claude:
result = await claude.run("Analyze the codebase")
Using Skills
# Async
result = await claude.skill("frontend-design", "Create a login form with validation")
# Sync
result = claude.skill("frontend-design", "Create a responsive navbar")
Using Agents
# Explore agent - search and understand codebase
result = await claude.agent("Explore", "Find all API endpoints in the project")
# Plan agent - design implementation strategies
result = await claude.agent("Plan", "Design a user authentication system")
Slash Commands
# Execute a slash command
result = await claude.command("code-review")
# With arguments
result = await claude.command("feature-dev", "Add user profile page")
Streaming Execution
async for event in claude.run_streaming("Explain async programming"):
print(f"[{event.type}]", end=" ")
if event.type == "assistant":
print(event.message)
elif event.type == "result":
print(event.result_text)
With File Context
# Include files as context
result = await claude.run_with_files(
"Review these files for security issues",
["src/auth.py", "src/database.py", "config.yaml"]
)
Cancellation
from claude_cli_sdk import CancellationToken
token = CancellationToken()
# Start a long-running task
task = asyncio.create_task(
claude.run("Complex analysis task", cancel_token=token)
)
# Cancel after 10 seconds
await asyncio.sleep(10)
token.cancel()
Progress Callback
def on_progress(event_type: str, data: dict):
if event_type == "assistant":
print("Claude is responding...")
elif event_type == "tool_use":
print(f"Using tool: {data.get('name')}")
result = await claude.run(
"Create a Python script",
on_progress=on_progress
)
Session Continuation
# First interaction
result1 = await claude.run("My name is Alice")
# Continue the conversation
result2 = await claude.continue_conversation("What is my name?")
print(result2.text) # "Your name is Alice"
Hook Management
Programmatically manage Claude CLI hooks without editing settings.json manually:
from claude_cli_sdk import HookManager, Hook, quick_hook_setup
# Create a hook manager
hooks = HookManager()
# Add pre-tool hooks (called before tool executes)
hooks.add_pre_tool_use(Hook(
matcher="Bash", # Match Bash tool
command="./validate.sh", # Run this script
timeout=5000 # 5 second timeout
))
# Add post-tool hooks (called after tool completes)
hooks.add_post_tool_use(Hook(
matcher="*", # Match all tools
command="./log_tool.sh"
))
# Save to project settings (.claude/settings.json)
hooks.save_to_project()
# Or save to user settings (~/.claude/settings.json)
hooks.save_to_user()
Quick Hook Setup
from claude_cli_sdk import quick_hook_setup
# One-liner for common hook configurations
hooks = quick_hook_setup(
validate_bash="./scripts/validate_bash.sh", # Validate Bash commands
log_tools="./scripts/log_all_tools.sh", # Log all tool usage
backup_edits="./scripts/backup_before_edit.sh" # Backup before editing
)
hooks.save_to_project()
Convenience Hook Creators
from claude_cli_sdk import (
create_bash_validator,
create_file_logger,
create_edit_backup
)
# Create specific hooks easily
bash_hook = create_bash_validator("./validate.sh", timeout=3000)
log_hook = create_file_logger("./log.sh", tools="Write")
backup_hook = create_edit_backup("./backup.sh")
hooks = HookManager()
hooks.add_pre_tool_use(bash_hook)
hooks.add_pre_tool_use(backup_hook)
hooks.add_post_tool_use(log_hook)
hooks.save_to_project()
Load and Modify Existing Hooks
hooks = HookManager()
hooks.load_from_project() # Load existing hooks
# Modify
hooks.add_pre_tool_use(Hook(matcher="Write", command="./check_write.sh"))
# Save back
hooks.save_to_project()
# Remove all hooks
hooks.remove_from_project()
Quick Functions (One-liners)
from claude_cli_sdk import (
quick_run, quick_run_sync,
quick_skill, quick_skill_sync,
quick_agent, quick_agent_sync,
quick_command, quick_streaming
)
# Async one-liners
result = await quick_run("Hello!")
result = await quick_skill("frontend-design", "Create a button")
result = await quick_agent("Explore", "Find Python files")
result = await quick_command("code-review")
# Sync one-liners
result = quick_run_sync("Hello!")
# Streaming
async for event in quick_streaming("Explain this"):
print(event.type)
# With config options
result = await quick_run("Explain this", model="opus", max_turns=3)
Result Object
The ClaudeResult object provides rich access to execution results:
result = await claude.run("Create a script")
# Basic properties
result.text # Final result text
result.success # True if successful
result.session_id # Session ID for continuation
result.stderr # Standard error output
# Execution info
result.cost # Cost information (if available)
result.duration_ms # Execution duration in ms
result.num_turns # Number of conversation turns
# Tool usage
result.tools_used # List of tools used: ["Write", "Bash", ...]
result.has_tool("Write") # Check if specific tool was used
result.get_tool_results("Read") # Get results from specific tool
# Messages
result.get_assistant_messages() # All assistant text messages
result.get_events_by_type("tool_use") # Filter events by type
# Iteration
for event in result.iter_events():
print(event.type, event.data)
# Boolean check
if result: # True if success
print("Success!")
Configuration Options
from claude_cli_sdk import ClaudeConfig, PermissionMode, OutputFormat
config = ClaudeConfig(
# Model selection
model="sonnet", # or "opus", "haiku", etc.
# Permission handling
permission_mode=PermissionMode.ACCEPT_EDITS, # Auto-approve file edits
# Options: DEFAULT, ACCEPT_EDITS, BYPASS_PERMISSIONS
# Output format (usually keep default)
output_format=OutputFormat.STREAM_JSON,
# Settings sources for Skills, Hooks, CLAUDE.md
setting_sources=["user", "project"],
# Tool permissions
allowed_tools=["Read", "Write", "Bash", "Glob", "Grep"],
disallowed_tools=["dangerous_tool"],
# MCP configuration
mcp_config="/path/to/mcp-config.json",
# Working directory
cwd="/path/to/project",
# Conversation limits
max_turns=10,
# Custom system prompt
system_prompt="You are a code review expert",
# Timeout
timeout=300.0, # 5 minutes
# Claude CLI path (if not in PATH)
claude_path="/usr/local/bin/claude"
)
Event Types
When streaming or analyzing results, you'll encounter these event types:
| Type | Description |
|---|---|
system |
Session information (contains session_id) |
assistant |
Claude's response (text and tool calls) |
tool_use |
Tool invocation details |
tool_result |
Tool execution results |
result |
Final result of the execution |
error |
Error information |
Architecture
┌─────────────────────────────────────────┐
│ Your Python Application │
├─────────────────────────────────────────┤
│ claude_cli_sdk │
│ - Async/Sync clients │
│ - subprocess.Popen("claude", ...) │
│ - JSON stream parsing │
│ - Event handling │
├─────────────────────────────────────────┤
│ Claude CLI │
│ (All features exposed via flags) │
└─────────────────────────────────────────┘
CLI Flags Reference
The SDK uses these Claude CLI flags internally:
| Flag | Purpose |
|---|---|
--setting-sources "user,project" |
Load Skills, Hooks, CLAUDE.md |
--allowed-tools "Tool1,Tool2" |
Specify allowed tools |
--output-format stream-json |
JSON stream output |
--verbose |
Required for stream-json |
--permission-mode acceptEdits |
Auto-approve file edits |
--max-turns N |
Limit conversation turns |
--mcp-config path |
MCP server configuration |
--model name |
Model selection |
--system-prompt text |
Custom system prompt |
License
MIT License
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file claude_cli_sdk-0.2.0.tar.gz.
File metadata
- Download URL: claude_cli_sdk-0.2.0.tar.gz
- Upload date:
- Size: 15.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
902ddeff6eeecfed028660f0ee458edea5b3d8052fe8f386a6735fd09fb8f17b
|
|
| MD5 |
d91f4a0738834633185e08e68cbba84e
|
|
| BLAKE2b-256 |
07d5e12c39e01e82599cbfaa90921c3ba65c553d8fd5860ae2ca1098e180a9a6
|
File details
Details for the file claude_cli_sdk-0.2.0-py3-none-any.whl.
File metadata
- Download URL: claude_cli_sdk-0.2.0-py3-none-any.whl
- Upload date:
- Size: 18.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a10bbecec6cfecafcd0702a3a8acee92eac3c07131e0be385089c8c6e35b2947
|
|
| MD5 |
80c4a565ddae7ef065aaea5dd696a044
|
|
| BLAKE2b-256 |
002633c2de79f8cbc8d0f7f733f472c9c5f90ae4b1f7a03bf20026515ba6ebe0
|