Claude Code

Agent SDK API reference

TypeScript and Python installation, query, ClaudeSDKClient, tools, session APIs, settings resolution, migration and version differences.

This engineering reference summarizes the official TypeScript/Python APIs. Consult the complete reference for details; start by choosing between one-shot query(), persistent clients, custom tools, session management, settings resolution and migration behavior.

For custom tools, streaming, structured output, tool search and approvals, see runtime patterns. For multitenancy and deployment, see production deployment.

#Official pages covered

Official pageCoverage
Agent SDK overviewPurpose, capabilities and differences from CLI/API
QuickstartInstallation, minimal agent and permission modes
TypeScript referencequery()、startup()、tool()、session API、resolveSettings()
Python referencequery()、ClaudeSDKClient、@tool、session API
Migration guidePackages, system prompts, setting sources and breaking changes
TypeScript V2 preview removedReplacement paths for removed APIs

#Installation

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

The TypeScript package usually includes the platform binary as an optional dependency. Verify that production images contain it and preserve PATH.

For Passion8, configure the subprocess environment:

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

The TypeScript env option replaces the subprocess environment. Usually spread ...process.env when supplying custom variables.

#Choose an entry point

RequirementTypeScriptPythonNotes
One-shot taskquery()query()Simplest option; process exits after the stream
Persistent chatcontinue: true or retain session IDClaudeSDKClientMultiple turns in one context
Streaming inputAsyncIterable<SDKUserMessage>AsyncIterable[dict]WebSockets or background queues
Custom toolstool()@toolExpose functions through an in-process MCP server
List local sessionslistSessions()list_sessions()History lists and resume controls
Resolve settingsresolveSettings()See Python options behaviorDisplay effective settings in the host app

#Minimal query() example

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

for await (const message of query({
  prompt: "Explain this repository's entry points",
  options: {
    cwd: process.cwd(),
    maxTurns: 5,
    permissionMode: "dontAsk",
    allowedTools: ["Read", "Grep", "Glob"],
    env: {
      ...process.env,
      ANTHROPIC_BASE_URL: "https://passion8.cc",
      ANTHROPIC_AUTH_TOKEN: process.env.PASSION8_API_KEY ?? ""
    }
  }
})) {
  if (message.type === "result") {
    console.log(message.result);
  }
}

#Python query() versus ClaudeSDKClient

Aspectquery()ClaudeSDKClient
SessionNew by defaultReused within the client
Multiple turnsRequires continue_conversation or resumeContext retained automatically
ConnectionOpens and closes automaticallyYou manage its lifetime
InterruptNot suitableSupported
Use caseJobs, CI, one-shot background workChat UIs, IDE panels, long conversations

For a continuously conversational agent panel, prefer Python ClaudeSDKClient. For one run per queued job, query() is simpler.

#Common functions

FunctionLanguagePurpose
query()TS/PythonStart the agent loop and return a message stream
startup()TSInitialize the subprocess early to reduce first-message latency
tool() / @toolTS/PythonDefine a custom tool
createSdkMcpServer() / create_sdk_mcp_server()TS/PythonWrap custom tools in an in-process MCP server
listSessions() / list_sessions()TS/PythonList local sessions
getSessionMessages() / get_session_messages()TS/PythonRead transcript messages
getSessionInfo() / get_session_info()TS/PythonRead one session's metadata
renameSession() / rename_session()TS/PythonRename a session
tagSession() / tag_session()TS/PythonTag a session
resolveSettings()TSResolve effective settings and provenance

#Permission modes at a glance

ModeBehaviorBest fit
defaultUnresolved tool requests invoke approval callbacksCustom approval UI
acceptEditsAutomatically approve edits and common filesystem commandsSupervised development
planRead-only exploration; edits require approvalPlanning large changes
dontAskDeny unapproved actions without promptingRestricted headless agents
autoTypeScript classifier makes decisionsSemiautonomous tasks
bypassPermissionsExecute most actions directlyStrongly isolated sandboxes only

allowedTools preapproves tools; it does not limit the complete tool inventory. Remove definitions with disallowedTools or narrow tools.

#Session API

FieldMeaning
sessionId / session_idUUID used to resume or inspect history
summaryAutomatic or manual title
lastModifiedLatest update time
cwdDirectory when the session ended
gitBranchBranch at session end
tagUser-defined tag

Typical UI usage:

const sessions = await listSessions({ dir: "/repo", limit: 50 });
const current = await getSessionInfo(sessions[0].sessionId, { dir: "/repo" });
const messages = await getSessionMessages(sessions[0].sessionId, { dir: "/repo", limit: 100 });

Do not treat a local transcript as the sole durable store. For cross-host restoration, see SessionStore in production deployment.

#Settings resolution

TypeScript resolveSettings() lets a host display effective configuration before startup.

OptionPurpose
cwdDirectory used to resolve project/local settings
settingSourcesSelect user, project and local; [] skips filesystem settings
managedSettingsHost-supplied stricter policy-tier settings
serverManagedSettingsHost-supplied server settings snapshot

Suggested multitenant defaults:

{
  settingSources: [],
  env: {
    ...process.env,
    CLAUDE_CONFIG_DIR: `/srv/claude-config/${tenantId}`,
    CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1"
  }
}

#Migrate from older SDKs

OldNew
@anthropic-ai/claude-code@anthropic-ai/claude-agent-sdk
claude-code-sdkclaude-agent-sdk
Python ClaudeCodeOptionsClaudeAgentOptions
Default Claude Code system promptExplicitly select the claude_code preset
Implicit settings behaviorReview settingSources carefully
TS V2 session APIRemoved; use current query(), session APIs or Python client

To retain CLI-like behavior when migrating, set:

systemPrompt: {
  type: "preset",
  preset: "claude_code"
}

#Cache effects

ChangeEffect on 5m/1h caching
Change systemPromptChanges the prefix, usually causing a miss
Change settingSourcesMay add/remove CLAUDE.md, skills, hooks and settings
Change tools/MCPSchema changes alter the prefix
New query() sessionEmpty history; only stable system/tool prefixes are reused
Continue/resumePreserves history and improves chances of prefix reuse
ENABLE_PROMPT_CACHING_1H=1Optionally request a one-hour TTL; higher write cost suits repeated use of the same configuration

See production deployment for observability fields.

#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.