### Install Claude Code Runtime Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/quickstart.md Installs the Claude Code runtime, which is used by the Agent SDK. This can be done via a curl script for macOS/Linux/WSL, Homebrew for macOS, or npm for cross-platform compatibility. After installation, users need to authenticate by running 'claude' in their terminal. ```bash curl -fsSL https://claude.ai/install.sh | bash ``` ```bash brew install --cask claude-code ``` ```bash npm install -g @anthropic-ai/claude-code ``` -------------------------------- ### Install Agent SDK Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/quickstart.md Installs the Claude Agent SDK package. For TypeScript, it uses npm. For Python, it provides options using uv (a fast Python package manager) or pip with a virtual environment. ```bash npm install @anthropic-ai/claude-agent-sdk ``` ```bash uv init && uv add claude-agent-sdk ``` ```bash python3 -m venv .venv && source .venv/bin/activate pip3 install claude-agent-sdk ``` -------------------------------- ### Create Project Directory Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/quickstart.md Creates a new directory for the quickstart project and navigates into it. This is a standard bash command for project initialization. ```bash mkdir my-agent && cd my-agent ``` -------------------------------- ### Set Custom System Prompt for Claude Agent Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/quickstart.md Customize the Claude agent's system prompt to define its persona and behavior. This example shows how to set a specific system prompt for a senior Python developer, ensuring adherence to PEP 8 guidelines, across Python and TypeScript configurations. It also includes tool and permission settings. ```python options=ClaudeAgentOptions( allowed_tools=["Read", "Edit", "Glob"], permission_mode="acceptEdits", system_prompt="You are a senior Python developer. Always follow PEP 8 style guidelines." ) ``` ```typescript options: { allowedTools: ["Read", "Edit", "Glob"], permissionMode: "acceptEdits", systemPrompt: "You are a senior Python developer. Always follow PEP 8 style guidelines." } ``` -------------------------------- ### SdkPluginConfig Example (Python) Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/python.md An example demonstrating how to configure local plugins for the Claude SDK. It shows how to specify multiple plugins using their type and path. ```python plugins=[ {"type": "local", "path": "./my-plugin"}, {"type": "local", "path": "/absolute/path/to/plugin"} ] ``` -------------------------------- ### Buggy Python Code Example Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/quickstart.md A Python code snippet containing intentional bugs: division by zero in `calculate_average` when given an empty list, and a TypeError in `get_user_name` when passed None. ```python def calculate_average(numbers): total = 0 for num in numbers: total += num return total / len(numbers) def get_user_name(user): return user["name"].upper() ``` -------------------------------- ### Complete Plugin Loading and Usage Example (Python) Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/guides/plugins.md A full Python example illustrating the process of loading a local plugin and utilizing its functionalities. It sets up the plugin path, configures the `ClaudeAgentOptions` with the plugin, and iterates through messages to display system initialization data and assistant responses. ```python #!/usr/bin/env python3 """Example demonstrating how to use plugins with the Agent SDK.""" from pathlib import Path import anyio from claude_agent_sdk import ( AssistantMessage, ClaudeAgentOptions, TextBlock, query, ) async def run_with_plugin(): """Example using a custom plugin.""" plugin_path = Path(__file__).parent / "plugins" / "demo-plugin" print(f"Loading plugin from: {plugin_path}") options = ClaudeAgentOptions( plugins=[ {"type": "local", "path": str(plugin_path)} ], max_turns=3, ) async for message in query( prompt="What custom commands do you have available?", options=options ): if message.type == "system" and message.subtype == "init": print(f"Loaded plugins: {message.data.get('plugins')}") print(f"Available commands: {message.data.get('slash_commands')}") if isinstance(message, AssistantMessage): for block in message.content: if isinstance(block, TextBlock): print(f"Assistant: {block.text}") if __name__ == "__main__": anyio.run(run_with_plugin) ``` -------------------------------- ### Complete Plugin Loading and Usage Example (TypeScript) Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/guides/plugins.md A comprehensive TypeScript example demonstrating how to load a local plugin and interact with its available commands. It shows how to specify the plugin path, query for available commands, and display the assistant's responses, including system initialization messages with plugin details. ```typescript import { query } from "@anthropic-ai/claude-agent-sdk"; import * as path from "path"; async function runWithPlugin() { const pluginPath = path.join(__dirname, "plugins", "my-plugin"); console.log("Loading plugin from:", pluginPath); for await (const message of query({ prompt: "What custom commands do you have available?", options: { plugins: [ { type: "local", path: pluginPath } ], maxTurns: 3 } })) { if (message.type === "system" && message.subtype === "init") { console.log("Loaded plugins:", message.plugins); console.log("Available commands:", message.slash_commands); } if (message.type === "assistant") { console.log("Assistant:", message.content); } } } runWithPlugin().catch(console.error); ``` -------------------------------- ### Example Sandbox Configuration Usage (TypeScript) Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/typescript.md Demonstrates how to configure sandbox settings programmatically when making a query. This example enables sandboxing, allows bash commands, excludes 'docker', and configures network access for local bindings and Unix sockets. ```typescript import { query } from "@anthropic-ai/claude-agent-sdk"; const result = await query({ prompt: "Build and test my project", options: { sandbox: { enabled: true, autoAllowBashIfSandboxed: true, excludedCommands: ["docker"], network: { allowLocalBinding: true, allowUnixSockets: ["/var/run/docker.sock"] } } } }); ``` -------------------------------- ### Set API Key Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/quickstart.md Creates a .env file to store the Anthropic API key. This is necessary for SDK authentication if Claude Code authentication is not already set up. The API key can be obtained from the Claude Console. ```bash ANTHROPIC_API_KEY=your-api-key ``` -------------------------------- ### Install Claude Agent SDK and Runtime Source: https://context7.com/nothflare/claude-agent-sdk-docs/llms.txt Commands to install the Claude Code runtime and the SDK for TypeScript and Python. Also includes setting the Anthropic API key. ```bash # Install Claude Code runtime (macOS/Linux/WSL) curl -fsSL https://claude.ai/install.sh | bash # TypeScript SDK npm install @anthropic-ai/claude-agent-sdk # Python SDK pip install claude-agent-sdk # Set API key export ANTHROPIC_API_KEY=your-api-key ``` -------------------------------- ### Installation Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/python.md Install the claude-agent-sdk using pip. ```APIDOC ## Installation ```bash pip install claude-agent-sdk ``` ``` -------------------------------- ### Load Project Settings for CLAUDE.md Instructions Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/python.md Shows how to load project settings, which is necessary to include CLAUDE.md files in the agent's context. This example also utilizes the 'claude_code' preset system prompt and specifies allowed tools. ```python # Load project settings to include CLAUDE.md files async for message in query( prompt="Add a new feature following project conventions", options=ClaudeAgentOptions( system_prompt={ "type": "preset", "preset": "claude_code" # Use Claude Code's system prompt }, setting_sources=["project"], # Required to load CLAUDE.md from project allowed_tools=["Read", "Write", "Edit"] ) ): print(message) ``` -------------------------------- ### Example Usage of SdkPluginConfig in TypeScript Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/typescript.md Provides an example of how to configure local plugins using the `SdkPluginConfig` type. It shows how to specify paths for plugins, both relative and absolute. ```typescript plugins: [ { type: 'local', path: './my-plugin' }, { type: 'local', path: '/absolute/path/to/plugin' } ] ``` -------------------------------- ### Install Sandbox Runtime with npm Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/guides/secure-deployment.md Installs the sandbox-runtime package using npm. This package provides lightweight isolation for Claude Code or Agent SDK applications, enforcing filesystem and network restrictions at the OS level. ```bash npm install @anthropic-ai/sandbox-runtime ``` -------------------------------- ### Multiple Tools Example with Selective Allowance Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/guides/custom-tools.md Demonstrates how to configure an MCP server with multiple tools and selectively allow specific tools for use in queries. This example shows how to define tools and then restrict their usage via the 'allowedTools' option in the query. ```typescript const multiToolServer = createSdkMcpServer({ name: "utilities", version: "1.0.0", tools: [ tool("calculate", "Perform calculations", { /* ... */ }, async (args) => { /* ... */ }), tool("translate", "Translate text", { /* ... */ }, async (args) => { /* ... */ }), tool("search_web", "Search the web", { /* ... */ }, async (args) => { /* ... */ }) ] }); // Allow only specific tools with streaming input async function* generateMessages() { yield { type: "user" as const, message: { role: "user" as const, content: "Calculate 5 + 3 and translate 'hello' to Spanish" } }; } for await (const message of query({ prompt: generateMessages(), // Use async generator for streaming input options: { mcpServers: { utilities: multiToolServer }, allowedTools: [ "mcp__utilities__calculate", // Allow calculator "mcp__utilities__translate", // Allow translator // "mcp__utilities__search_web" is NOT allowed ] } })) { // Process messages } ``` ```python from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, tool, create_sdk_mcp_server from typing import Any import asyncio # Define multiple tools using the @tool decorator @tool("calculate", "Perform calculations", {"expression": str}) async def calculate(args: dict[str, Any]) -> dict[str, Any]: result = eval(args["expression"]) # Use safe eval in production return {"content": [{"type": "text", "text": f"Result: {result}"}]} @tool("translate", "Translate text", {"text": str, "target_lang": str}) async def translate(args: dict[str, Any]) -> dict[str, Any]: # Translation logic here return {"content": [{"type": "text", "text": f"Translated: {args['text']}"}]} @tool("search_web", "Search the web", {"query": str}) async def search_web(args: dict[str, Any]) -> dict[str, Any]: # Search logic here return {"content": [{"type": "text", "text": f"Search results for: {args['query']}"}]} multi_tool_server = create_sdk_mcp_server( name="utilities", version="1.0.0", tools=[calculate, translate, search_web] # Pass decorated functions ) # Allow only specific tools with streaming input async def message_generator(): yield { "type": "user", "message": { "role": "user", "content": "Calculate 5 + 3 and translate 'hello' to Spanish" } } async for message in query( prompt=message_generator(), # Use async generator for streaming input options=ClaudeAgentOptions( mcp_servers={"utilities": multi_tool_server}, allowed_tools=[ "mcp__utilities__calculate", # Allow calculator "mcp__utilities__translate", # Allow translator # "mcp__utilities__search_web" is NOT allowed ] ) ): if hasattr(message, 'result'): print(message.result) ``` -------------------------------- ### Hook Usage Example Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/python.md Demonstrates how to register and use hooks for security validation and logging tool usage. ```APIDOC ## Hook Usage Example This example registers two hooks: one that blocks dangerous bash commands like `rm -rf /`, and another that logs all tool usage for auditing. The security hook only runs on Bash commands (via the `matcher`), while the logging hook runs on all tools. ```python from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, HookContext from typing import Any async def validate_bash_command( input_data: dict[str, Any], tool_use_id: str | None, context: HookContext ) -> dict[str, Any]: """Validate and potentially block dangerous bash commands.""" if input_data['tool_name'] == 'Bash': command = input_data['tool_input'].get('command', '') if 'rm -rf /' in command: return { 'hookSpecificOutput': { 'hookEventName': 'PreToolUse', 'permissionDecision': 'deny', 'permissionDecisionReason': 'Dangerous command blocked' } } return {} async def log_tool_use( input_data: dict[str, Any], tool_use_id: str | None, context: HookContext ) -> dict[str, Any]: """Log all tool usage for auditing.""" print(f"Tool used: {input_data.get('tool_name')}") return {} options = ClaudeAgentOptions( hooks={ 'PreToolUse': [ HookMatcher(matcher='Bash', hooks=[validate_bash_command], timeout=120), # 2 min for validation HookMatcher(hooks=[log_tool_use]) # Applies to all tools (default 60s timeout) ], 'PostToolUse': [ HookMatcher(hooks=[log_tool_use]) ] } ) async for message in query( prompt="Analyze this codebase", options=options ): print(message) ``` ``` -------------------------------- ### Install Claude Agent SDK (npm) Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/migration-guide.md Command to install the new Claude Agent SDK package for a Node.js project using npm. ```bash npm install @anthropic-ai/claude-agent-sdk ``` -------------------------------- ### Claude Agent SDK Hook Usage Example Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/python.md Demonstrates how to register and use hooks in the Claude Agent SDK. This example includes a security hook to block dangerous bash commands and a logging hook to record all tool usage. It configures these hooks using `ClaudeAgentOptions` and shows how they are applied during a query. ```python from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, HookContext from typing import Any async def validate_bash_command( input_data: dict[str, Any], tool_use_id: str | None, context: HookContext ) -> dict[str, Any]: """Validate and potentially block dangerous bash commands.""" if input_data['tool_name'] == 'Bash': command = input_data['tool_input'].get('command', '') if 'rm -rf /' in command: return { 'hookSpecificOutput': { 'hookEventName': 'PreToolUse', 'permissionDecision': 'deny', 'permissionDecisionReason': 'Dangerous command blocked' } } return {} async def log_tool_use( input_data: dict[str, Any], tool_use_id: str | None, context: HookContext ) -> dict[str, Any]: """Log all tool usage for auditing.""" print(f"Tool used: {input_data.get('tool_name')}") return {} options = ClaudeAgentOptions( hooks={ 'PreToolUse': [ HookMatcher(matcher='Bash', hooks=[validate_bash_command], timeout=120), # 2 min for validation HookMatcher(hooks=[log_tool_use]) # Applies to all tools (default 60s timeout) ], 'PostToolUse': [ HookMatcher(hooks=[log_tool_use]) ] } ) async for message in query( prompt="Analyze this codebase", options=options ): print(message) ``` -------------------------------- ### Connect to Claude with ClaudeSDKClient (Python) Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/python.md Demonstrates how to establish a connection to Claude using the `connect` method of the `ClaudeSDKClient`. This method can optionally take an initial prompt or a stream of messages to start the conversation. ```python async def connect(self, prompt: str | AsyncIterable[dict] | None = None) -> None ``` -------------------------------- ### Query Claude Agent SDK (Python) Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/guides/streaming-vs-single-mode.md Example of making a one-shot query and continuing a conversation using the Claude Agent SDK in Python. It demonstrates the use of ClaudeAgentOptions for configuring query parameters like max_turns and allowed_tools. Session continuity is managed via the continue_conversation flag. ```python from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage import asyncio async def single_message_example(): # Simple one-shot query using query() function async for message in query( prompt="Explain the authentication flow", options=ClaudeAgentOptions( max_turns=1, allowed_tools=["Read", "Grep"] ) ): if isinstance(message, ResultMessage): print(message.result) # Continue conversation with session management async for message in query( prompt="Now explain the authorization process", options=ClaudeAgentOptions( continue_conversation=True, max_turns=1 ) ): if isinstance(message, ResultMessage): print(message.result) asyncio.run(single_message_example()) ``` -------------------------------- ### Load All Filesystem Settings Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/python.md Demonstrates loading all available filesystem settings (user, project, and local) for compatibility with older SDK versions. This is achieved by passing a list containing 'user', 'project', and 'local' to the `setting_sources` option. ```python # Load all settings like SDK v0.0.x did from claude_agent_sdk import query, ClaudeAgentOptions async for message in query( prompt="Analyze this code", options=ClaudeAgentOptions( setting_sources=["user", "project", "local"] # Load all settings ) ): print(message) ``` -------------------------------- ### Get Session ID and Start Conversation Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/guides/sessions.md Initiates a new conversation and captures the session ID from the system's initial message. This ID is crucial for resuming the conversation later. The SDK automatically creates a session when a new query is made. ```typescript import { query } from "@anthropic-ai/claude-agent-sdk" let sessionId: string | undefined const response = query({ prompt: "Help me build a web application", options: { model: "claude-sonnet-4-5" } }) for await (const message of response) { // The first message is a system init message with the session ID if (message.type === 'system' && message.subtype === 'init') { sessionId = message.session_id console.log(`Session started with ID: ${sessionId}`) // You can save this ID for later resumption } // Process other messages... console.log(message) } // Later, you can use the saved sessionId to resume if (sessionId) { const resumedResponse = query({ prompt: "Continue where we left off", options: { resume: sessionId } }) } ``` ```python from claude_agent_sdk import query, ClaudeAgentOptions session_id = None async for message in query( prompt="Help me build a web application", options=ClaudeAgentOptions( model="claude-sonnet-4-5" ) ): # The first message is a system init message with the session ID if hasattr(message, 'subtype') and message.subtype == 'init': session_id = message.data.get('session_id') print(f"Session started with ID: {session_id}") # You can save this ID for later resumption # Process other messages... print(message) # Later, you can use the saved session_id to resume if session_id: async for message in query( prompt="Continue where we left off", options=ClaudeAgentOptions( resume=session_id ) ): print(message) ``` -------------------------------- ### Install Claude Code via Homebrew Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/overview.md Installs Claude Code using the Homebrew package manager. This command is specific to macOS users who have Homebrew installed. It simplifies the installation process by leveraging Homebrew's cask functionality. ```bash brew install --cask claude-code ``` -------------------------------- ### Install Claude Code via cURL Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/overview.md Installs Claude Code using a cURL command. This is a common method for downloading and executing installation scripts from a URL on macOS, Linux, and WSL environments. Ensure you have cURL installed and execute this command in your terminal. ```bash curl -fsSL https://claude.ai/install.sh | bash ``` -------------------------------- ### Install Claude Code via npm Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/overview.md Installs the Claude Code CLI globally using npm. This command is suitable for users who have Node.js and npm installed. It makes the Claude Code command-line interface available system-wide. ```bash npm install -g @anthropic-ai/claude-code ``` -------------------------------- ### Install Claude Agent SDK (pip) Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/migration-guide.md Command to install the new Claude Agent SDK package for a Python project using pip. ```bash pip install claude-agent-sdk ``` -------------------------------- ### Basic File Operations using Query (Python) Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/python.md This example demonstrates basic file operations using the `query` function from the `claude_agent_sdk`. It shows how to configure agent options, including allowed tools and working directory, and how to process messages to identify tool usage. The primary dependencies are `claude_agent_sdk` and `asyncio`. ```python from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ToolUseBlock import asyncio async def create_project(): options = ClaudeAgentOptions( allowed_tools=["Read", "Write", "Bash"], permission_mode='acceptEdits', cwd="/home/user/project" ) async for message in query( prompt="Create a Python project structure with setup.py", options=options ): if isinstance(message, AssistantMessage): for block in message.content: if isinstance(block, ToolUseBlock): print(f"Using tool: {block.name}") asyncio.run(create_project()) ``` -------------------------------- ### Run Interactive Example with Checkpointing (Python & TypeScript) Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/guides/file-checkpointing.md An interactive script that uses the Claude Agent SDK to add doc comments to a utility file. It demonstrates enabling file checkpointing, auto-accepting edits, and provides an option to rewind changes using captured checkpoint and session IDs. ```python import asyncio from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, UserMessage, ResultMessage async def main(): # Configure the SDK with checkpointing enabled # - enable_file_checkpointing: Track file changes for rewinding # - permission_mode: Auto-accept file edits without prompting # - extra_args: Required to receive user message UUIDs in the stream options = ClaudeAgentOptions( enable_file_checkpointing=True, permission_mode="acceptEdits", extra_args={"replay-user-messages": None} ) checkpoint_id = None # Store the user message UUID for rewinding session_id = None # Store the session ID for resuming print("Running agent to add doc comments to utils.py...\n") # Run the agent and capture checkpoint data from the response stream async with ClaudeSDKClient(options) as client: await client.query("Add doc comments to utils.py") async for message in client.receive_response(): # Capture the first user message UUID - this is our restore point if isinstance(message, UserMessage) and message.uuid and not checkpoint_id: checkpoint_id = message.uuid # Capture the session ID so we can resume later if isinstance(message, ResultMessage): session_id = message.session_id print("Done! Open utils.py to see the added doc comments.\n") # Ask the user if they want to rewind the changes if checkpoint_id and session_id: response = input("Rewind to remove the doc comments? (y/n): ") if response.lower() == "y": # Resume the session with an empty prompt, then rewind async with ClaudeSDKClient(ClaudeAgentOptions( enable_file_checkpointing=True, resume=session_id )) as client: await client.query("") # Empty prompt opens the connection async for message in client.receive_response(): await client.rewind_files(checkpoint_id) # Restore files break print("\n✓ File restored! Open utils.py to verify the doc comments are gone.") else: print("\nKept the modified file.") asyncio.run(main()) ``` ```typescript import { query } from "@anthropic-ai/claude-agent-sdk"; import * as readline from "readline"; async function main() { // Configure the SDK with checkpointing enabled // - enableFileCheckpointing: Track file changes for rewinding // - permissionMode: Auto-accept file edits without prompting // - extraArgs: Required to receive user message UUIDs in the stream const opts = { enableFileCheckpointing: true, permissionMode: "acceptEdits" as const, extraArgs: { 'replay-user-messages': null } }; let sessionId: string | undefined; let checkpointId: string | undefined; console.log("Running agent to add doc comments to utils.ts...\n"); const response = query({ prompt: "Add doc comments to utils.ts", options: opts }); for await (const message of response) { if (message.type === "user" && message.uuid && !checkpointId) { checkpointId = message.uuid; } if (message.type === "result") { sessionId = message.sessionId; } } console.log("Done! Open utils.ts to see the added doc comments.\n"); if (checkpointId && sessionId) { const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); const answer = await new Promise((resolve) => { rl.question("Rewind to remove the doc comments? (y/n): ", (ans) => { rl.close(); resolve(ans); }); }); if (answer.toLowerCase() === "y") { const resumeResponse = query({ prompt: "", options: { enableFileCheckpointing: true, resume: sessionId } }); for await (const message of resumeResponse) { if (message.type === "user" && message.uuid === checkpointId) { await query.rewindFiles(checkpointId); break; } } console.log("\n✓ File restored! Open utils.ts to verify the doc comments are gone."); } else { console.log("\nKept the modified file."); } } } main().catch(console.error); ``` -------------------------------- ### Loading CLAUDE.md Project Instructions with query() Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/typescript.md Explains how to load project settings, including CLAUDE.md files, by specifying `settingSources: ['project']` and using a preset system prompt. This ensures the agent follows project conventions. ```typescript // Load project settings to include CLAUDE.md files const result = query({ prompt: "Add a new feature following project conventions", options: { systemPrompt: { type: 'preset', preset: 'claude_code' // Required to use CLAUDE.md }, settingSources: ['project'], // Loads CLAUDE.md from project directory allowedTools: ['Read', 'Write', 'Edit'] } }); ``` -------------------------------- ### Loading All Setting Sources with query() Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/typescript.md Demonstrates how to load all available filesystem settings (user, project, and local) using the `settingSources` option in the `query` function. This replicates the legacy behavior of SDK v0.0.x. ```typescript // Load all settings like SDK v0.0.x did const result = query({ prompt: "Analyze this code", options: { settingSources: ['user', 'project', 'local'] // Load all settings } }); ``` -------------------------------- ### Verify Plugin Installation in Python Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/guides/plugins.md Demonstrates how to verify successful plugin loading in Python. The system initialization message, identified by `message.type == 'system'` and `message.subtype == 'init'`, provides information on loaded plugins and available slash commands. This allows developers to confirm that their custom extensions are active and ready for use. ```python import asyncio from claude_agent_sdk import query async def main(): async for message in query( prompt="Hello", options={"plugins": [{"type": "local", "path": "./my-plugin"}]} ): if message.type == "system" and message.subtype == "init": # Check loaded plugins print("Plugins:", message.data.get("plugins")) # Example: [{"name": "my-plugin", "path": "./my-plugin"}] # Check available commands from plugins print("Commands:", message.data.get("slash_commands")) # Example: ["/help", "/compact", "my-plugin:custom-command"] asyncio.run(main()) ``` -------------------------------- ### Run First Agent: List Files (Python) Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/overview.md An example Python script that initializes the Claude Agent SDK and uses the `query` function to ask the agent to list files in the current directory. It specifies allowed tools ('Bash', 'Glob') and prints the result. This demonstrates a basic agent interaction. ```python import asyncio from claude_agent_sdk import query, ClaudeAgentOptions async def main(): async for message in query( prompt="What files are in this directory?", options=ClaudeAgentOptions(allowed_tools=["Bash", "Glob"]) ): if hasattr(message, "result"): print(message.result) asyncio.run(main()) ``` -------------------------------- ### Controlling Agent Permissions Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/overview.md This snippet illustrates how to control the tools available to an agent using the `allowed_tools` and `permission_mode` options. The example creates a read-only agent capable of analyzing code but not modifying it. It provides examples in both Python and TypeScript. ```Python import asyncio from claude_agent_sdk import query, ClaudeAgentOptions async def main(): async for message in query( prompt="Review this code for best practices", options=ClaudeAgentOptions( allowed_tools=["Read", "Glob", "Grep"], permission_mode="bypassPermissions" ) ): if hasattr(message, "result"): print(message.result) asyncio.run(main()) ``` ```TypeScript import { query } from "@anthropic-ai/claude-agent-sdk"; for await (const message of query({ prompt: "Review this code for best practices", options: { allowedTools: ["Read", "Glob", "Grep"], permissionMode: "bypassPermissions" } })) { if ("result" in message) console.log(message.result); } ``` -------------------------------- ### Dynamic Agent Configuration with Python Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/guides/subagents.md Demonstrates creating a security reviewer agent dynamically using a factory function in Python. This allows for runtime customization of agent behavior, including prompt and model selection based on a security level. It utilizes the `claude_agent_sdk` library for agent interaction. ```python import asyncio from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition # Factory function that returns an AgentDefinition # This pattern lets you customize agents based on runtime conditions def create_security_agent(security_level: str) -> AgentDefinition: is_strict = security_level == "strict" return AgentDefinition( description="Security code reviewer", # Customize the prompt based on strictness level prompt=f"You are a {'strict' if is_strict else 'balanced'} security reviewer...", tools=["Read", "Grep", "Glob"], # Key insight: use a more capable model for high-stakes reviews model="opus" if is_strict else "sonnet" ) async def main(): # The agent is created at query time, so each request can use different settings async for message in query( prompt="Review this PR for security issues", options=ClaudeAgentOptions( allowed_tools=["Read", "Grep", "Glob", "Task"], agents={ # Call the factory with your desired configuration "security-reviewer": create_security_agent("strict") } ) ): if hasattr(message, "result"): print(message.result) asyncio.run(main()) ``` -------------------------------- ### Verify Plugin Installation in TypeScript Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/guides/plugins.md Illustrates how to verify that plugins have been loaded successfully in TypeScript. After loading plugins, the system initialization message (`message.type === 'system'` and `message.subtype === 'init'`) contains details about the loaded plugins and available slash commands. This helps confirm that custom functionalities are accessible. ```typescript import { query } from "@anthropic-ai/claude-agent-sdk"; for await (const message of query({ prompt: "Hello", options: { plugins: [{ type: "local", path: "./my-plugin" }] } })) { if (message.type === "system" && message.subtype === "init") { // Check loaded plugins console.log("Plugins:", message.plugins); // Example: [{ name: "my-plugin", path: "./my-plugin" }] // Check available commands from plugins console.log("Commands:", message.slash_commands); // Example: ["/help", "/compact", "my-plugin:custom-command"] } } ``` -------------------------------- ### Create Read-Only Subagent with Tool Restrictions in Python and TypeScript Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/guides/subagents.md This example demonstrates how to create a subagent with restricted tool access. By specifying the `tools` field in the `AgentDefinition`, you can limit the agent to only use the listed tools, preventing it from modifying files or running commands. This example creates a read-only analysis agent. ```python import asyncio from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition async def main(): async for message in query( prompt="Analyze the architecture of this codebase", options=ClaudeAgentOptions( allowed_tools=["Read", "Grep", "Glob", "Task"], agents={ "code-analyzer": AgentDefinition( description="Static code analysis and architecture review", prompt="""You are a code architecture analyst. Analyze code structure, identify patterns, and suggest improvements without making changes.""", # Read-only tools: no Edit, Write, or Bash access tools=["Read", "Grep", "Glob"] ) } ) ): if hasattr(message, "result"): print(message.result) asyncio.run(main()) ``` ```typescript import { query } from '@anthropic-ai/claude-agent-sdk'; for await (const message of query({ prompt: "Analyze the architecture of this codebase", options: { allowedTools: ['Read', 'Grep', 'Glob', 'Task'], agents: { 'code-analyzer': { description: 'Static code analysis and architecture review', prompt: `You are a code architecture analyst. Analyze code structure, identify patterns, and suggest improvements without making changes.`, // Read-only tools: no Edit, Write, or Bash access tools: ['Read', 'Grep', 'Glob'] } } } })) { if ('result' in message) console.log(message.result); } ``` -------------------------------- ### Run First Agent: List Files (TypeScript) Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/overview.md An example TypeScript script that initializes the Claude Agent SDK and uses the `query` function to ask the agent to list files in the current directory. It specifies allowed tools ('Bash', 'Glob') and logs the result to the console. This demonstrates a basic agent interaction in TypeScript. ```typescript import { query } from "@anthropic-ai/claude-agent-sdk"; for await (const message of query({ prompt: "What files are in this directory?", options: { allowedTools: ["Bash", "Glob"] }, })) { if ("result" in message) console.log(message.result); } ``` -------------------------------- ### Loading Specific Setting Sources with query() Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/typescript.md Shows how to load only specific filesystem settings, such as project settings, while ignoring others. This allows for more granular control over configuration. ```typescript // Load only project settings, ignore user and local const result = query({ prompt: "Run CI checks", options: { settingSources: ['project'] // Only .claude/settings.json } }); ``` -------------------------------- ### Python SDK: Query Function Example Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/python.md Demonstrates how to use the `query()` function from the Python SDK to interact with Claude Code. It shows how to set options like system prompt, permission mode, and current working directory. The function returns an async iterator yielding messages. ```python import asyncio from claude_agent_sdk import query, ClaudeAgentOptions async def main(): options = ClaudeAgentOptions( system_prompt="You are an expert Python developer", permission_mode='acceptEdits', cwd="/home/user/project" ) async for message in query( prompt="Create a Python web server", options=options ): print(message) asyncio.run(main()) ``` -------------------------------- ### Python: Rename ClaudeCodeOptions to ClaudeAgentOptions Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/migration-guide.md Example showing the renaming of the `ClaudeCodeOptions` type to `ClaudeAgentOptions` in Python for the Claude Agent SDK. ```python # BEFORE (v0.0.x) from claude_agent_sdk import query, ClaudeCodeOptions options = ClaudeCodeOptions( model="claude-sonnet-4-5", permission_mode="acceptEdits" ) # AFTER (v0.1.0) from claude_agent_sdk import query, ClaudeAgentOptions options = ClaudeAgentOptions( model="claude-sonnet-4-5", permission_mode="acceptEdits" ) ``` -------------------------------- ### System Prompt Preset Configuration Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/python.md Configure the use of Claude Code's preset system prompt, with the option to append custom instructions. ```APIDOC ## System Prompt Preset Configuration ### Description Configuration for using Claude Code's preset system prompt with optional additions. This allows leveraging predefined prompts tailored for code-related tasks. ### Method Not Applicable (Configuration Option) ### Endpoint Not Applicable (Configuration Option) ### Parameters #### Request Body - **type** (Literal["preset"]) - Required - Must be set to `"preset"` to use a preset system prompt. - **preset** (Literal["claude_code"]) - Required - Must be set to `"claude_code"` to use Claude Code's system prompt. - **append** (str) - Optional - Additional instructions to append to the preset system prompt. ### Request Example ```python from claude_agent_sdk import ClaudeAgentOptions system_prompt_config = { "type": "preset", "preset": "claude_code", "append": "Ensure all code suggestions are well-commented." } options = ClaudeAgentOptions(system_prompt=system_prompt_config) ``` ### Response #### Success Response (200) Not Applicable (Configuration Option) #### Response Example None ``` -------------------------------- ### SubagentStart Hook Input Type (TypeScript) Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/typescript.md Defines the input structure for the 'SubagentStart' hook event. It includes the ID and type of the subagent that is starting. ```typescript type SubagentStartHookInput = BaseHookInput & { hook_event_name: 'SubagentStart'; agent_id: string; agent_type: string; } ``` -------------------------------- ### Example CLAUDE.md Content Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/guides/modifying-system-prompts.md This markdown file provides project-specific guidelines for Claude, including code style, testing requirements, and common commands. It's intended to be loaded by the Agent SDK to inform Claude's behavior. ```markdown # Project Guidelines ## Code Style - Use TypeScript strict mode - Prefer functional components in React - Always include JSDoc comments for public APIs ## Testing - Run `npm test` before committing - Maintain >80% code coverage - Use jest for unit tests, playwright for E2E ## Commands - Build: `npm run build` - Dev server: `npm run dev` - Type check: `npm run typecheck` ``` -------------------------------- ### Permissions Control Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/overview.md Explains how to control the tools your agent can access, allowing for safe operations or blocking sensitive actions. This example creates a read-only agent. ```APIDOC ## Permissions Control ### Description This example demonstrates how to control the tools your agent can use by specifying `allowedTools`. This creates a read-only agent capable of analysis but not modification. ### Method query ### Endpoint N/A (SDK function) ### Parameters #### Query Parameters - **prompt** (string) - Required - The prompt for the agent. - **options** (object) - Optional - Configuration options for the agent. - **allowedTools** (array of strings) - Required - A list of tools the agent is permitted to use (e.g., ["Read", "Glob", "Grep"]). - **permissionMode** (string) - Optional - The permission mode to use (e.g., "bypassPermissions"). ### Request Example ```typescript import { query } from "@anthropic-ai/claude-agent-sdk"; for await (const message of query({ prompt: "Review this code for best practices", options: { allowedTools: ["Read", "Glob", "Grep"], permissionMode: "bypassPermissions" } })) { if ("result" in message) console.log(message.result); } ``` ### Response #### Success Response (200) - **result** (string) - The output from the agent's analysis. #### Response Example ```json { "result": "The code follows best practices..." } ``` ``` -------------------------------- ### Configuring query() for Testing and CI Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/typescript.md Illustrates how to configure the `query` function for testing and CI environments by excluding local settings to ensure consistent behavior. It also shows how to bypass permissions. ```typescript // Ensure consistent behavior in CI by excluding local settings const result = query({ prompt: "Run tests", options: { settingSources: ['project'], // Only team-shared settings permissionMode: 'bypassPermissions' } }); ``` -------------------------------- ### Subagents Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/overview.md Demonstrates how to use subagents within the Claude Agent SDK to delegate tasks to specialized agents. This example shows a code-reviewer agent being used to review a codebase. ```APIDOC ## Subagents Example ### Description This example demonstrates how to use a specialized 'code-reviewer' subagent to review a codebase. The agent is configured with specific tools and a prompt for code analysis. ### Method query ### Endpoint N/A (SDK function) ### Parameters #### Query Parameters - **prompt** (string) - Required - The main prompt for the agent. - **options** (object) - Optional - Configuration options for the agent. - **allowedTools** (array of strings) - Optional - List of allowed tools for the agent. - **agents** (object) - Optional - Configuration for subagents. - **code-reviewer** (object) - Configuration for the code-reviewer agent. - **description** (string) - Description of the code-reviewer agent. - **prompt** (string) - Prompt for the code-reviewer agent. - **tools** (array of strings) - Tools available to the code-reviewer agent. ### Request Example ```typescript for await (const message of query({ prompt: "Use the code-reviewer agent to review this codebase", options: { allowedTools: ["Read", "Glob", "Grep", "Task"], agents: { "code-reviewer": { description: "Expert code reviewer for quality and security reviews.", prompt: "Analyze code quality and suggest improvements.", tools: ["Read", "Glob", "Grep"] } } } })) { if ("result" in message) console.log(message.result); } ``` ### Response #### Success Response (200) - **result** (string) - The output from the subagent's execution. #### Response Example ```json { "result": "Code review suggestions..." } ``` ``` -------------------------------- ### Programmatic Subagent Definition (Python) Source: https://github.com/nothflare/claude-agent-sdk-docs/blob/main/docs/en/agent-sdk/guides/subagents.md This example demonstrates how to define two subagents, 'code-reviewer' and 'test-runner', programmatically using the `AgentDefinition` class in Python. It shows how to specify descriptions, prompts, allowed tools, and model overrides for each subagent. ```APIDOC ## POST /query (Simulated) ### Description This endpoint simulates a query to the Claude Agent SDK, demonstrating the programmatic definition of subagents. It showcases how to configure specialized agents like a code reviewer and a test runner with specific prompts, tools, and model settings. ### Method POST (Simulated) ### Endpoint /query (Simulated) ### Parameters #### Query Parameters None #### Request Body ```json { "prompt": "Review the authentication module for security issues", "options": { "allowed_tools": ["Read", "Grep", "Glob", "Task"], "agents": { "code-reviewer": { "description": "Expert code review specialist. Use for quality, security, and maintainability reviews.", "prompt": "You are a code review specialist with expertise in security, performance, and best practices.\n\nWhen reviewing code:\n- Identify security vulnerabilities\n- Check for performance issues\n- Verify adherence to coding standards\n- Suggest specific improvements\n\nBe thorough but concise in your feedback.", "tools": ["Read", "Grep", "Glob"], "model": "sonnet" }, "test-runner": { "description": "Runs and analyzes test suites. Use for test execution and coverage analysis.", "prompt": "You are a test execution specialist. Run tests and provide clear analysis of results.\n\nFocus on:\n- Running test commands\n- Analyzing test output\n- Identifying failing tests\n- Suggesting fixes for failures", "tools": ["Bash", "Read", "Grep"] } } } } ``` ### Response #### Success Response (200) - **result** (string) - The output or result generated by the agent or subagent. #### Response Example ```json { "result": "Code review feedback or test results..." } ``` ```