AgentStack
SKILL verified MIT Self-run

Agent Sdk Builder

skill-acaprino-claude-code-daodan-agent-sdk-builder · by acaprino

>

No reviews yet
0 installs
17 views
0.0% view→install

Install

$ agentstack add skill-acaprino-claude-code-daodan-agent-sdk-builder

✓ scanned · ✓ verified — works with Claude Code, Cursor, and more.

Security review

✓ Passed

No issues found. Passed automated security review. · v0.1.0 How review works →

  • Prompt-injection patterns
  • Secret / credential exfiltration
  • Dangerous shell & filesystem operations
  • Untrusted network calls
  • Known-malicious package signatures

What it can access

  • Network access No
  • Filesystem access No
  • Shell / process execution No
  • Environment & secrets Used
  • Dynamic code execution No

From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.

Are you the author of Agent Sdk Builder? Claim this listing to set pricing, connect Stripe payouts, and keep 70% of every sale.
Sign up to claim

About

Claude Agent SDK

The Claude Agent SDK lets you run Claude Code programmatically -- build AI agents that read files, write code, execute commands, search the web, and orchestrate subagents, all from your application code.

Key distinction: The Agent SDK (claude-agent-sdk) runs the full Claude Code agent loop with built-in tools. The Anthropic Client SDK (anthropic) is for raw API calls. Use the Agent SDK when you need autonomous tool-using agents.

Quick Reference

| | TypeScript | Python | |---|---|---| | Package | @anthropic-ai/claude-agent-sdk | claude-agent-sdk | | Install | npm install @anthropic-ai/claude-agent-sdk | pip install claude-agent-sdk | | Auth | ANTHROPIC_API_KEY env var | ANTHROPIC_API_KEY env var | | Core function | query() | query() | | GitHub | anthropics/claude-agent-sdk-typescript | anthropics/claude-agent-sdk-python |

The CLI package @anthropic-ai/claude-code is bundled inside the SDK -- no separate install needed.


1. Installation & Auth

# TypeScript
npm install @anthropic-ai/claude-agent-sdk

# Python
pip install claude-agent-sdk
# or with uv
uv add claude-agent-sdk

Authentication via environment variable:

export ANTHROPIC_API_KEY=sk-ant-...

Alternative providers:

  • Amazon Bedrock: CLAUDE_CODE_USE_BEDROCK=1 + AWS credentials
  • Google Vertex AI: CLAUDE_CODE_USE_VERTEX=1 + GCP credentials
  • Microsoft Azure: CLAUDE_CODE_USE_FOUNDRY=1 + Azure credentials

2. Core API -- query()

Both SDKs expose query() as the primary entry point. It returns an async iterator streaming SDKMessage objects. Claude handles the entire tool loop autonomously -- you do NOT implement tool execution.

TypeScript

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

for await (const message of query({
  prompt: "Find and fix the bug in auth.py",
  options: {
    allowedTools: ["Read", "Edit", "Bash"],
    maxTurns: 10,
  },
})) {
  if (message.type === "assistant" && message.content) {
    for (const block of message.content) {
      if (block.type === "text") process.stdout.write(block.text);
    }
  }
  if ("result" in message) {
    console.log("\nFinal:", message.result);
    console.log("Cost:", message.total_cost_usd);
  }
}

Python

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    options = ClaudeAgentOptions(
        allowed_tools=["Read", "Edit", "Bash"],
        max_turns=10,
    )
    async for message in query(prompt="Find and fix the bug in auth.py", options=options):
        if hasattr(message, "result"):
            print(f"Final: {message.result}")
            print(f"Cost: ${message.total_cost_usd:.4f}")

asyncio.run(main())

3. Configuration Options

Full Options Reference

