Claude Agent SDK: Python & TypeScript

Build agents with the Claude Agent SDK in Python and TypeScript: official package names, query(), ClaudeSDKClient, and running through QCode (2026).

Updated 2026-11-26

Need an API key? Sign up →Endpoints & base URLs →

On This Page

Last verified: 2026-10-20 · 📄 Per official docs (Claude Agent SDK overview, Python and TypeScript references, checked 2026-10-20)

The Claude Agent SDK is Anthropic's official package for using Claude Code as a library: install claude-agent-sdk for Python or @anthropic-ai/claude-agent-sdk for TypeScript, then call query(). It is a library that runs the Claude Code binary, with built-in tools, permissions, sessions, and hooks, so you can embed Claude Code capabilities in your own application (checked 2026-10-20).

What is the Claude Agent SDK?

The Claude Agent SDK provides building blocks to help you create applications that can:

  • Understand natural language instructions and execute complex tasks
  • Use tools (search, code execution, file operations, etc.)
  • Maintain conversation context for multi-turn interactions
  • Connect to external services (via MCP servers)

Install the Agent SDK

Python

pip install claude-agent-sdk

TypeScript

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

The SDK version tracks the bundled Claude Code version: in the official example, SDK v0.3.191 bundles Claude Code v2.1.191 (checked 2026-10-20). These docs use Claude Code 2.1.330 (see the installation guide); check the SDK release notes for the bundled version of the current release.

Quick start with query()

Python

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    options = ClaudeAgentOptions()
    async for message in query(prompt="Create a Python web server", options=options):
        print(message)

asyncio.run(main())

TypeScript

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

for await (const message of query({
  prompt: "Create a Python web server",
  options: {}
})) {
  console.log(message);
}

query() creates a new session by default; for multiple exchanges in the same session, use ClaudeSDKClient in Python (checked 2026-10-20).

Configure QCode

Python's ClaudeAgentOptions(env={...}) merges the variables on top of the inherited process environment:

from claude_agent_sdk import ClaudeAgentOptions

options = ClaudeAgentOptions(
    env={
        "ANTHROPIC_BASE_URL": "https://api.qcode.cc/api",  # switch to https://asia.qcode.cc/api if mainland China access is unstable
        "ANTHROPIC_AUTH_TOKEN": "cr_your_api_key",
    }
)

In TypeScript, options.env replaces process.env, so spread ...process.env to keep inherited variables such as PATH:

const options = { env: { ...process.env, ANTHROPIC_BASE_URL: "https://api.qcode.cc/api", ANTHROPIC_AUTH_TOKEN: "cr_..." } };

Authenticate with an API key: the official docs state that third-party developers may not offer claude.ai login for products built on the SDK (checked 2026-10-20). QCode bills per token, with per-model rates listed on qcode.cc/models.

Agent SDK vs Claude Code CLI vs Client SDK

Item Agent SDK Claude Code CLI Client SDK
Form Python / TypeScript library Terminal interface anthropic / @anthropic-ai/sdk
How it runs Library that runs the Claude Code binary Interactive use in a terminal Calls the Messages API directly
What is built in Tools, permissions, sessions, and hooks Tools, permissions, sessions, and hooks You handle tool calls in your own code
Use it for Embedding Claude Code in your own application Daily interactive development Calling the Messages API directly

Client SDK: calling the Messages API directly

The examples below use the Client SDK (anthropic / @anthropic-ai/sdk), not the Agent SDK; use it when you only need to call the Messages API directly.

Install the Client SDK

Python SDK

pip install anthropic

TypeScript SDK

npm install @anthropic-ai/sdk

Basic Message Call

from anthropic import Anthropic

# Via QCode.cc API
client = Anthropic(
    base_url="https://api.qcode.cc/api",
    api_key="cr_your_api_key"
)

message = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=4096,
    messages=[
        {"role": "user", "content": "Explain what a RESTful API is"}
    ]
)

print(message.content[0].text)

Streaming Response

with client.messages.stream(
    model="claude-opus-5-5",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Write a Python quicksort function"}
    ]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

Tool Use

Tool Use is the core capability of Agents, allowing the model to call external tools.

Define Tools

from anthropic import Anthropic

client = Anthropic(
    base_url="https://api.qcode.cc/api",
    api_key="cr_your_api_key"
)

# Define search tool
tools = [
    {
        "name": "search_web",
        "description": "Search the web for information",
        "input_schema": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Search keywords"
                }
            },
            "required": ["query"]
        }
    },
    {
        "name": "calculate",
        "description": "Perform mathematical calculations",
        "input_schema": {
            "type": "object",
            "properties": {
                "expression": {
                    "type": "string",
                    "description": "Mathematical expression, e.g., '2 + 3 * 4'"
                }
            },
            "required": ["expression"]
        }
    }
]

