Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

claude-agent-sdk

БесплатноБез исполняемых скриптовНе проверен

Use when working with Anthropic Claude Agent SDK. Provides architecture guidance, implementation patterns, best practices, and common pitfalls.

sammcjот 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:

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:

  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

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 execution
  • PostToolUse → Process/log/modify tool results
  • Stop → 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 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:

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
Полный SKILL.md на GitHub

Установить 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), без исполняемых скриптов.

Похожие скиллы

Сравнить claude-agent-sdk с