| Option (TS / Py) | Type | Description | |---|---|---| | allowedTools / allowed_tools | string[] | Tools to auto-approve without user confirmation | | disallowedTools / disallowed_tools | string[] | Tools to always deny | | permissionMode / permission_mode | string | Permission strategy (see Permissions section) | | systemPrompt / system_prompt | string | Custom system prompt or "claude_code" for default | | model | string | Model ID (e.g., "claude-fable-5", "claude-opus-4-8", "claude-sonnet-4-6") -- short aliases resolve to the latest date-slugged release (e.g., "claude-haiku-4-5" resolves to "claude-haiku-4-5-20251001"); pin a full slug for reproducibility | | maxTurns / max_turns | number | Maximum agentic loop iterations | | maxBudgetUsd / max_budget_usd | number | Spending cap in USD | | effort | string | "low", "medium", "high", "max" | | cwd | string | Working directory for file operations | | mcpServers / mcp_servers | object | MCP server configurations | | hooks | object | Lifecycle hook callbacks | | agents | object | Subagent definitions | | resume | string | Session ID to resume | | continue / continue_conversation | boolean | Continue most recent session | | forkSession / fork_session | string | Fork from an existing session | | settingSources / setting_sources | string[] | Load settings from ["user", "project", "local"] | | plugins | string[] | Local plugin directory paths | | sandbox | object | Sandbox/isolation settings | | thinking | object | Extended thinking: "adaptive", {type: "enabled", budget: N}, "disabled" | | outputFormat / output_format | object | JSON schema for structured output | | env | object | Environment variables passed to agent | | canUseTool / can_use_tool | function | Runtime permission callback | | includePartialMessages / include_partial_messages | boolean | Enable token-level streaming | | spawnClaudeCodeProcess | function | Custom process spawner (VMs, containers, remote) | | agentProgressSummaries | boolean | Enable periodic AI-generated progress summaries for running subagents | | debug / debug | boolean | Enable programmatic debug logging | | debugFile / debug_file | string | File path for debug log output |

Example -- Full Configuration

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

for await (const msg of query({
  prompt: "Refactor the auth module to use JWT tokens",
  options: {
    model: "claude-sonnet-4-6",
    allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"],
    disallowedTools: ["WebSearch", "WebFetch"],
    permissionMode: "bypassPermissions",
    maxTurns: 25,
    maxBudgetUsd: 1.0,
    effort: "high",
    cwd: "/home/user/project",
    systemPrompt: "You are a senior backend engineer. Follow the project's coding standards.",
    thinking: "adaptive",
    env: { NODE_ENV: "development" },
  },
})) {
  // process messages
}

4. Built-in Tools

The agent has access to these tools by default:

| Tool | Purpose | |---|---| | Read | Read files from filesystem | | Write | Create new files | | Edit | Precise string replacements in existing files | | Bash | Execute shell commands | | Glob | Find files by pattern | | Grep | Search file contents with regex | | WebSearch | Search the web | | WebFetch | Fetch and parse web pages | | Agent | Spawn subagents (required for multi-agent) | | Skill | Invoke skills from plugins | | AskUserQuestion | Request user input | | TodoWrite | Manage task lists | | ToolSearch | Discover deferred tools |

Control which tools the agent can use:

// Only allow read-only operations
options: {
  allowedTools: ["Read", "Glob", "Grep"],
  disallowedTools: ["Bash", "Write", "Edit"],
}

5. Custom Tools via MCP

Create custom tools using the SDK's MCP server helpers. Tools are defined with schemas and handlers, then exposed as in-process MCP servers.

TypeScript

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

// Define tools
const getWeather = tool(
  "get_weather",
  "Get current weather for a city",
  { city: z.string(), units: z.enum(["celsius", "fahrenheit"]).default("celsius") },
  async ({ city, units }) => ({
    content: [{ type: "text", text: JSON.stringify({ city, temp: 22, units }) }],
  })
);

const searchDatabase = tool(
  "search_db",
  "Search the application database",
  { query: z.string(), limit: z.number().default(10) },
  async ({ query: q, limit }) => {
    const results = await db.search(q, limit);
    return { content: [{ type: "text", text: JSON.stringify(results) }] };
  }
);

