Claude Code

Agent SDK

Claude Agent SDK purpose, installation, TypeScript/Python query usage, permissions, hooks, MCP, sessions and deployment boundaries.

Agent SDK exposes the Claude Code agent loop as Python and TypeScript libraries. Embed file reading, command execution, code editing and context management in services, CLIs, CI or background jobs.

Use the CLI for direct project work; use Agent SDK to embed these capabilities in products, automation and background services.

This page covers basics. See API reference for TypeScript/Python, sessions, settings and migration; agent features for the loop, settingSources, skills, subagents, todos and checkpoints; capabilities for permissions, hooks, MCP, SessionStore, costs, OTEL, security and caching; runtime patterns for tools, prompts, streaming, structured output, search, approvals and commands; and production deployment for topology.

#When to use the SDK

RequirementChoose
Local interactive development and repository editsClaude Code CLI
Run agents inside a web service or internal platformAgent SDK
Automated fixes, reviews or migration in CIAgent SDK or claude -p
Custom tools, approvals and session storageAgent SDK
Pure model API callsClaude Messages API

#Installation

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

The TypeScript SDK includes the platform Claude Code binary through an optional dependency; separate CLI installation is usually unnecessary.

#Authentication

The official SDK supports API keys and cloud-provider authentication. For Passion8, point its Anthropic-compatible endpoint at the gateway:

export ANTHROPIC_BASE_URL="https://passion8.cc"
export ANTHROPIC_AUTH_TOKEN="sk-YOUR_PASSION8_API_KEY"

For a direct Anthropic Console key, use:

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

Do not mix Claude subscription login with third-party products. Official guidance generally requires API key/provider authentication for third-party developers; do not resell or embed claude.ai subscription access in an agent product.

#Minimal examples

#TypeScript

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

for await (const message of query({
  prompt: "Read the current directory and summarize this project's purpose.",
  options: {
    allowedTools: ["Read", "Glob", "Grep"],
    permissionMode: "dontAsk"
  }
})) {
  if ("result" in message) console.log(message.result);
}

Run:

npx tsx agent.ts

#Python

agent.py
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions


async def main():
    async for message in query(
        prompt="Read the current directory and summarize this project's purpose.",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Glob", "Grep"],
            permission_mode="dontAsk",
        ),
    ):
        if hasattr(message, "result"):
            print(message.result)


asyncio.run(main())

Run:

python agent.py

query() returns an async iterator. Items may be system or assistant messages, tool calls, tool results or the final result. Stream them to a UI or collect them for processing.

#Common options

OptionTypeScriptPythonPurpose
Preapproved toolsallowedToolsallowed_toolsPreapprove tool use
Permission modepermissionModepermission_modeacceptEdits, plan and others
System promptsystemPromptsystem_promptCustom agent role
MCPmcpServersmcp_serversExternal tools
HookshookshooksIntercept before/after tools
Working directorycwdcwdAgent execution directory

#Permission modes

ModeSDK purpose
defaultSupply an approval callback
acceptEditsAutomatically accept file edits
planRead-only exploration without source changes
dontAskDeny actions outside the allowed tools
autoTypeScript safety classifier
bypassPermissionsSandboxed CI or isolated environments only

Start production agents with dontAsk or plan, expanding tool access for the task as needed.

#Built-in tools

Agent SDK can use Claude Code's core tools directly:

ToolPurpose
ReadRead files
WriteCreate files
EditPrecise file edits
BashRun commands
GlobFind files
GrepSearch content
WebSearchSearch the web
WebFetchFetch pages
MonitorWatch background script output
AskUserQuestionRequest clarification or approval

#Hooks and MCP

The SDK also supports Claude Code extensions:

  • Hooks: record, block or validate at PreToolUse, PostToolUse, Stop and other events.
  • MCP: connect databases, browsers, internal APIs and project-management systems.
  • Subagents: isolate subtasks in specialized agents.
  • Sessions: save and restore conversation context.
  • Prompt caching: inspect cache read/write tokens and control TTL.

#Production recommendations

RiskRecommendation
Unbounded runsSet timeouts, turn limits and budgets
Too many toolsUse tool search or expose only task-relevant tools
Excessive permissionsDefault to dontAsk and allow tools individually
Tenant leakageIsolate working directory, environment and session storage per user
Uncontrolled costsRecord cache_creation_input_tokens and cache_read_input_tokens
Difficult output parsingUse structured output or JSON schema

See production deployment for a complete checklist. For persistent conversations, queues, images and plugins, continue to streaming and plugins.

#Official references

Support

Need help?

For setup, billing, or model issues, email us. Check the status page for uptime.

WeChat / QQ support is available at the bottom right.