agent-sdk-python
Implements production-ready AI agents using the official Python SDK for autonomous workflows. Use when implementing agent workflows, SDK integration, one-shot queries, interactive conversations, custom MCP tools, permission control, CLAUDE.md context loading, error handling, hooks, or agent delegation. Works with .py files and agent architectures. Trigger terms: "Agent SDK", "query()", "ClaudeSDKClient", "@tool decorator", "setting_sources", "agent permissions", "SDK hooks".
What this skill does
# Agent SDK Integration
## Purpose
Build production-ready AI agents using the **Agent SDK** for Python. This skill provides hands-on workflows for implementing agent features including simple queries, interactive conversations, custom MCP tools, permission control, context loading, and error handling.
## Quick Start
**Simple one-shot query:**
```python
from claude_agent_sdk import query
async for message in query(prompt="What is the capital of France?"):
print(message)
```
**Interactive conversation:**
```python
from claude_agent_sdk import ClaudeSDKClient
async with ClaudeSDKClient() as client:
await client.query("Hello!")
async for msg in client.receive_response():
print(msg)
```
## When to Use This Skill
**Explicit Triggers:**
- "build agent with SDK"
- "use query() function"
- "create ClaudeSDKClient"
- "implement agent workflows"
- "add custom MCP tools"
- "configure agent permissions"
- "load CLAUDE.md context"
- "implement agent hooks"
**Implicit Triggers:**
- Implementing autonomous agent behavior
- Creating interactive chat agents
- Building batch processing workflows
- Adding custom tools to agents
- Managing agent permissions
- Integrating project context into agents
**Debugging Scenarios:**
- Agent not connecting to CLI
- Tools not available to agent
- Permission denied errors
- Context not loading correctly
- Hooks not executing
## Instructions
### Step 1: Choose the Right API Mode
**Use `query()` for:**
- Simple one-shot questions
- Batch processing of independent tasks
- Stateless operations
- When all inputs are known upfront
- CI/CD automation scripts
**Use `ClaudeSDKClient` for:**
- Interactive conversations with follow-ups
- Chat applications or REPL interfaces
- When you need to send messages based on responses
- Long-running sessions with state management
- Interrupt capabilities
### Step 2: Build Simple Agent (query() Function)
**Basic implementation:**
```python
from claude_agent_sdk import query, ClaudeAgentOptions
async for message in query(
prompt="Analyze this code for security issues",
options=ClaudeAgentOptions(
system_prompt="You are a security expert",
cwd="/path/to/project",
permission_mode="default"
)
):
if hasattr(message, 'content'):
print(message.content)
```
**Key configuration options:**
- `system_prompt`: Define agent expertise
- `cwd`: Set working directory
- `permission_mode`: Control tool execution ("default", "acceptEdits", "bypassPermissions")
- `model`: Choose model ("claude-sonnet-4", "claude-opus-4")
### Step 3: Build Interactive Agent (ClaudeSDKClient)
**Full conversation example:**
```python
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
async with ClaudeSDKClient(
options=ClaudeAgentOptions(
system_prompt="You are a helpful coding assistant",
permission_mode="acceptEdits"
)
) as client:
# Send initial message
await client.query("Help me write a Python web server")
# Process response
async for msg in client.receive_response():
print(msg)
# Follow-up question
await client.query("Can you add error handling?")
async for msg in client.receive_response():
print(msg)
```
See [references/implementation-guide.md](./references/implementation-guide.md) for detailed patterns.
### Step 4: Create Custom MCP Tools
**Define tools with @tool decorator:**
```python
from claude_agent_sdk import tool, create_sdk_mcp_server
@tool("greet", "Greet a user by name", {"name": str})
async def greet(args):
return {
"content": [{"type": "text", "text": f"Hello, {args['name']}!"}]
}
# Create MCP server
calculator = create_sdk_mcp_server(
name="calculator",
version="1.0.0",
tools=[greet]
)
# Use with agent
options = ClaudeAgentOptions(
mcp_servers={"calc": calculator},
allowed_tools=["greet"]
)
```
See [references/implementation-guide.md](./references/implementation-guide.md) for error handling and advanced patterns.
### Step 5: Configure Permissions and Tool Access
**Fine-grained tool restrictions:**
```python
options = ClaudeAgentOptions(
# Allow only specific tools
allowed_tools=["Read", "Grep", "search_code"],
# Block dangerous tools
disallowed_tools=["Bash", "Write"],
# Permission mode
permission_mode="default"
)
```
**Dynamic permission callback:**
```python
from claude_agent_sdk import PermissionResultAllow, PermissionResultDeny
async def can_use_tool(tool_name, tool_input, context):
if tool_name in ["Read", "Grep", "Glob"]:
return PermissionResultAllow()
if tool_name == "Bash" and "rm" in str(tool_input):
return PermissionResultDeny(
message="Destructive bash commands are not allowed",
interrupt=True
)
return PermissionResultAllow()
options = ClaudeAgentOptions(can_use_tool=can_use_tool)
```
See [references/implementation-guide.md](./references/implementation-guide.md) for complete examples.
### Step 6: Load CLAUDE.md Context (setting_sources)
**Load project and user instructions:**
```python
options = ClaudeAgentOptions(
# Load CLAUDE.md files
setting_sources=["user", "project"],
# user: ~/.claude/CLAUDE.md (user-level instructions)
# project: ./CLAUDE.md or ./.claude/CLAUDE.md (project-level)
cwd="/path/to/project"
)
async for message in query(
prompt="Review this code following project standards",
options=options
):
print(message)
```
**When to use which source:**
- **"user"**: Personal preferences, global workflows
- **"project"**: Team standards, project architecture
- **"local"**: Machine-specific settings
- **Best practice**: Use `["user", "project"]` for most workflows
### Step 7: Implement Error Handling
**Try/catch with specific exceptions:**
```python
from claude_agent_sdk import (
ClaudeSDKError,
CLIConnectionError,
CLINotFoundError,
ProcessError
)
try:
async for message in query(prompt="Hello"):
print(message)
except CLINotFoundError:
print("Install CLI: npm install -g claude-code")
except CLIConnectionError as e:
print(f"Connection failed: {e}")
except ProcessError as e:
print(f"Process error (exit {e.exit_code}): {e.stderr}")
```
See [references/implementation-guide.md](./references/implementation-guide.md) for retry patterns.
### Step 8: Add Hooks for Event-Driven Automation
**PreToolUse hook:**
```python
from claude_agent_sdk import HookMatcher
async def log_tool_use(input_data, tool_use_id, context):
tool_name = input_data.get("tool", {}).get("name")
print(f"About to use tool: {tool_name}")
return {} # Empty = allow
options = ClaudeAgentOptions(
hooks={
"PreToolUse": [
HookMatcher(matcher="Bash|Write", hooks=[log_tool_use])
]
}
)
```
See [references/implementation-guide.md](./references/implementation-guide.md) for PostToolUse and blocking patterns.
### Step 9: Implement Agent Delegation
**Define custom agents:**
```python
from claude_agent_sdk import AgentDefinition
options = ClaudeAgentOptions(
agents={
"python-expert": AgentDefinition(
description="Python code expert",
prompt="Expert Python developer",
tools=["Read", "Write"],
model="opus"
)
}
)
async for message in query(
prompt="@python-expert Review this code",
options=options
):
print(message)
```
See [references/implementation-guide.md](./references/implementation-guide.md) for multi-agent patterns.
## Supporting Files
### References
- **[api-reference.md](./references/api-reference.md)** - Complete API documentation including all classes, functions, and types
- **[implementation-guide.md](./references/implementation-guide.md)** - Detailed patterns for all steps including production examples
### Scripts
- **[verify_sdk.py](./scripts/verify_sdk.py)** - Verify Agent SDK installation and configuration
- **[claudeRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.