// Create MCP server
const server = createSdkMcpServer({
  name: "app-tools",
  tools: [getWeather, searchDatabase],
});

// Use in query
for await (const msg of query({
  prompt: "What's the weather in Rome and find related travel posts?",
  options: {
    mcpServers: { app: server },
    allowedTools: ["mcp__app__get_weather", "mcp__app__search_db"],
  },
})) {
  // Custom tools are called automatically by the agent
}

Python

from claude_agent_sdk import tool, create_sdk_mcp_server, query, ClaudeAgentOptions

@tool("get_weather", "Get current weather for a city", {"city": str, "units": str})
async def get_weather(args):
    return {"content": [{"type": "text", "text": f"Weather in {args['city']}: 22C"}]}

@tool("search_db", "Search the database", {"query": str, "limit": int})
async def search_db(args):
    results = await db.search(args["query"], args["limit"])
    return {"content": [{"type": "text", "text": str(results)}]}

server = create_sdk_mcp_server(name="app-tools", tools=[get_weather, search_db])

options = ClaudeAgentOptions(
    mcp_servers={"app": server},
    allowed_tools=["mcp__app__get_weather", "mcp__app__search_db"],
)

async for msg in query(prompt="Weather in Rome?", options=options):
    pass

MCP Tool Naming Convention

Custom tools follow the pattern: mcp____

Example: server named "mytools" with tool "search" becomes mcp__mytools__search

External MCP Servers

Connect to external MCP servers via stdio or HTTP:

options: {
  mcpServers: {
    // stdio transport (local process)
    localServer: {
      command: "node",
      args: ["./mcp-server.js"],
    },
    // HTTP/SSE transport (remote)
    remoteServer: {
      url: "https://mcp.example.com/sse",
      headers: { Authorization: "Bearer token" },
    },
  },
}

6. Subagents -- Multi-Agent Orchestration

Subagents let you define specialized agents that the main agent can spawn for parallel or delegated work.

Defining Subagents

for await (const msg of query({
  prompt: "Review the codebase for quality and security issues",
  options: {
    allowedTools: ["Read", "Grep", "Glob", "Agent"],  // Agent tool required
    agents: {
      "security-reviewer": {
        description: "Security expert. Use for vulnerability scanning, auth review, injection detection.",
        prompt: "You are a security auditor. Find vulnerabilities, auth issues, and injection vectors.",
        tools: ["Read", "Glob", "Grep"],
        model: "opus",
      },
      "code-quality": {
        description: "Code quality reviewer. Use for style, patterns, complexity, dead code.",
        prompt: "Review code quality: naming, complexity, patterns, duplication.",
        tools: ["Read", "Glob", "Grep"],
        model: "sonnet",
      },
      "test-runner": {
        description: "Runs tests and reports results.",
        prompt: "Execute test suites and analyze failures.",
        tools: ["Bash", "Read", "Grep"],
        model: "haiku",
      },
    },
  },
})) {
  // Claude automatically decides when to spawn subagents
  // based on their descriptions
}

Subagent Properties

| Property | Type | Description | |---|---|---| | description | string | Required. When to use this agent (Claude decides based on this) | | prompt | string | Required. System prompt for the subagent | | tools | string[] | Restricted tool set | | model | string | "sonnet", "opus", "haiku", or "inherit" | | disallowedTools | string[] | Tools to block (TS only) | | mcpServers | object | MCP servers available to subagent | | skills | string[] | Skills the subagent can invoke | | memory | object | Memory configuration for the subagent | | maxTurns | number | Turn limit for this subagent (TS only) |

