claude-agent-sdk
БесплатноБез исполняемых скриптовНе проверенUse when working with Anthropic Claude Agent SDK. Provides architecture guidance, implementation patterns, best practices, and common pitfalls.
от sammcj★ 175 звёзд на GitHubОб этом скилле
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
# Python
pip install claude-agent-sdk
# TypeScript
npm install @anthropic-ai/agent-sdk
Core Architecture: Feedback Loop Pattern
Every agent follows this cycle:
- Gather Context → filesystem navigation, subagents, tools
- Take Action → tools, bash, code generation, MCP
- Verify Work → rules-based, visual, LLM-as-judge
- 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:
- Custom Tools → Primary workflows (appear prominently in context)
- Bash → Flexible one-off operations
- Code Generation → Complex, reusable outputs (prefer TypeScript for linting feedback)
- 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
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
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:
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:
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 executionPostToolUse→ Process/log/modify tool resultsStop→ Handle completion events
Python validation example:
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:
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 useplan→ Agent can read/explore freely, prompts for modificationsacceptEdits→ Auto-approve file edits, prompt for bash/destructive opsbypassPermissions→ Fully autonomous (use carefully)
Dynamic control with canUseTool:
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 fro
Установить claude-agent-sdk в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл claude-agent-sdk?
Use when working with Anthropic Claude Agent SDK. Provides architecture guidance, implementation patterns, best practices, and common pitfalls.
Как установить скилл claude-agent-sdk?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл claude-agent-sdk запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic