AgentSkillsCN

claude-agent-sdk

使用 Claude Agent SDK(TypeScript 与 Python)构建生产级应用。适用于编写使用 @anthropic-ai/claude-agent-sdk 或 claude-agent-sdk 包的代码,创建带有 query()、ClaudeSDKClient、自定义 MCP 工具、子代理、会话管理、权限控制、钩子、插件、结构化输出,或成本追踪功能的代理时使用。也适用于托管/部署基于 SDK 的代理。

SKILL.md
--- frontmatter
name: claude-agent-sdk
description: Build production applications with Claude Agent SDK (TypeScript and Python). Use when writing code that uses @anthropic-ai/claude-agent-sdk or claude-agent-sdk packages, creating agents with query(), ClaudeSDKClient, custom MCP tools, subagents, session management, permissions, hooks, plugins, structured outputs, or cost tracking. Also use for hosting/deploying SDK-based agents.

Claude Agent SDK

Build production applications that leverage Claude's agentic coding capabilities.

Quick Start

TypeScript:

typescript
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Analyze this codebase",
  options: {
    maxTurns: 10,
    allowedTools: ["Read", "Grep", "Glob"]
  }
})) {
  if (message.type === "result" && message.subtype === "success") {
    console.log(message.result);
  }
}

Python:

python
from claude_agent_sdk import query, ClaudeAgentOptions

async for message in query(
    prompt="Analyze this codebase",
    options=ClaudeAgentOptions(
        max_turns=10,
        allowed_tools=["Read", "Grep", "Glob"]
    )
):
    if message.type == "result":
        print(message.result)

Reference Documentation

TopicDescription
overview.mdInstallation, authentication, core concepts
python-api.mdPython SDK complete API reference
typescript-api.mdTypeScript SDK complete API reference
custom-tools.mdCreating custom MCP tools
mcp.mdModel Context Protocol integration
permissions.mdPermission modes and canUseTool
hosting.mdProduction deployment patterns
sessions.mdSession management and resumption
subagents.mdCreating specialized subagents
streaming.mdStreaming vs single message input
structured-output.mdJSON schema validated outputs
costs.mdToken usage and cost tracking
skills.mdAgent Skills in SDK
plugins.mdLoading custom plugins
slash-commands.mdCustom slash commands
system-prompt.mdModifying system prompts
todos.mdTodo list tracking

Common Patterns

Basic Query

typescript
for await (const message of query({
  prompt: "Your task",
  options: { maxTurns: 5, model: "claude-sonnet-4-5" }
})) {
  console.log(message);
}

With Custom Tools

typescript
import { tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";

const server = createSdkMcpServer({
  name: "my-tools",
  version: "1.0.0",
  tools: [
    tool("get_data", "Fetch data", { id: z.string() }, async (args) => ({
      content: [{ type: "text", text: `Data for ${args.id}` }]
    }))
  ]
});

// Use with streaming input
async function* messages() {
  yield { type: "user", message: { role: "user", content: "Get data for user-123" } };
}

for await (const msg of query({
  prompt: messages(),
  options: {
    mcpServers: { "my-tools": server },
    allowedTools: ["mcp__my-tools__get_data"]
  }
})) {
  console.log(msg);
}

With Subagents

typescript
const result = query({
  prompt: "Review this code",
  options: {
    agents: {
      'reviewer': {
        description: 'Code review specialist',
        prompt: 'You are a code reviewer...',
        tools: ['Read', 'Grep'],
        model: 'sonnet'
      }
    }
  }
});

With Structured Output

typescript
for await (const message of query({
  prompt: "Extract user info",
  options: {
    outputFormat: {
      type: 'json_schema',
      schema: {
        type: 'object',
        properties: {
          name: { type: 'string' },
          email: { type: 'string' }
        },
        required: ['name', 'email']
      }
    }
  }
})) {
  if (message.structured_output) {
    console.log(message.structured_output);
  }
}

Session Management

typescript
// Get session ID
let sessionId: string;
for await (const msg of query({ prompt: "Hello" })) {
  if (msg.type === 'system' && msg.subtype === 'init') {
    sessionId = msg.session_id;
  }
}

// Resume later
for await (const msg of query({
  prompt: "Continue",
  options: { resume: sessionId }
})) {
  console.log(msg);
}

Permission Control

typescript
const result = query({
  prompt: "Make changes",
  options: {
    permissionMode: 'acceptEdits',  // Auto-accept file edits
    canUseTool: async (toolName, input) => {
      if (toolName === "Bash" && input.command?.includes("rm")) {
        return { behavior: "deny", message: "Deletion not allowed" };
      }
      return { behavior: "allow", updatedInput: input };
    }
  }
});

Key Options

OptionDescription
maxTurnsMaximum conversation turns
allowedToolsExplicitly allowed tools
disallowedToolsExplicitly blocked tools
permissionModedefault, acceptEdits, bypassPermissions
modelClaude model to use
mcpServersMCP server configurations
agentsSubagent definitions
outputFormatStructured output schema
resumeSession ID to resume
systemPromptCustom or preset system prompt
hooksEvent hook callbacks
pluginsPlugin configurations
settingSourcesLoad settings from user, project, local

Message Types

  • system (subtype: init) - Session started, lists tools and commands
  • assistant - Claude's response with content blocks
  • result (subtype: success, error_max_turns, error_during_execution) - Final result
  • user - User messages (tool results)