Subagent Behavior

  • Context isolation -- each subagent gets a fresh conversation; only its final message returns to the parent
  • Parallel execution -- multiple subagents run concurrently when spawned together
  • No nesting -- subagents cannot spawn their own subagents
  • Resumable -- subagents can be resumed by ID from tool results
  • Cost isolated -- each subagent's token usage is tracked separately
  • Progress summaries -- enable agentProgressSummaries: true to receive periodic AI-generated progress updates from running subagents

7. Session Management

Sessions persist conversation history to disk, enabling multi-turn workflows.

Resume a Session (TypeScript)

let sessionId: string | undefined;

// First query -- capture session ID
for await (const msg of query({
  prompt: "Read the authentication module",
  options: { allowedTools: ["Read", "Glob"] },
})) {
  if (msg.type === "system" && msg.subtype === "init") {
    sessionId = msg.session_id;
  }
}

// Second query -- resume with full context
for await (const msg of query({
  prompt: "Now refactor it to use JWT",
  options: { resume: sessionId },
})) {
  if ("result" in msg) console.log(msg.result);
}

Continue Most Recent Session

// TypeScript
for await (const msg of query({
  prompt: "Continue where we left off",
  options: { continue: true },
})) { /* ... */ }
# Python
options = ClaudeAgentOptions(continue_conversation=True)
async for msg in query(prompt="Continue where we left off", options=options):
    pass

Session Client (Python)

Python provides ClaudeSDKClient for managed multi-turn conversations:

from claude_agent_sdk import ClaudeSDKClient

async with ClaudeSDKClient() as client:
    # First turn
    await client.query("What's the project structure?")
    async for msg in client.receive_response():
        pass  # process

    # Second turn -- context retained automatically
    await client.query("Now find all API endpoints")
    async for msg in client.receive_response():
        pass  # process

    # Interrupt current generation
    await client.interrupt()

List, Inspect, and Manage Sessions

import {
  listSessions, getSessionInfo, getSessionMessages,
  forkSession, tagSession, renameSession,
} from "@anthropic-ai/claude-agent-sdk";

// List sessions
const sessions = await listSessions({ dir: "/path/to/project", limit: 10 });
for (const session of sessions) {
  console.log(session.sessionId, session.createdAt, session.tag);
}

// Single-session metadata lookup
const info = await getSessionInfo(sessionId);
console.log(info.tag, info.createdAt);

// Read conversation history (includes parallel tool results)
const messages = await getSessionMessages(sessionId);

// Branch a conversation from a specific point
const forked = await forkSession(sessionId);

// Organize sessions with tags and renames
await tagSession(sessionId, "auth-refactor");
await renameSession(sessionId, "auth-refactor-v2");
from claude_agent_sdk import (
    list_sessions, get_session_info, get_session_messages,
    fork_session, tag_session, rename_session,
)

sessions = await list_sessions(dir="/path/to/project", limit=10)
for session in sessions:
    messages = await get_session_messages(session.session_id)

info = await get_session_info(session_id)
await tag_session(session_id, "auth-refactor")
await rename_session(session_id, "auth-refactor-v2")

Session State Events

Session state change events are opt-in as of v0.2.83. Enable with environment variable:

export CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS=1

Exit Reasons

The ExitReason type includes: "end_turn", "max_turns", "budget", "interrupt", "resume".


8. Introspection Utilities

import { supportedAgents, getSettings } from "@anthropic-ai/claude-agent-sdk";

// Discover available subagents
const agents = await supportedAgents();

// Inspect runtime-resolved settings (includes applied model and effort)
const settings = await getSettings();
console.log(settings.applied.model, settings.applied.effort);

9. Permissions

Control what the agent can do at runtime.

Permission Modes

| Mode | Behavior | |---|---| | "default" | Unmatched tools trigger canUseTool callback or user prompt | | "dontAsk" | Deny anything not pre-approved (TypeScript only) | | "acceptEdits" | Auto-accept file mutations (Edit, Write, m

Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

Install and usage instructions live in the source repository linked above.

Reviews

No reviews yet — be the first.

Versions

  • v0.1.0 Imported from the upstream source.