# Send message with tools
message = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=4096,
    messages=[
        {"role": "user", "content": "Calculate (15 + 25) * 2 and search for what this means"}
    ],
    tools=tools
)

# Define a safe calculator before processing tool calls:
# tool arguments returned by the model can also be steered by prompt injection —
# never execute them with eval().
import ast
import operator

_OPS = {ast.Add: operator.add, ast.Sub: operator.sub,
        ast.Mult: operator.mul, ast.Div: operator.truediv}

def safe_calculate(expression: str):
    """Allow only numbers and + - * / so no arbitrary code can run."""
    def _eval(node):
        if isinstance(node, ast.Expression):
            return _eval(node.body)
        if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
            return node.value
        if isinstance(node, ast.BinOp) and type(node.op) in _OPS:
            return _OPS[type(node.op)](_eval(node.left), _eval(node.right))
        raise ValueError("only numbers and + - * / are supported")

    return _eval(ast.parse(expression, mode="eval"))

# Process tool calls
for content in message.content:
    if content.type == "text":
        print(content.text)
    elif content.type == "tool_use":
        print(f"Calling tool: {content.name}")
        print(f"Parameters: {content.input}")

        # Simulate executing the tool
        if content.name == "calculate":
            result = safe_calculate(content.input["expression"])
            tool_result = str(result)
        elif content.name == "search_web":
            tool_result = f"Results for '{content.input['query']}'..."

        # Send the result back to the model
        message = client.messages.create(
            model="claude-opus-5-5",
            max_tokens=4096,
            messages=[
                {"role": "user", "content": "Calculate (15 + 25) * 2 and search for what this means"},
                message,
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "tool_result",
                            "tool_use_id": content.id,
                            "content": tool_result
                        }
                    ]
                }
            ],
            tools=tools
        )

Streaming Tool Calls

with client.messages.stream(
    model="claude-opus-5-5",
    max_tokens=4096,
    messages=[
        {"role": "user", "content": "Create a file named hello.py that prints 'Hello, World!'"}
    ],
    tools=[
        {
            "name": "write_file",
            "description": "Write content to a file",
            "input_schema": {
                "type": "object",
                "properties": {
                    "filename": {"type": "string"},
                    "content": {"type": "string"}
                },
                "required": ["filename", "content"]
            }
        }
    ]
) as stream:
    for event in stream:
        if event.type == "content_block_delta":
            if event.delta.type == "text_delta":
                print(event.delta.text, end="", flush=True)
            elif event.delta.type == "input_json_delta":
                print(event.delta.partial_json, end="", flush=True)

Prompt Caching

Prompt Caching can significantly reduce costs for long conversations:

# System prompt (will be cached)
system_prompt = """You are a professional code review assistant.
Your responsibilities:
1. Check code security
2. Identify performance issues
3. Verify code standards
4. Provide improvement suggestions
"""

# Use cache_control to mark cacheable content
message = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=4096,
    system=[
        {
            "type": "text",
            "text": system_prompt,
            "cache_control": {"type": "ephemeral"}
        }
    ],
    messages=[
        {"role": "user", "content": "Review @src/auth/login.ts"}
    ]
)

Agent Building Example

from anthropic import Anthropic
from typing import List

class CodeReviewAgent:
    def __init__(self, api_key: str):
        self.client = Anthropic(
            base_url="https://api.qcode.cc/api",
            api_key=api_key
        )
        self.system_prompt = """You are a professional code review assistant.
Focus on: security, performance, readability, best practices.
Output for each review: issue list, severity, fix suggestions."""

    def review(self, code_snippet: str) -> str:
        message = self.client.messages.create(
            model="claude-opus-5-5",
            max_tokens=4096,
            system=self.system_prompt,
            messages=[
                {"role": "user", "content": f"Review this code:\n\n{code_snippet}"}
            ]
        )
        return message.content[0].text

# Usage
agent = CodeReviewAgent("cr_your_api_key")
result = agent.review("SELECT * FROM users WHERE id = " + user_id)

QCode.cc Configuration for the Client SDK

import os

# Method 1: Environment variable
os.environ["ANTHROPIC_BASE_URL"] = "https://api.qcode.cc/api"
os.environ["ANTHROPIC_AUTH_TOKEN"] = "cr_your_key"

client = Anthropic()  # Auto-reads environment variables

# Method 2: Asia node (recommended for mainland China)
client = Anthropic(
    base_url="https://api.qcode.cc/api",
    api_key="cr_your_key"
)

Next Steps

Get started with QCode

One API key for Claude Code, Codex and more — billed per token, per-model prices on qcode.cc/models

Enterprise →