Definition

The Claude Agent SDK (formerly the Claude Code SDK) is a TypeScript/Node.js framework for building autonomous agents with capabilities identical to Claude Code.

It provides the AgentRuntime (exposed via ClaudeSDKClient) which manages the core agentic loop, tool-calling state, and context compaction.


Core Architecture

ClaudeAgent and ClaudeSDKClient

The primary entry points for interacting with the agent.

  • ClaudeAgent: A high-level class for simple query/response interactions where the agent autonomously decides which tools to call.
  • ClaudeSDKClient: A lower-level client used for granular control over the agent's runtime, including hook registration and session management.

The Agentic Loop

The SDK implements a state-machine loop that executes until a terminal condition is met.

  1. Request: The SDK sends the conversation history and available tool schemas to Claude.
  2. Stop Reason: The model returns a response with a stop_reason.
  3. Branching:
    • If stop_reason == "tool_use": The SDK executes the requested tool(s) locally and appends the result to the history. It then automatically re-triggers the Request.
    • If stop_reason == "end_turn": The loop terminates and returns the final answer.

Middleware and Hooks

The SDK features a lifecycle Hook System that acts as middleware for deterministic governance.

Implementation

Hooks are registered in the ClaudeAgentOptions and receive input, toolUseID, and an AbortSignal.

import { ClaudeSDKClient, type PreToolUseHookInput } from "@anthropic-ai/claude-agent-sdk";

const client = new ClaudeSDKClient({
  hooks: {
    PreToolUse: [{
      pattern: "Bash", // Regex matcher for tool names
      callback: async (input) => {
        const { tool_input } = input as PreToolUseHookInput;
        // Deterministic check: Block network access in Bash
        if (tool_input.command.includes("curl")) {
          return { 
            result: { type: "error", message: "Network access restricted." } 
          };
        }
        return {}; // Proceed
      }
    }]
  }
});

Key Lifecycle Events

  • UserPromptSubmit: Before the agent receives the prompt (PII scrubbing).
  • PreToolUse: Before a tool executes (Permission enforcement).
  • PostToolUse: After tool execution (Output filtering/logging).
  • PreCompact: Before history summarization (Preserving critical facts).

Context Management

The SDK automatically manages the 200k+ token context window through Compaction.

Compaction Strategy

When the token count reaches a defined threshold, the SDK triggers a compaction event.

  • Summarization: Older conversation turns are summarized into a concise "Context Summary" block.
  • Retention: Critical "Case Facts" and recent turns are preserved in high resolution.
  • Customization: Developers can use the PreCompact hook to inject specific facts that must never be summarized or deleted.

Tools and MCP Integration

The SDK is designed to consume tools via the Model Context Protocol (MCP).

Built-in Tools

  • Filesystem: Read, Write, Edit, LS, Grep.
  • System: Bash (Shell execution).
  • Network: WebFetch (Crawl/Search).

Custom Tools

Developers can define custom tools by providing a JSON Schema and a local execution function.

const agent = new ClaudeAgent({
  tools: [
    {
      name: "get_weather",
      description: "Get current weather for a city",
      input_schema: { type: "object", properties: { city: { type: "string" } } },
      handler: async ({ city }) => ({ temperature: "22C", unit: "metric" })
    }
  ]
});

Examples and Use Cases

Headless CI/CD Reviewer

Using the SDK in a non-interactive environment to audit pull requests.

  • Runtime: Node.js script invoked by GitHub Actions.
  • Process: agent.query("Review PR #12 for security bugs") -> Agent reads files, identifies vulnerabilities, and posts a GitHub comment via an MCP tool.

Specialized Agent Skills

Creating "skills" (modular sets of tools and prompts) that can be shared across multiple agent instances.


References