claude-agent-sdk
Comprehensive knowledge of Claude Agent SDK architecture, tools, hooks, skills, and production patterns. Auto-activates for agent building, SDK integration, tool design, and MCP server tasks.
What this skill does
# Claude Agent SDK - Comprehensive Skill
## Overview
The **Claude Agent SDK** is Anthropic's official framework for building production-ready AI agents with Claude. It provides a high-level abstraction over the Messages API, handling the agent loop, tool orchestration, context management, and extended-thinking patterns automatically.
### When to Use the Agent SDK
**Use the Agent SDK when:**
- Building autonomous agents that need to use tools iteratively
- Implementing agentic workflows with verification and iteration
- Creating subagent hierarchies for complex task decomposition
- Integrating MCP (Model Context Protocol) servers for standardized tools
- Need production patterns like hooks, permissions, and context management
**Don't use when:**
- Simple single-turn API calls suffice (use Messages API directly)
- No tool use required (standard chat)
- Custom agent loop logic needed (SDK loop is opinionated)
### Language Support
- **Python**: `claude-agents` package (recommended for most use cases)
- **TypeScript**: `@anthropics/agent-sdk` package (Node.js environments)
Both implementations share the same core concepts and API patterns.
## Quick Start
### Installation
**Python:**
```bash
pip install claude-agents
```
**TypeScript:**
```bash
npm install @anthropics/agent-sdk
```
### Authentication
Set your API key as an environment variable:
```bash
export ANTHROPIC_API_KEY="your-api-key-here" # pragma: allowlist secret
```
Or pass it explicitly in code:
```python
from claude_agents import Agent
agent = Agent(api_key="your-api-key-here")
```
### Basic Agent Creation
**Python Example:**
```python
from claude_agents import Agent
# Create agent with default settings
agent = Agent(
model="claude-sonnet-4-5-20250929",
system="You are a helpful assistant focused on accuracy."
)
# Run simple task
result = agent.run("What is 2+2?")
print(result.response)
```
**TypeScript Example:**
```typescript
import { Agent } from "@anthropics/agent-sdk";
const agent = new Agent({
model: "claude-sonnet-4-5-20250929",
system: "You are a helpful assistant focused on accuracy.",
});
const result = await agent.run("What is 2+2?");
console.log(result.response);
```
### First Tool Example
Tools extend agent capabilities with external functions:
**Python:**
```python
from claude_agents import Agent
from claude_agents.tools import Tool
# Define custom tool
def get_weather(location: str) -> dict:
"""Get weather for a location."""
return {"location": location, "temp": 72, "condition": "sunny"}
weather_tool = Tool(
name="get_weather",
description="Get current weather for a location",
input_schema={
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
},
function=get_weather
)
# Agent with custom tool
agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[weather_tool]
)
result = agent.run("What's the weather in San Francisco?")
print(result.response)
```
## Core Concepts Reference
### The Agent Loop
The SDK manages a complete agent loop automatically:
1. **Input Processing**: User message + system prompt + tools
2. **Model Invocation**: Claude generates response (text or tool calls)
3. **Tool Execution**: SDK executes requested tools, handles results
4. **Iteration**: Results fed back to model, continues until completion
5. **Output**: Final response with full conversation history
**Key Properties:**
- Automatic iteration until task completion or max turns
- Built-in error handling and retry logic
- Context management with automatic compaction options
- Token budget tracking and optimization
### Context Management
The SDK manages conversation context automatically:
**Context Components:**
- System prompt (persistent instructions)
- Conversation history (user messages + assistant responses)
- Tool definitions (available capabilities)
- Tool results (execution outputs)
**Subagents for Context Isolation:**
```python
# Spawn subagent with isolated context
with agent.subagent(
system="You are a code reviewer focused on security.",
tools=[security_scan_tool]
) as reviewer:
review = reviewer.run("Review this code for vulnerabilities: ...")
# Subagent context doesn't pollute parent
```
**Context Compaction:**
When approaching token limits, the SDK can automatically summarize earlier conversation turns while preserving critical information.
### Tools System
Tools are the agent's interface to external capabilities.
**Built-in Tools:**
- `bash`: Execute shell commands
- `read_file`: Read file contents
- `write_file`: Write data to files
- `edit_file`: Modify existing files
- `glob`: File pattern matching
- `grep`: Content search
**Custom Tool Schema:**
```python
Tool(
name="tool_name", # Unique identifier
description="What it does", # Clear capability description
input_schema={ # JSON Schema for parameters
"type": "object",
"properties": {...},
"required": [...]
},
function=callable # Python function or async function
)
```
**MCP Integration:**
The SDK can use Model Context Protocol (MCP) servers as tool providers:
```python
from claude_agents import Agent
from claude_agents.mcp import MCPClient
# Connect to MCP server
mcp_client = MCPClient("npx", ["-y", "@modelcontextprotocol/server-filesystem"])
agent = Agent(
model="claude-sonnet-4-5-20250929",
mcp_clients=[mcp_client]
)
```
### Permissions System
Control which tools agents can access:
**Allowed Tools (Whitelist):**
```python
agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[tool1, tool2, tool3, tool4],
allowed_tools=["tool1", "tool2"] # Only these can be used
)
```
**Disallowed Tools (Blacklist):**
```python
agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[tool1, tool2, tool3],
disallowed_tools=["tool3"] # All except tool3
)
```
**Permission Modes:**
- `"strict"`: Agent MUST get permission before tool use (via hooks)
- `"permissive"`: Agent can use allowed tools freely (default)
### Hooks System
Hooks provide lifecycle event interception for observability, validation, and control.
**Available Hooks:**
- `PreToolUseHook`: Before tool execution (validation, logging, blocking)
- `PostToolUseHook`: After tool execution (logging, result modification)
- `PreSubagentStartHook`: Before subagent spawns (context setup)
- `PostSubagentStopHook`: After subagent completes (result processing)
**Basic Hook Example:**
```python
from claude_agents.hooks import PreToolUseHook
class LoggingHook(PreToolUseHook):
async def execute(self, context):
print(f"Tool: {context.tool_name}")
print(f"Args: {context.tool_input}")
return context # Allow execution
agent = Agent(
model="claude-sonnet-4-5-20250929",
hooks=[LoggingHook()]
)
```
**Blocking Tool Use:**
```python
class ValidationHook(PreToolUseHook):
async def execute(self, context):
if context.tool_name == "bash" and "rm -rf" in context.tool_input.get("command", ""):
raise PermissionError("Destructive command blocked")
return context
```
## Common Patterns
### File Operations
```python
from claude_agents import Agent
agent = Agent(
model="claude-sonnet-4-5-20250929",
allowed_tools=["read_file", "write_file", "glob"]
)
result = agent.run(
"Read all Python files in ./src and create a summary in summary.md"
)
```
### Code Execution
```python
agent = Agent(
model="claude-sonnet-4-5-20250929",
allowed_tools=["bash"]
)
result = agent.run(
"Run the test suite and analyze any failures"
)
```
### Agentic Search (Gather-Act Pattern)
```python
# Agent automatically gathers information iteratively
search_agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[web_search_tool, read_url_tool]
)
result = search_agent.run(
Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.