Python SDK for programmatically interacting with Claude Code, enabling AI-powered automation workflows with support for bidirectional conversations, custom in-process tools, hooks, and fine-grained permission control
—
—
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
View guide
—
The risk profile of this skill
This plugin was archived by the owner on Jun 3, 2026
Reason: Retiring all tiles created prior to the transition to plugin support
Define custom agents with specific behaviors, tools, prompts, and models. Agents allow you to create specialized AI assistants tailored for specific tasks or domains.
Configuration for a custom agent.
@dataclass
class AgentDefinition:
"""
Agent definition configuration.
Defines a custom agent with specific capabilities, behavior, and model.
Agents can have specialized prompts, restricted tool access, and use
specific models for their tasks.
Use cases:
- Task-specific agents (reviewer, implementer, tester)
- Domain experts (security, performance, documentation)
- Role-based assistants (junior developer, senior architect)
- Workflow stages (planning, execution, verification)
Attributes:
description: Human-readable agent description
prompt: System prompt defining agent behavior
tools: Available tools for this agent
model: Model to use for this agent
"""
description: str
"""Agent description.
A human-readable description of what this agent does and when to use it.
This helps understand the agent's purpose and capabilities.
Example:
"Code review expert who focuses on security and best practices"
"Implementation specialist who writes clean, tested code"
"Documentation writer who creates clear, comprehensive docs"
"""
prompt: str
"""Agent system prompt.
The system prompt that defines the agent's behavior, personality, and
capabilities. This is the core instruction that shapes how the agent
responds and acts.
The prompt should:
- Define the agent's role and expertise
- Specify behavioral guidelines
- Set output format expectations
- Include relevant constraints or rules
Example:
"You are a security-focused code reviewer. When reviewing code:
1. Check for common vulnerabilities (XSS, SQL injection, etc.)
2. Verify input validation and sanitization
3. Review authentication and authorization logic
4. Flag hardcoded secrets or credentials
Always provide specific line numbers and remediation suggestions."
"""
tools: list[str] | None = None
"""Available tools.
List of tool names this agent can use. If None, the agent inherits
tool permissions from the parent configuration.
Restricting tools helps:
- Prevent unwanted actions (e.g., reviewer can't modify code)
- Focus agent capabilities (e.g., docs writer only needs Read)
- Enforce workflow boundaries (e.g., planner can't execute)
Example:
["Read", "Grep", "Glob"] # Read-only agent
["Write", "Edit", "MultiEdit"] # Editor agent
["Bash"] # Executor agent
None # Inherit from parent
"""
model: Literal["sonnet", "opus", "haiku", "inherit"] | None = None
"""Model to use.
The Claude model this agent should use. Options:
- 'sonnet': Claude Sonnet (balanced performance)
- 'opus': Claude Opus (maximum capability)
- 'haiku': Claude Haiku (fast and efficient)
- 'inherit': Use parent model configuration
- None: Use default model
Choose based on task requirements:
- Use 'opus' for complex reasoning and code generation
- Use 'sonnet' for balanced general-purpose work
- Use 'haiku' for simple, fast operations
- Use 'inherit' to match parent configuration
"""System prompt preset configuration.
class SystemPromptPreset(TypedDict):
"""
System prompt preset configuration.
Allows using a preset system prompt with optional additional text.
Currently only supports the "claude_code" preset.
Fields:
type: Must be "preset"
preset: Preset name (currently only "claude_code")
append: Optional text to append to the preset
"""
type: Literal["preset"]
"""Type marker.
Must be "preset" to indicate this is a preset configuration.
"""
preset: Literal["claude_code"]
"""Preset name.
The name of the preset to use. Currently only "claude_code" is
supported, which provides the standard Claude Code system prompt.
"""
append: NotRequired[str]
"""Text to append.
Optional text to append to the preset prompt. Use this to add
additional instructions or constraints while keeping the base
preset behavior.
Example:
"Additionally, focus on performance optimization"
"Always explain your reasoning before taking action"
"""Setting source types for loading configuration.
SettingSource = Literal["user", "project", "local"]
"""
Setting source types.
Specifies which setting files to load:
- 'user': User-level settings (~/.config/claude/)
- 'project': Project-level settings (.claude/ in project root)
- 'local': Local settings (.claude/ in current directory)
Used in ClaudeAgentOptions.setting_sources to control which
configuration files are loaded.
"""from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
# Define a code reviewer agent
reviewer = AgentDefinition(
description="Code review expert",
prompt="""You are a code reviewer. Focus on:
- Code quality and best practices
- Potential bugs and edge cases
- Security vulnerabilities
- Performance issues
Provide specific feedback with line numbers.""",
tools=["Read", "Grep", "Glob"],
model="sonnet"
)
options = ClaudeAgentOptions(
agents={"reviewer": reviewer}
)
async for msg in query(prompt="Review this codebase", options=options):
print(msg)from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
# Define specialized agents for different tasks
agents = {
"reviewer": AgentDefinition(
description="Code review expert",
prompt="You are a code reviewer. Find bugs, security issues, and suggest improvements.",
tools=["Read", "Grep"],
model="sonnet"
),
"implementer": AgentDefinition(
description="Code implementation expert",
prompt="You are an implementation expert. Write clean, tested, documented code.",
tools=["Read", "Write", "Edit", "Bash"],
model="sonnet"
),
"documenter": AgentDefinition(
description="Documentation specialist",
prompt="You are a documentation expert. Write clear, comprehensive documentation.",
tools=["Read", "Write"],
model="haiku" # Faster for docs
),
"tester": AgentDefinition(
description="Testing specialist",
prompt="You are a testing expert. Write comprehensive tests with good coverage.",
tools=["Read", "Write", "Bash"],
model="sonnet"
)
}
options = ClaudeAgentOptions(agents=agents)
async for msg in query(
prompt="First review, then implement, document, and test",
options=options
):
print(msg)from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
security_agent = AgentDefinition(
description="Security auditor",
prompt="""You are a security expert. When analyzing code:
1. Check for OWASP Top 10 vulnerabilities
2. Review authentication and authorization
3. Look for hardcoded secrets
4. Verify input validation
5. Check for injection vulnerabilities
6. Review cryptographic implementations
7. Check for insecure dependencies
For each issue found:
- Provide file and line number
- Explain the vulnerability
- Suggest remediation
- Rate severity (Critical/High/Medium/Low)""",
tools=["Read", "Grep", "Glob"],
model="opus" # Use most capable model for security
)
options = ClaudeAgentOptions(
agents={"security": security_agent}
)
async for msg in query(prompt="Perform security audit", options=options):
print(msg)from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
performance_agent = AgentDefinition(
description="Performance optimization expert",
prompt="""You are a performance optimization expert. Analyze code for:
1. Algorithmic complexity (O(n), O(n²), etc.)
2. Memory usage and leaks
3. Unnecessary computations
4. Database query efficiency
5. Caching opportunities
6. Concurrency issues
7. Resource cleanup
Provide:
- Current performance characteristics
- Optimization suggestions
- Expected improvements
- Code examples""",
tools=["Read", "Grep", "Bash"],
model="opus"
)
options = ClaudeAgentOptions(
agents={"performance": performance_agent}
)
async for msg in query(prompt="Optimize this application", options=options):
print(msg)from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
# Agent that can only read, never modify
analyzer = AgentDefinition(
description="Code analyzer (read-only)",
prompt="""You are a code analyzer. Examine code and provide insights:
- Architecture and design patterns
- Code organization and structure
- Dependencies and imports
- Complexity metrics
- Potential refactoring opportunities
You cannot modify code, only analyze and provide recommendations.""",
tools=["Read", "Grep", "Glob"], # No write tools
model="sonnet"
)
options = ClaudeAgentOptions(
agents={"analyzer": analyzer}
)
async for msg in query(prompt="Analyze architecture", options=options):
print(msg)from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
# Agent that inherits tool permissions from parent
flexible_agent = AgentDefinition(
description="Flexible assistant",
prompt="You are a general-purpose assistant. Adapt to the task at hand.",
tools=None, # Inherit from ClaudeAgentOptions.allowed_tools
model="inherit" # Inherit model from parent
)
options = ClaudeAgentOptions(
allowed_tools=["Read", "Write", "Bash"], # Agent will use these
model="claude-sonnet-4-5", # Agent will use this
agents={"assistant": flexible_agent}
)
async for msg in query(prompt="Help with this task", options=options):
print(msg)from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
# Define agents for different workflow stages
planner = AgentDefinition(
description="Planning agent",
prompt="""You are a planning expert. Create detailed implementation plans:
1. Break down requirements
2. Identify dependencies
3. Define tasks and subtasks
4. Estimate complexity
5. Suggest order of implementation
Output a structured plan, not code.""",
tools=["Read", "Grep"],
model="sonnet"
)
implementer = AgentDefinition(
description="Implementation agent",
prompt="""You are an implementation expert. Follow the plan and:
1. Write clean, maintainable code
2. Add appropriate error handling
3. Include helpful comments
4. Follow coding standards""",
tools=["Read", "Write", "Edit"],
model="sonnet"
)
verifier = AgentDefinition(
description="Verification agent",
prompt="""You are a verification expert. Check that:
1. Implementation matches plan
2. Code works as expected
3. Error cases are handled
4. Tests pass""",
tools=["Read", "Bash"],
model="sonnet"
)
options = ClaudeAgentOptions(
agents={
"planner": planner,
"implementer": implementer,
"verifier": verifier
}
)
async for msg in query(
prompt="Plan, implement, and verify a new feature",
options=options
):
print(msg)from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
docs_agent = AgentDefinition(
description="Documentation specialist",
prompt="""You are a documentation expert. Create clear, comprehensive documentation:
For functions/classes:
- Purpose and usage
- Parameters and return values
- Examples
- Edge cases and limitations
For projects:
- Overview and architecture
- Setup instructions
- Usage examples
- API reference
Write in clear, simple language. Use examples liberally.""",
tools=["Read", "Write"],
model="haiku" # Fast for documentation
)
options = ClaudeAgentOptions(
agents={"documenter": docs_agent}
)
async for msg in query(prompt="Document this codebase", options=options):
print(msg)from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
testing_agent = AgentDefinition(
description="Testing specialist",
prompt="""You are a testing expert. Create comprehensive tests:
1. Unit tests for individual functions
2. Integration tests for component interaction
3. Edge case and error condition tests
4. Performance tests for critical paths
Use appropriate testing frameworks (pytest, unittest, etc.)
Aim for high code coverage
Include both positive and negative test cases
Add clear test names and docstrings""",
tools=["Read", "Write", "Bash"],
model="sonnet"
)
options = ClaudeAgentOptions(
agents={"tester": testing_agent}
)
async for msg in query(prompt="Write comprehensive tests", options=options):
print(msg)from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
# Agent using preset with custom addition
agent = AgentDefinition(
description="Enhanced Claude Code agent",
prompt={
"type": "preset",
"preset": "claude_code",
"append": """
Additionally:
- Always explain your reasoning
- Ask clarifying questions when needed
- Suggest improvements proactively
"""
},
tools=None,
model="inherit"
)
options = ClaudeAgentOptions(
agents={"enhanced": agent}
)
async for msg in query(prompt="Help with this project", options=options):
print(msg)from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
# Load only project and local settings, not user settings
options = ClaudeAgentOptions(
setting_sources=["project", "local"], # Skip user settings
agents={
"team_agent": AgentDefinition(
description="Team-configured agent",
prompt="Follow team conventions and project standards",
tools=["Read", "Write"],
model="sonnet"
)
}
)
async for msg in query(prompt="Work on this project", options=options):
print(msg)from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
# Database expert
db_agent = AgentDefinition(
description="Database expert",
prompt="""You are a database expert specializing in SQL and optimization.
- Design efficient schemas
- Write optimized queries
- Review indexes and performance
- Suggest migrations""",
tools=["Read", "Write"],
model="opus"
)
# API designer
api_agent = AgentDefinition(
description="API design expert",
prompt="""You are an API design expert. Design RESTful APIs:
- Clear endpoint structure
- Proper HTTP methods
- Consistent naming
- Good error handling
- OpenAPI documentation""",
tools=["Read", "Write"],
model="sonnet"
)
# Frontend specialist
frontend_agent = AgentDefinition(
description="Frontend expert",
prompt="""You are a frontend expert. Build great UIs:
- Accessible components
- Responsive design
- Modern CSS/frameworks
- Performance optimization
- Cross-browser compatibility""",
tools=["Read", "Write", "Bash"],
model="sonnet"
)
options = ClaudeAgentOptions(
agents={
"database": db_agent,
"api": api_agent,
"frontend": frontend_agent
}
)
async for msg in query(
prompt="Design database, API, and frontend for user management",
options=options
):
print(msg)from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
# Define agents for different phases
agents = {
"planner": AgentDefinition(
description="High-level planner",
prompt="Create detailed plans. Don't implement, just plan.",
tools=["Read"],
model="opus"
),
"executor": AgentDefinition(
description="Implementation executor",
prompt="Implement according to plan. Focus on correct implementation.",
tools=["Read", "Write", "Bash"],
model="sonnet"
)
}
options = ClaudeAgentOptions(agents=agents)
# Phase 1: Planning
async for msg in query(prompt="Plan the implementation", options=options):
print(msg)
# Phase 2: Execution
async for msg in query(prompt="Execute the plan", options=options):
print(msg)docs