# Claude Code Agent SDK API reference

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

URL: https://docs.passion8.cc/en/docs/claude-code/sdk-api-reference
Language: en
Publisher: Passion8

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](https://docs.passion8.cc/en/docs/claude-code/sdk-runtime-patterns). For multitenancy and deployment, see [production deployment](https://docs.passion8.cc/en/docs/claude-code/sdk-production).

## Official pages covered

| Official page | Coverage |
| --- | --- |
| Agent SDK overview | Purpose, capabilities and differences from CLI/API |
| Quickstart | Installation, minimal agent and permission modes |
| TypeScript reference | `query()`、`startup()`、`tool()`、session API、`resolveSettings()` |
| Python reference | `query()`、`ClaudeSDKClient`、`@tool`、session API |
| Migration guide | Packages, system prompts, setting sources and breaking changes |
| TypeScript V2 preview removed | Replacement paths for removed APIs |

## Installation





### TypeScript


```bash
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.




### Python


```bash
pip install claude-agent-sdk
```

Python requires 3.10 or newer. Prefer ClaudeSDKClient for persistent conversations and query() for one-shot tasks.







For Passion8, configure the subprocess environment:

```bash
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

| Requirement | TypeScript | Python | Notes |
| --- | --- | --- | --- |
| One-shot task | `query()` | `query()` | Simplest option; process exits after the stream |
| Persistent chat | `continue: true` or retain session ID | `ClaudeSDKClient` | Multiple turns in one context |
| Streaming input | `AsyncIterable<SDKUserMessage>` | `AsyncIterable[dict]` | WebSockets or background queues |
| Custom tools | `tool()` | `@tool` | Expose functions through an in-process MCP server |
| List local sessions | `listSessions()` | `list_sessions()` | History lists and resume controls |
| Resolve settings | `resolveSettings()` | See Python options behavior | Display effective settings in the host app |

## Minimal query() example





### TypeScript


```typescript
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


```python
import asyncio
from claude_agent_sdk import ClaudeAgentOptions, query


async def main() -> None:
    options = ClaudeAgentOptions(
        cwd=".",
        max_turns=5,
        permission_mode="dontAsk",
        allowed_tools=["Read", "Grep", "Glob"],
        env={
            "ANTHROPIC_BASE_URL": "https://passion8.cc",
            "ANTHROPIC_AUTH_TOKEN": "sk-YOUR_PASSION8_API_KEY",
        },
    )

    async for message in query(prompt="Explain this repository's entry points", options=options):
        if getattr(message, "type", None) == "result":
            print(message.result)


asyncio.run(main())
```







## Python query() versus ClaudeSDKClient

| Aspect | `query()` | `ClaudeSDKClient` |
| --- | --- | --- |
| Session | New by default | Reused within the client |
| Multiple turns | Requires continue_conversation or resume | Context retained automatically |
| Connection | Opens and closes automatically | You manage its lifetime |
| Interrupt | Not suitable | Supported |
| Use case | Jobs, CI, one-shot background work | Chat 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

| Function | Language | Purpose |
| --- | --- | --- |
| `query()` | TS/Python | Start the agent loop and return a message stream |
| `startup()` | TS | Initialize the subprocess early to reduce first-message latency |
| `tool()` / `@tool` | TS/Python | Define a custom tool |
| `createSdkMcpServer()` / `create_sdk_mcp_server()` | TS/Python | Wrap custom tools in an in-process MCP server |
| `listSessions()` / `list_sessions()` | TS/Python | List local sessions |
| `getSessionMessages()` / `get_session_messages()` | TS/Python | Read transcript messages |
| `getSessionInfo()` / `get_session_info()` | TS/Python | Read one session's metadata |
| `renameSession()` / `rename_session()` | TS/Python | Rename a session |
| `tagSession()` / `tag_session()` | TS/Python | Tag a session |
| `resolveSettings()` | TS | Resolve effective settings and provenance |

## Permission modes at a glance

| Mode | Behavior | Best fit |
| --- | --- | --- |
| `default` | Unresolved tool requests invoke approval callbacks | Custom approval UI |
| `acceptEdits` | Automatically approve edits and common filesystem commands | Supervised development |
| `plan` | Read-only exploration; edits require approval | Planning large changes |
| `dontAsk` | Deny unapproved actions without prompting | Restricted headless agents |
| `auto` | TypeScript classifier makes decisions | Semiautonomous tasks |
| `bypassPermissions` | Execute most actions directly | Strongly isolated sandboxes only |

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

## Session API

| Field | Meaning |
| --- | --- |
| `sessionId` / `session_id` | UUID used to resume or inspect history |
| `summary` | Automatic or manual title |
| `lastModified` | Latest update time |
| `cwd` | Directory when the session ended |
| `gitBranch` | Branch at session end |
| `tag` | User-defined tag |

Typical UI usage:

```typescript
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](https://docs.passion8.cc/en/docs/claude-code/sdk-production).

## Settings resolution

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

| Option | Purpose |
| --- | --- |
| `cwd` | Directory used to resolve project/local settings |
| `settingSources` | Select user, project and local; [] skips filesystem settings |
| `managedSettings` | Host-supplied stricter policy-tier settings |
| `serverManagedSettings` | Host-supplied server settings snapshot |

Suggested multitenant defaults:

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

## Migrate from older SDKs

| Old | New |
| --- | --- |
| `@anthropic-ai/claude-code` | `@anthropic-ai/claude-agent-sdk` |
| `claude-code-sdk` | `claude-agent-sdk` |
| Python `ClaudeCodeOptions` | `ClaudeAgentOptions` |
| Default Claude Code system prompt | Explicitly select the claude_code preset |
| Implicit settings behavior | Review settingSources carefully |
| TS V2 session API | Removed; use current query(), session APIs or Python client |

To retain CLI-like behavior when migrating, set:

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

## Cache effects

| Change | Effect on 5m/1h caching |
| --- | --- |
| Change systemPrompt | Changes the prefix, usually causing a miss |
| Change settingSources | May add/remove CLAUDE.md, skills, hooks and settings |
| Change tools/MCP | Schema changes alter the prefix |
| New query() session | Empty history; only stable system/tool prefixes are reused |
| Continue/resume | Preserves history and improves chances of prefix reuse |
| `ENABLE_PROMPT_CACHING_1H=1` | Optionally request a one-hour TTL; higher write cost suits repeated use of the same configuration |

See [production deployment](https://docs.passion8.cc/en/docs/claude-code/sdk-production) for observability fields.

## Official references

- [Agent SDK overview](https://code.claude.com/docs/en/agent-sdk/overview.md)
- [Agent SDK quickstart](https://code.claude.com/docs/en/agent-sdk/quickstart.md)
- [TypeScript reference](https://code.claude.com/docs/en/agent-sdk/typescript.md)
- [Python reference](https://code.claude.com/docs/en/agent-sdk/python.md)
- [Migration guide](https://code.claude.com/docs/en/agent-sdk/migration-guide.md)
- [TypeScript V2 session API removed](https://code.claude.com/docs/en/agent-sdk/typescript-v2-preview.md)
