# Claude Agent Sdk

> |

- **Type:** Skill
- **Install:** `agentstack add skill-jackspace-claudeskillz-claude-agent-sdk`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [jackspace](https://agentstack.voostack.com/s/jackspace)
- **Installs:** 0
- **Category:** [Cloud & Infrastructure](https://agentstack.voostack.com/c/cloud-infrastructure)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [jackspace](https://github.com/jackspace)
- **Source:** https://github.com/jackspace/ClaudeSkillz/tree/master/skills/claude-agent-sdk
- **Website:** http://claudeskillz.jackspace.com/

## Install

```sh
agentstack add skill-jackspace-claudeskillz-claude-agent-sdk
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Claude Agent SDK

**Status**: Production Ready
**Last Updated**: 2025-10-25
**Dependencies**: @anthropic-ai/claude-agent-sdk, zod
**Latest Versions**: @anthropic-ai/claude-agent-sdk@0.1.0+, zod@3.23.0+

---

## Quick Start (5 Minutes)

### 1. Install SDK

```bash
npm install @anthropic-ai/claude-agent-sdk zod
```

**Why these packages:**
- `@anthropic-ai/claude-agent-sdk` - Main Agent SDK
- `zod` - Type-safe schema validation for tools

### 2. Set API Key

```bash
export ANTHROPIC_API_KEY="sk-ant-..."
```

**CRITICAL:**
- API key required for all agent operations
- Never commit API keys to version control
- Use environment variables

### 3. Basic Query

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

const response = query({
  prompt: "Analyze the codebase and suggest improvements",
  options: {
    model: "claude-sonnet-4-5",
    workingDirectory: process.cwd(),
    allowedTools: ["Read", "Grep", "Glob"]
  }
});

for await (const message of response) {
  if (message.type === 'assistant') {
    console.log(message.content);
  }
}
```

---

## The Complete Claude Agent SDK Reference

## Table of Contents

1. [Core Query API](#core-query-api)
2. [Tool Integration](#tool-integration-built-in--custom)
3. [MCP Servers](#mcp-servers-model-context-protocol)
4. [Subagent Orchestration](#subagent-orchestration)
5. [Session Management](#session-management)
6. [Permission Control](#permission-control)
7. [Filesystem Settings](#filesystem-settings)
8. [Message Types & Streaming](#message-types--streaming)
9. [Error Handling](#error-handling)
10. [Known Issues](#known-issues-prevention)

---

## Core Query API

### The `query()` Function

The primary interface for interacting with Claude Code CLI programmatically.

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

const response = query({
  prompt: string | AsyncIterable,
  options?: Options
});

// Response is AsyncGenerator
for await (const message of response) {
  // Process streaming messages
}
```

### Basic Options

```typescript
const response = query({
  prompt: "Review this code for bugs",
  options: {
    model: "claude-sonnet-4-5",        // or "haiku", "opus"
    workingDirectory: "/path/to/project",
    systemPrompt: "You are a security-focused code reviewer.",
    allowedTools: ["Read", "Grep", "Glob"],
    disallowedTools: ["Write", "Edit", "Bash"],
    permissionMode: "default"           // or "acceptEdits", "bypassPermissions"
  }
});
```

### Model Selection

| Model | ID | Best For | Speed | Capability |
|-------|-----|----------|-------|------------|
| **Haiku** | `"haiku"` | Fast tasks, monitoring | Fastest | Basic |
| **Sonnet** | `"sonnet"` or `"claude-sonnet-4-5"` | Balanced | Medium | High |
| **Opus** | `"opus"` | Complex reasoning | Slowest | Highest |
| **Inherit** | `"inherit"` | Use parent model | - | - |

**Default**: `"sonnet"` if not specified

### System Prompts

```typescript
const response = query({
  prompt: "Implement user authentication",
  options: {
    systemPrompt: `You are an expert backend developer.

Follow these principles:
- Always use TypeScript with strict types
- Implement comprehensive error handling
- Add detailed logging for debugging
- Write unit tests for all functions
- Follow OWASP security guidelines`
  }
});
```

**CRITICAL:**
- System prompt sets agent behavior for entire session
- Should be clear and specific
- Can be 1-10k tokens (affects context window)

### Working Directory

```typescript
const response = query({
  prompt: "Refactor the user service",
  options: {
    workingDirectory: "/Users/dev/projects/my-app",
    // Agent operates within this directory
    // Relative paths resolved from here
  }
});
```

**Best Practices:**
- Use absolute paths for clarity
- Agent stays within this directory scope
- Critical for multi-project environments

---

## Tool Integration (Built-in + Custom)

### Built-in Tools

The SDK provides access to Claude Code's built-in tools:

| Tool | Description | Use Case |
|------|-------------|----------|
| `Read` | Read file contents | Code analysis |
| `Write` | Create new files | Generate code |
| `Edit` | Modify existing files | Refactoring |
| `Bash` | Execute shell commands | Run tests, git |
| `Grep` | Search file contents | Find patterns |
| `Glob` | Find files by pattern | File discovery |
| `WebSearch` | Search the web | Research |
| `WebFetch` | Fetch URL content | Documentation |
| `Task` | Delegate to subagent | Orchestration |

### Allowing/Disallowing Tools

```typescript
// Whitelist approach (recommended)
const response = query({
  prompt: "Analyze code but don't modify anything",
  options: {
    allowedTools: ["Read", "Grep", "Glob"]
    // ONLY these tools can be used
  }
});

// Blacklist approach
const response = query({
  prompt: "Review and fix issues",
  options: {
    disallowedTools: ["Bash"]
    // Everything except Bash allowed
  }
});

// Combination (allowedTools takes precedence)
const response = query({
  prompt: "Safe code review",
  options: {
    allowedTools: ["Read", "Grep", "Glob", "Edit"],
    disallowedTools: ["Edit"]  // Edit still blocked (allowedTools overridden)
  }
});
```

**CRITICAL:**
- `allowedTools` = whitelist (only these tools)
- `disallowedTools` = blacklist (everything except these)
- If both specified, `allowedTools` wins

### Custom Tool Execution Monitoring

```typescript
const response = query({
  prompt: "Implement feature X",
  options: {
    allowedTools: ["Read", "Write", "Edit", "Bash"]
  }
});

for await (const message of response) {
  if (message.type === 'tool_call') {
    console.log(`Tool requested: ${message.tool_name}`);
    console.log(`Input:`, message.input);
  } else if (message.type === 'tool_result') {
    console.log(`Tool ${message.tool_name} completed`);
  }
}
```

---

## MCP Servers (Model Context Protocol)

### Overview

MCP servers extend agent capabilities with custom tools. The SDK supports:
- **In-process servers** (`createSdkMcpServer`) - Run in same process
- **External servers** (stdio, HTTP, SSE) - Separate processes

### Creating In-Process MCP Servers

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

const weatherServer = createSdkMcpServer({
  name: "weather-service",
  version: "1.0.0",
  tools: [
    tool(
      "get_weather",
      "Get current weather for a location",
      {
        location: z.string().describe("City name or coordinates"),
        units: z.enum(["celsius", "fahrenheit"]).default("celsius")
      },
      async (args) => {
        // Tool implementation
        const response = await fetch(
          `https://api.weather.com/v1/current?location=${args.location}&units=${args.units}`
        );
        const data = await response.json();

        return {
          content: [{
            type: "text",
            text: `Temperature: ${data.temp}° ${args.units}
Conditions: ${data.conditions}
Humidity: ${data.humidity}%`
          }]
        };
      }
    )
  ]
});

// Use in query
const response = query({
  prompt: "What's the weather in San Francisco?",
  options: {
    mcpServers: {
      "weather-service": weatherServer
    },
    allowedTools: ["mcp__weather-service__get_weather"]
  }
});
```

### Tool Definition Pattern

```typescript
tool(
  name: string,                    // Tool identifier
  description: string,             // What the tool does
  inputSchema: ZodSchema,          // Input validation
  handler: async (args) => Result // Implementation
)
```

**Input Schema Options:**

```typescript
// Simple object schema
{
  email: z.string().email(),
  limit: z.number().min(1).max(100).default(10),
  enabled: z.boolean().optional()
}

// Complex nested schema
{
  user: z.object({
    name: z.string(),
    age: z.number().min(0)
  }),
  filters: z.array(z.string()).optional()
}

// Enum types
{
  status: z.enum(["pending", "active", "completed"]),
  priority: z.union([z.literal("low"), z.literal("high")])
}
```

**Handler Return Format:**

```typescript
// Success
return {
  content: [{
    type: "text",
    text: "Result data here"
  }]
};

// Error
return {
  content: [{
    type: "text",
    text: "Error description"
  }],
  isError: true
};
```

### Multiple Tools in One Server

```typescript
const databaseServer = createSdkMcpServer({
  name: "database",
  version: "1.0.0",
  tools: [
    tool(
      "query_users",
      "Query user records from database",
      {
        email: z.string().email().optional(),
        limit: z.number().min(1).max(100).default(10)
      },
      async (args) => {
        const results = await db.query("SELECT * FROM users WHERE...");
        return {
          content: [{ type: "text", text: JSON.stringify(results, null, 2) }]
        };
      }
    ),
    tool(
      "create_user",
      "Create a new user record",
      {
        email: z.string().email(),
        name: z.string(),
        role: z.enum(["admin", "user", "guest"])
      },
      async (args) => {
        const user = await db.insert("users", args);
        return {
          content: [{ type: "text", text: `User created: ${user.id}` }]
        };
      }
    ),
    tool(
      "delete_user",
      "Delete a user by ID",
      { userId: z.string().uuid() },
      async (args) => {
        await db.delete("users", args.userId);
        return {
          content: [{ type: "text", text: "User deleted" }]
        };
      }
    )
  ]
});
```

### External MCP Servers (stdio)

```typescript
const response = query({
  prompt: "List files and analyze Git history",
  options: {
    mcpServers: {
      // Filesystem server
      "filesystem": {
        command: "npx",
        args: ["@modelcontextprotocol/server-filesystem"],
        env: {
          ALLOWED_PATHS: "/Users/developer/projects:/tmp"
        }
      },
      // Git operations server
      "git": {
        command: "npx",
        args: ["@modelcontextprotocol/server-git"],
        env: {
          GIT_REPO_PATH: "/Users/developer/projects/my-repo"
        }
      }
    },
    allowedTools: [
      "mcp__filesystem__list_files",
      "mcp__filesystem__read_file",
      "mcp__git__log",
      "mcp__git__diff"
    ]
  }
});
```

### External MCP Servers (HTTP/SSE)

```typescript
const response = query({
  prompt: "Analyze data from remote service",
  options: {
    mcpServers: {
      "remote-service": {
        url: "https://api.example.com/mcp",
        headers: {
          "Authorization": "Bearer your-token-here",
          "Content-Type": "application/json"
        }
      }
    },
    allowedTools: ["mcp__remote-service__analyze"]
  }
});
```

### MCP Tool Naming Convention

**Format**: `mcp____`

Examples:
- `mcp__weather-service__get_weather`
- `mcp__database__query_users`
- `mcp__filesystem__read_file`
- `mcp__git__log`

**CRITICAL:**
- Server name and tool name MUST match configuration
- Use double underscores (`__`) as separators
- Include in `allowedTools` array

---

## Subagent Orchestration

### What Are Subagents?

Specialized agents with:
- **Specific expertise** - Focused on one domain
- **Custom tools** - Only tools they need
- **Different models** - Match capability to task
- **Dedicated prompts** - Tailored instructions

### Defining Subagents

```typescript
const response = query({
  prompt: "Deploy the application to production",
  options: {
    model: "claude-sonnet-4-5",
    agents: {
      "test-runner": {
        description: "Run test suites and verify coverage",
        prompt: "You run tests. Always verify 100% pass before approving deployment. Report failures clearly.",
        tools: ["Bash", "Read", "Grep"],
        model: "haiku"  // Fast, cost-effective for testing
      },
      "security-checker": {
        description: "Security validation and vulnerability scanning",
        prompt: "You check security. Verify no secrets committed, dependencies updated, OWASP compliance.",
        tools: ["Read", "Grep", "Bash"],
        model: "sonnet"  // Balance for security analysis
      },
      "deployer": {
        description: "Handle deployments and rollbacks",
        prompt: "You deploy. Deploy to staging first, verify health checks, then production. Always have rollback plan.",
        tools: ["Bash", "Read"],
        model: "sonnet"  // Reliable for critical operations
      }
    }
  }
});
```

### AgentDefinition Type

```typescript
type AgentDefinition = {
  description: string;        // When to use this agent
  prompt: string;             // System prompt for agent
  tools?: string[];           // Allowed tools (optional)
  model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';  // Model (optional)
}
```

**Field Details:**

- **description**: Natural language description of when to use agent
  - Used by main agent to decide which subagent to invoke
  - Should be clear and specific
  - Examples: "Handle database queries", "Deploy to production"

- **prompt**: System prompt for the subagent
  - Defines agent's role and behavior
  - Can include instructions, constraints, formatting
  - Inherits main agent's context

- **tools**: Array of allowed tool names
  - If omitted, inherits all tools from main agent
  - Use to restrict agent to specific tools
  - Examples: `["Read", "Grep"]` for read-only agent

- **model**: Model override
  - `"haiku"` - Fast, cost-effective tasks
  - `"sonnet"` - Balanced capability
  - `"opus"` - Maximum reasoning
  - `"inherit"` - Use main agent's model
  - If omitted, inherits main agent's model

### Multi-Agent Workflow Example

```typescript
async function runDevOpsAgent(task: string) {
  const response = query({
    prompt: task,
    options: {
      model: "claude-sonnet-4-5",
      workingDirectory: process.cwd(),
      systemPrompt: `You are a DevOps orchestrator.
Coordinate specialized agents to:
- Run tests (test-runner agent)
- Check security (security-checker agent)
- Deploy application (deployer agent)
- Monitor systems (monitoring-agent agent)`,

      agents: {
        "test-runner": {
          description: "Run automated test suites",
          prompt: "You run tests. Execute test commands, parse results, report coverage. Fail if any tests fail.",
          tools: ["Bash", "Read"],
          model: "haiku"
        },
        "security-checker": {
          description: "Security audits and vulnerability scanning",
          prompt: "You check security. Scan for secrets, check dependencies, validate permissions, verify OWASP compliance.",
          tools: ["Read", "Grep", "Bash"],
          model: "sonnet"
        },
        "deployer": {
          description: "Application deployment and rollbacks",
          prompt: "You deploy. Deploy to staging, verify health checks, deploy to production, have rollback ready.",
          tools: ["Bash", "Read"],
          model: "sonnet"
        },
        "monitoring-agent": {
          description: "System monitoring and alerting",
          prompt: "You monitor. Check metrics, detect anomalies, alert on issues, track SLAs.",
          tools: ["Bash", "Read"],
          model: "haiku"
        }
      }
    }
  });

  for await (const message of response) {
    if (message.type === 'assistant') {
      console.log('Orchestrator:', message.content);
    }
  }
}

// Usage
await runDevOpsAgent("Deploy version 2.5.0 to production with full validation");
```

### When to Use Subagents

✅ **Use subagents when:**
- Task requires different expertise areas
- Some subtasks need different models (cost optimization)
- Tool access should be restricted per role
- Clear separation of concerns needed
- Multiple steps with specialized knowledge

❌ **Don't use subagents when:**
- Single straightforward task
- All work can be done by one agent
- Overhead of orchestration > benefit
- Tools/permissions don't vary

---

## Session Management

### Overview

Sessions allow:
- **Persistent conversations** - Resume where you left off
- **Context preservation** - Agent remembers previo

…

## Source & license

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

- **Author:** [jackspace](https://github.com/jackspace)
- **Source:** [jackspace/ClaudeSkillz](https://github.com/jackspace/ClaudeSkillz)
- **License:** MIT
- **Homepage:** http://claudeskillz.jackspace.com/

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

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** yes
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-jackspace-claudeskillz-claude-agent-sdk
- Seller: https://agentstack.voostack.com/s/jackspace
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
