claude-agent-sdk
Use when working with Anthropic Claude Agent SDK. Provides architecture guidance, implementation patterns, best practices, and common pitfalls.
What this skill does
# Claude Agent SDK
## Overview
The Claude Agent SDK enables building autonomous AI agents with Claude through a feedback loop architecture. Available for Python (3.10+) and TypeScript (Node 18+).
**Repository:**
- Python: https://github.com/anthropics/claude-agent-sdk-python
- TypeScript: https://github.com/anthropics/claude-agent-sdk-typescript
**Documentation:** https://platform.claude.com/docs/en/agent-sdk/overview
## Installation
```bash
# Python
pip install claude-agent-sdk
# TypeScript
npm install @anthropic-ai/agent-sdk
```
## Core Architecture: Feedback Loop Pattern
Every agent follows this cycle:
1. **Gather Context** → filesystem navigation, subagents, tools
2. **Take Action** → tools, bash, code generation, MCP
3. **Verify Work** → rules-based, visual, LLM-as-judge
4. **Repeat** → iterate until completion
This pattern applies whether you're building a simple script or a complex multi-agent system.
## Execution Mechanisms (Priority Order)
Choose mechanisms based on task requirements:
1. **Custom Tools** → Primary workflows (appear prominently in context)
2. **Bash** → Flexible one-off operations
3. **Code Generation** → Complex, reusable outputs (prefer TypeScript for linting feedback)
4. **MCP** → Pre-built external integrations (Slack, GitHub, databases)
**Rule:** Use tools for repeatable operations, bash for exploration, code generation when you need structured output that can be validated.
## Quick Start Patterns
### Python: Basic Query
```python
from claude_agent_sdk import query
result = await query(
model="claude-sonnet-4-5",
system_prompt="You are a helpful coding assistant.",
user_message="List files in current directory",
working_dir=".",
)
print(result.final_message)
```
### TypeScript: Session Management
```typescript
import { ClaudeSdkClient } from '@anthropic-ai/agent-sdk';
const client = new ClaudeSdkClient({ apiKey: process.env.ANTHROPIC_API_KEY });
const result = await client.query({
model: 'claude-sonnet-4-5',
systemPrompt: 'You are a helpful coding assistant.',
userMessage: 'List files in current directory',
workingDir: '.',
});
console.log(result.finalMessage);
```
## Key Components
### 1. Custom Tools (SDK MCP Servers)
In-process tools with no subprocess overhead. Primary building block for agents.
**Python:**
```python
from claude_agent_sdk.mcp import tool, create_sdk_mcp_server
@tool(
name="calculator",
description="Perform calculations",
input_schema={"expression": str}
)
async def calculator(args):
result = eval(args["expression"]) # Use safe eval in production
return {"content": [{"type": "text", "text": str(result)}]}
server = create_sdk_mcp_server(name="math", tools=[calculator])
```
**TypeScript:**
```typescript
import { createSdkMcpServer, tool } from '@anthropic-ai/agent-sdk';
import { z } from 'zod';
const calculator = tool({
name: 'calculator',
description: 'Perform calculations',
inputSchema: z.object({ expression: z.string() }),
async execute({ expression }) {
const result = eval(expression); // Use safe eval in production
return { content: [{ type: 'text', text: String(result) }] };
},
});
const server = createSdkMcpServer({ name: 'math', tools: [calculator] });
```
**Benefits over external MCP:** Better performance, easier debugging, shared memory space, no IPC overhead.
### 2. Hooks (Lifecycle Callbacks)
Intercept and modify agent behaviour at specific points.
**Available hooks:**
- `PreToolUse` → Validate/modify/deny tool calls before execution
- `PostToolUse` → Process/log/modify tool results
- `Stop` → Handle completion events
**Python validation example:**
```python
async def validate_command(input_data, tool_use_id, context):
if "rm -rf" in input_data["tool_input"].get("command", ""):
return {
"hookSpecificOutput": {
"permissionDecision": "deny",
"permissionDecisionReason": "Dangerous command blocked"
}
}
```
**TypeScript logging example:**
```typescript
const loggingHook = {
matcher: (input) => input.toolName === 'bash',
async handler(input, toolUseId, context) {
console.log(`Executing: ${input.toolInput.command}`);
}
};
```
### 3. Permission System
Four modes with progressively less restriction:
- `default` → Prompt for each tool use
- `plan` → Agent can read/explore freely, prompts for modifications
- `acceptEdits` → Auto-approve file edits, prompt for bash/destructive ops
- `bypassPermissions` → Fully autonomous (use carefully)
**Dynamic control with `canUseTool`:**
```python
async def permission_callback(tool_name, tool_input, context):
if tool_name == "bash" and "git push" in tool_input.get("command", ""):
return False # Deny
return True # Allow
```
### 4. Subagents
Isolated agents with separate context windows and specialised capabilities.
**When to use:**
- Parallel processing of independent tasks
- Context isolation (prevent one task from bloating main context)
- Specialised agents with different tools/models
**Python:**
```python
from claude_agent_sdk import ClaudeAgentOptions
options = ClaudeAgentOptions(
subagent_definitions={
"researcher": {
"tools": ["read", "grep", "glob"],
"model": "claude-haiku-4",
"description": "Fast research agent"
}
}
)
```
**TypeScript:**
```typescript
const options = {
subagentDefinitions: {
researcher: {
tools: ['read', 'grep', 'glob'],
model: 'claude-haiku-4',
description: 'Fast research agent'
}
}
};
```
### 5. Context Management
**Agentic Search (Preferred):**
Use bash + filesystem navigation (grep, ls, tail) before reaching for semantic search. Simpler and more reliable.
**Automatic Compaction:**
SDK automatically summarises messages when approaching token limits. Transparent and automatic.
**Folder Structure as Context Engineering:**
Organise files intentionally—directory structure is visible to the agent and influences its understanding.
## Verification Patterns
### Rules-Based (Preferred)
Explicit validation enables self-correction:
```python
# In PostToolUse hook
if tool_name == "write":
# Run linter on generated file
lint_result = run_linter(tool_output)
if lint_result.has_errors:
return {"continue": True} # Let agent fix errors
```
### Visual Feedback
For UI tasks, screenshot and re-evaluate:
```python
@tool(name="check_ui", description="Verify UI matches requirements")
async def check_ui(args):
screenshot = take_screenshot(args["url"])
# Return screenshot to agent for evaluation
return {"content": [{"type": "image", "source": screenshot}]}
```
### LLM-as-Judge
Only for fuzzy criteria where rules don't work (higher latency):
```python
judge_result = await secondary_model.evaluate(
criteria="Does output match tone guidelines?",
output=agent_output
)
```
## Common Pitfalls & Solutions
### 1. System Prompt Not Loading
**Symptom:** CLAUDE.md ignored, custom prompts not applied
**Solution:** Set `setting_sources=["project"]` or `["user", "project"]`
```python
# Python
options = ClaudeAgentOptions(setting_sources=["project"])
# TypeScript
const options = { settingSources: ['project'] };
```
### 2. Tool Not Available
**Symptom:** "Tool not found" errors
**Solution:** Check MCP tool naming: `mcp__{server_name}__{tool_name}`
### 3. Permission Denied
**Symptom:** Agent can't access directories
**Solution:** Add directories explicitly:
```python
options = ClaudeAgentOptions(add_dirs=["/path/to/data"])
```
### 4. Python Keyword Conflicts
**Symptom:** Syntax errors with `async` or `continue` parameters
**Solution:** Use `async_` and `continue_` (SDK auto-converts)
```python
# Use async_ not async
hook_result = {"async_": True, "continue_": False}
```
### 5. Context Overflow
**Symptom:** Token limit errors
**Solution:** Use subagents for isolation or let automatic compaction handle it
### 6. Tool ExeRelated 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.