Loading...
    • Developer Guide
    • API Reference
    • MCP
    • Resources
    • Release Notes
    Search...
    ⌘K

    First steps

    Intro to ClaudeQuickstart

    Models & pricing

    Models overviewChoosing a modelWhat's new in Claude 4.5Migrating to Claude 4.5Model deprecationsPricing

    Build with Claude

    Features overviewUsing the Messages APIContext windowsPrompting best practices

    Capabilities

    Prompt cachingContext editingExtended thinkingStreaming MessagesBatch processingCitationsMultilingual supportToken countingEmbeddingsVisionPDF supportFiles APISearch resultsGoogle Sheets add-on

    Tools

    OverviewHow to implement tool useToken-efficient tool useFine-grained tool streamingBash toolCode execution toolComputer use toolText editor toolWeb fetch toolWeb search toolMemory tool

    Agent Skills

    OverviewQuickstartBest practicesUsing Skills with the API

    Agent SDK

    OverviewTypeScript SDKPython SDK

    Guides

    Streaming InputHandling PermissionsSession ManagementHosting the Agent SDKModifying system promptsMCP in the SDKCustom ToolsSubagents in the SDKSlash Commands in the SDKAgent Skills in the SDKTracking Costs and UsageTodo ListsPlugins in the SDK

    MCP in the API

    MCP connectorRemote MCP servers

    Claude on 3rd-party platforms

    Amazon BedrockVertex AI

    Prompt engineering

    OverviewPrompt generatorUse prompt templatesPrompt improverBe clear and directUse examples (multishot prompting)Let Claude think (CoT)Use XML tagsGive Claude a role (system prompts)Prefill Claude's responseChain complex promptsLong context tipsExtended thinking tips

    Test & evaluate

    Define success criteriaDevelop test casesUsing the Evaluation ToolReducing latency

    Strengthen guardrails

    Reduce hallucinationsIncrease output consistencyMitigate jailbreaksStreaming refusalsReduce prompt leakKeep Claude in character

    Administration and monitoring

    Admin API overviewUsage and Cost APIClaude Code Analytics API
    Console
    Agent SDK

    Agent SDK reference - TypeScript

    Complete API reference for the TypeScript Agent SDK, including all functions, types, and interfaces.

    Installation

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

    Functions

    query()

    The primary function for interacting with Claude Code. Creates an async generator that streams messages as they arrive.

    function query({
      prompt,
      options
    }: {
      prompt: string | AsyncIterable<SDKUserMessage>;
      options?: Options;
    }): Query

    Parameters

    ParameterTypeDescription
    promptstring | AsyncIterable<SDKUserMessage>The input prompt as a string or async iterable for streaming mode
    optionsOptionsOptional configuration object (see Options type below)

    Returns

    Returns a Query object that extends AsyncGenerator<SDKMessage, void> with additional methods.

    tool()

    Creates a type-safe MCP tool definition for use with SDK MCP servers.

    function tool<Schema extends ZodRawShape>(
      name: string,
      description: string,
      inputSchema: Schema,
      handler: (args: z.infer<ZodObject<Schema>>, extra: unknown) => Promise<CallToolResult>
    ): SdkMcpToolDefinition<Schema>

    Parameters

    ParameterTypeDescription
    namestringThe name of the tool
    descriptionstringA description of what the tool does
    inputSchemaSchema extends ZodRawShapeZod schema defining the tool's input parameters
    handler(args, extra) => Promise<CallToolResult>Async function that executes the tool logic

    createSdkMcpServer()

    Creates an MCP server instance that runs in the same process as your application.

    function createSdkMcpServer(options: {
      name: string;
      version?: string;
      tools?: Array<SdkMcpToolDefinition<any>>;
    }): McpSdkServerConfigWithInstance

    Parameters

    ParameterTypeDescription
    options.namestringThe name of the MCP server
    options.versionstringOptional version string
    options.toolsArray<SdkMcpToolDefinition>Array of tool definitions created with tool()

    Types

    Options

    Configuration object for the query() function.

    PropertyTypeDefaultDescription
    abortControllerAbortControllernew AbortController()Controller for cancelling operations
    additionalDirectoriesstring[][]Additional directories Claude can access
    agentsRecord<string, [AgentDefinition](#agentdefinition)>undefinedProgrammatically define subagents
    allowedToolsstring[]All toolsList of allowed tool names
    canUseToolCanUseToolundefinedCustom permission function for tool usage
    continuebooleanfalseContinue the most recent conversation
    cwdstringprocess.cwd()Current working directory
    disallowedToolsstring[][]List of disallowed tool names
    envDict<string>process.envEnvironment variables
    executable'bun' | 'deno' | 'node'Auto-detectedJavaScript runtime to use
    executableArgsstring[][]Arguments to pass to the executable
    extraArgsRecord<string, string | null>{}Additional arguments
    fallbackModelstringundefinedModel to use if primary fails
    forkSessionbooleanfalseWhen resuming with resume, fork to a new session ID instead of continuing the original session
    hooksPartial<Record<HookEvent, HookCallbackMatcher[]>>{}Hook callbacks for events
    includePartialMessagesbooleanfalseInclude partial message events
    maxThinkingTokensnumberundefinedMaximum tokens for thinking process
    maxTurnsnumberundefinedMaximum conversation turns
    mcpServersRecord<string, [McpServerConfig](#mcpserverconfig)>{}MCP server configurations
    modelstringDefault from CLIClaude model to use
    pathToClaudeCodeExecutablestringAuto-detectedPath to Claude Code executable
    permissionModePermissionMode'default'Permission mode for the session
    permissionPromptToolNamestringundefinedMCP tool name for permission prompts
    pluginsSdkPluginConfig[][]Load custom plugins from local paths. See Plugins for details
    resumestringundefinedSession ID to resume
    settingSourcesSettingSource[][] (no settings)Control which filesystem settings to load. When omitted, no settings are loaded. Note: Must include 'project' to load CLAUDE.md files
    stderr(data: string) => voidundefinedCallback for stderr output
    strictMcpConfigbooleanfalseEnforce strict MCP validation
    systemPromptstring | { type: 'preset'; preset: 'claude_code'; append?: string }undefined (empty prompt)System prompt configuration. Pass a string for custom prompt, or { type: 'preset', preset: 'claude_code' } to use Claude Code's system prompt. When using the preset object form, add append to extend the system prompt with additional instructions

    Query

    Interface returned by the query() function.

    interface Query extends AsyncGenerator<SDKMessage, void> {
      interrupt(): Promise<void>;
      setPermissionMode(mode: PermissionMode): Promise<void>;
    }

    Methods

    MethodDescription
    interrupt()Interrupts the query (only available in streaming input mode)
    setPermissionMode()Changes the permission mode (only available in streaming input mode)

    AgentDefinition

    Configuration for a subagent defined programmatically.

    type AgentDefinition = {
      description: string;
      tools?: string[];
      prompt: string;
      model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
    }
    FieldRequiredDescription
    descriptionYesNatural language description of when to use this agent
    toolsNoArray of allowed tool names. If omitted, inherits all tools
    promptYesThe agent's system prompt
    modelNoModel override for this agent. If omitted, uses the main model

    SettingSource

    Controls which filesystem-based configuration sources the SDK loads settings from.

    type SettingSource = 'user' | 'project' | 'local';
    ValueDescriptionLocation
    'user'Global user settings~/.claude/settings.json
    'project'Shared project settings (version controlled).claude/settings.json
    'local'Local project settings (gitignored).claude/settings.local.json

    Default behavior

    When settingSources is omitted or undefined, the SDK does not load any filesystem settings. This provides isolation for SDK applications.

    Why use settingSources?

    Load all filesystem settings (legacy behavior):

    // Load all settings like SDK v0.0.x did
    const result = query({
      prompt: "Analyze this code",
      options: {
        settingSources: ['user', 'project', 'local']  // Load all settings
      }
    });

    Load only specific setting sources:

    // Load only project settings, ignore user and local
    const result = query({
      prompt: "Run CI checks",
      options: {
        settingSources: ['project']  // Only .claude/settings.json
      }
    });

    Testing and CI environments:

    // Ensure consistent behavior in CI by excluding local settings
    const result = query({
      prompt: "Run tests",
      options: {
        settingSources: ['project'],  // Only team-shared settings
        permissionMode: 'bypassPermissions'
      }
    });

    SDK-only applications:

    // Define everything programmatically (default behavior)
    // No filesystem dependencies - settingSources defaults to []
    const result = query({
      prompt: "Review this PR",
      options: {
        // settingSources: [] is the default, no need to specify
        agents: { /* ... */ },
        mcpServers: { /* ... */ },
        allowedTools: ['Read', 'Grep', 'Glob']
      }
    });

    Loading CLAUDE.md project instructions:

    // 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']
      }
    });

    Settings precedence

    When multiple sources are loaded, settings are merged with this precedence (highest to lowest):

    1. Local settings (.claude/settings.local.json)
    2. Project settings (.claude/settings.json)
    3. User settings (~/.claude/settings.json)

    Programmatic options (like agents, allowedTools) always override filesystem settings.

    PermissionMode

    type PermissionMode =
      | 'default'           // Standard permission behavior
      | 'acceptEdits'       // Auto-accept file edits
      | 'bypassPermissions' // Bypass all permission checks
      | 'plan'              // Planning mode - no execution

    CanUseTool

    Custom permission function type for controlling tool usage.

    type CanUseTool = (
      toolName: string,
      input: ToolInput,
      options: {
        signal: AbortSignal;
        suggestions?: PermissionUpdate[];
      }
    ) => Promise<PermissionResult>;

    PermissionResult

    Result of a permission check.

    type PermissionResult = 
      | {
          behavior: 'allow';
          updatedInput: ToolInput;
          updatedPermissions?: PermissionUpdate[];
        }
      | {
          behavior: 'deny';
          message: string;
          interrupt?: boolean;
        }

    McpServerConfig

    Configuration for MCP servers.

    type McpServerConfig = 
      | McpStdioServerConfig
      | McpSSEServerConfig
      | McpHttpServerConfig
      | McpSdkServerConfigWithInstance;

    McpStdioServerConfig

    type McpStdioServerConfig = {
      type?: 'stdio';
      command: string;
      args?: string[];
      env?: Record<string, string>;
    }

    McpSSEServerConfig

    type McpSSEServerConfig = {
      type: 'sse';
      url: string;
      headers?: Record<string, string>;
    }

    McpHttpServerConfig

    type McpHttpServerConfig = {
      type: 'http';
      url: string;
      headers?: Record<string, string>;
    }

    McpSdkServerConfigWithInstance

    type McpSdkServerConfigWithInstance = {
      type: 'sdk';
      name: string;
      instance: McpServer;
    }

    SdkPluginConfig

    Configuration for loading plugins in the SDK.

    type SdkPluginConfig = {
      type: 'local';
      path: string;
    }
    FieldTypeDescription
    type'local'Must be 'local' (only local plugins currently supported)
    pathstringAbsolute or relative path to the plugin directory

    Example:

    plugins: [
      { type: 'local', path: './my-plugin' },
      { type: 'local', path: '/absolute/path/to/plugin' }
    ]

    For complete information on creating and using plugins, see Plugins.

    Message Types

    SDKMessage

    Union type of all possible messages returned by the query.

    type SDKMessage = 
      | SDKAssistantMessage
      | SDKUserMessage
      | SDKUserMessageReplay
      | SDKResultMessage
      | SDKSystemMessage
      | SDKPartialAssistantMessage
      | SDKCompactBoundaryMessage;

    SDKAssistantMessage

    Assistant response message.

    type SDKAssistantMessage = {
      type: 'assistant';
      uuid: UUID;
      session_id: string;
      message: APIAssistantMessage; // From Anthropic SDK
      parent_tool_use_id: string | null;
    }

    SDKUserMessage

    User input message.

    type SDKUserMessage = {
      type: 'user';
      uuid?: UUID;
      session_id: string;
      message: APIUserMessage; // From Anthropic SDK
      parent_tool_use_id: string | null;
    }

    SDKUserMessageReplay

    Replayed user message with required UUID.

    type SDKUserMessageReplay = {
      type: 'user';
      uuid: UUID;
      session_id: string;
      message: APIUserMessage;
      parent_tool_use_id: string | null;
    }

    SDKResultMessage

    Final result message.

    type SDKResultMessage = 
      | {
          type: 'result';
          subtype: 'success';
          uuid: UUID;
          session_id: string;
          duration_ms: number;
          duration_api_ms: number;
          is_error: boolean;
          num_turns: number;
          result: string;
          total_cost_usd: number;
          usage: NonNullableUsage;
          permission_denials: SDKPermissionDenial[];
        }
      | {
          type: 'result';
          subtype: 'error_max_turns' | 'error_during_execution';
          uuid: UUID;
          session_id: string;
          duration_ms: number;
          duration_api_ms: number;
          is_error: boolean;
          num_turns: number;
          total_cost_usd: number;
          usage: NonNullableUsage;
          permission_denials: SDKPermissionDenial[];
        }

    SDKSystemMessage

    System initialization message.

    type SDKSystemMessage = {
      type: 'system';
      subtype: 'init';
      uuid: UUID;
      session_id: string;
      apiKeySource: ApiKeySource;
      cwd: string;
      tools: string[];
      mcp_servers: {
        name: string;
        status: string;
      }[];
      model: string;
      permissionMode: PermissionMode;
      slash_commands: string[];
      output_style: string;
    }

    SDKPartialAssistantMessage

    Streaming partial message (only when includePartialMessages is true).

    type SDKPartialAssistantMessage = {
      type: 'stream_event';
      event: RawMessageStreamEvent; // From Anthropic SDK
      parent_tool_use_id: string | null;
      uuid: UUID;
      session_id: string;
    }

    SDKCompactBoundaryMessage

    Message indicating a conversation compaction boundary.

    type SDKCompactBoundaryMessage = {
      type: 'system';
      subtype: 'compact_boundary';
      uuid: UUID;
      session_id: string;
      compact_metadata: {
        trigger: 'manual' | 'auto';
        pre_tokens: number;
      };
    }

    SDKPermissionDenial

    Information about a denied tool use.

    type SDKPermissionDenial = {
      tool_name: string;
      tool_use_id: string;
      tool_input: ToolInput;
    }

    Hook Types

    HookEvent

    Available hook events.

    type HookEvent = 
      | 'PreToolUse'
      | 'PostToolUse'
      | 'Notification'
      | 'UserPromptSubmit'
      | 'SessionStart'
      | 'SessionEnd'
      | 'Stop'
      | 'SubagentStop'
      | 'PreCompact';

    HookCallback

    Hook callback function type.

    type HookCallback = (
      input: HookInput, // Union of all hook input types
      toolUseID: string | undefined,
      options: { signal: AbortSignal }
    ) => Promise<HookJSONOutput>;

    HookCallbackMatcher

    Hook configuration with optional matcher.

    interface HookCallbackMatcher {
      matcher?: string;
      hooks: HookCallback[];
    }

    HookInput

    Union type of all hook input types.

    type HookInput = 
      | PreToolUseHookInput
      | PostToolUseHookInput
      | NotificationHookInput
      | UserPromptSubmitHookInput
      | SessionStartHookInput
      | SessionEndHookInput
      | StopHookInput
      | SubagentStopHookInput
      | PreCompactHookInput;

    BaseHookInput

    Base interface that all hook input types extend.

    type BaseHookInput = {
      session_id: string;
      transcript_path: string;
      cwd: string;
      permission_mode?: string;
    }

    PreToolUseHookInput

    type PreToolUseHookInput = BaseHookInput & {
      hook_event_name: 'PreToolUse';
      tool_name: string;
      tool_input: ToolInput;
    }

    PostToolUseHookInput

    type PostToolUseHookInput = BaseHookInput & {
      hook_event_name: 'PostToolUse';
      tool_name: string;
      tool_input: ToolInput;
      tool_response: ToolOutput;
    }

    NotificationHookInput

    type NotificationHookInput = BaseHookInput & {
      hook_event_name: 'Notification';
      message: string;
      title?: string;
    }

    UserPromptSubmitHookInput

    type UserPromptSubmitHookInput = BaseHookInput & {
      hook_event_name: 'UserPromptSubmit';
      prompt: string;
    }

    SessionStartHookInput

    type SessionStartHookInput = BaseHookInput & {
      hook_event_name: 'SessionStart';
      source: 'startup' | 'resume' | 'clear' | 'compact';
    }

    SessionEndHookInput

    type SessionEndHookInput = BaseHookInput & {
      hook_event_name: 'SessionEnd';
      reason: 'clear' | 'logout' | 'prompt_input_exit' | 'other';
    }

    StopHookInput

    type StopHookInput = BaseHookInput & {
      hook_event_name: 'Stop';
      stop_hook_active: boolean;
    }

    SubagentStopHookInput

    type SubagentStopHookInput = BaseHookInput & {
      hook_event_name: 'SubagentStop';
      stop_hook_active: boolean;
    }

    PreCompactHookInput

    type PreCompactHookInput = BaseHookInput & {
      hook_event_name: 'PreCompact';
      trigger: 'manual' | 'auto';
      custom_instructions: string | null;
    }

    HookJSONOutput

    Hook return value.

    type HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput;

    AsyncHookJSONOutput

    type AsyncHookJSONOutput = {
      async: true;
      asyncTimeout?: number;
    }

    SyncHookJSONOutput

    type SyncHookJSONOutput = {
      continue?: boolean;
      suppressOutput?: boolean;
      stopReason?: string;
      decision?: 'approve' | 'block';
      systemMessage?: string;
      reason?: string;
      hookSpecificOutput?:
        | {
            hookEventName: 'PreToolUse';
            permissionDecision?: 'allow' | 'deny' | 'ask';
            permissionDecisionReason?: string;
          }
        | {
            hookEventName: 'UserPromptSubmit';
            additionalContext?: string;
          }
        | {
            hookEventName: 'SessionStart';
            additionalContext?: string;
          }
        | {
            hookEventName: 'PostToolUse';
            additionalContext?: string;
          };
    }

    Tool Input Types

    Documentation of input schemas for all built-in Claude Code tools. These types are exported from @anthropic-ai/claude-agent-sdk and can be used for type-safe tool interactions.

    ToolInput

    Note: This is a documentation-only type for clarity. It represents the union of all tool input types.

    type ToolInput = 
      | AgentInput
      | BashInput
      | BashOutputInput
      | FileEditInput
      | FileReadInput
      | FileWriteInput
      | GlobInput
      | GrepInput
      | KillShellInput
      | NotebookEditInput
      | WebFetchInput
      | WebSearchInput
      | TodoWriteInput
      | ExitPlanModeInput
      | ListMcpResourcesInput
      | ReadMcpResourceInput;

    Task

    Tool name: Task

    interface AgentInput {
      /**
       * A short (3-5 word) description of the task
       */
      description: string;
      /**
       * The task for the agent to perform
       */
      prompt: string;
      /**
       * The type of specialized agent to use for this task
       */
      subagent_type: string;
    }

    Launches a new agent to handle complex, multi-step tasks autonomously.

    Bash

    Tool name: Bash

    interface BashInput {
      /**
       * The command to execute
       */
      command: string;
      /**
       * Optional timeout in milliseconds (max 600000)
       */
      timeout?: number;
      /**
       * Clear, concise description of what this command does in 5-10 words
       */
      description?: string;
      /**
       * Set to true to run this command in the background
       */
      run_in_background?: boolean;
    }

    Executes bash commands in a persistent shell session with optional timeout and background execution.

    BashOutput

    Tool name: BashOutput

    interface BashOutputInput {
      /**
       * The ID of the background shell to retrieve output from
       */
      bash_id: string;
      /**
       * Optional regex to filter output lines
       */
      filter?: string;
    }

    Retrieves output from a running or completed background bash shell.

    Edit

    Tool name: Edit

    interface FileEditInput {
      /**
       * The absolute path to the file to modify
       */
      file_path: string;
      /**
       * The text to replace
       */
      old_string: string;
      /**
       * The text to replace it with (must be different from old_string)
       */
      new_string: string;
      /**
       * Replace all occurrences of old_string (default false)
       */
      replace_all?: boolean;
    }

    Performs exact string replacements in files.

    Read

    Tool name: Read

    interface FileReadInput {
      /**
       * The absolute path to the file to read
       */
      file_path: string;
      /**
       * The line number to start reading from
       */
      offset?: number;
      /**
       * The number of lines to read
       */
      limit?: number;
    }

    Reads files from the local filesystem, including text, images, PDFs, and Jupyter notebooks.

    Write

    Tool name: Write

    interface FileWriteInput {
      /**
       * The absolute path to the file to write
       */
      file_path: string;
      /**
       * The content to write to the file
       */
      content: string;
    }

    Writes a file to the local filesystem, overwriting if it exists.

    Glob

    Tool name: Glob

    interface GlobInput {
      /**
       * The glob pattern to match files against
       */
      pattern: string;
      /**
       * The directory to search in (defaults to cwd)
       */
      path?: string;
    }

    Fast file pattern matching that works with any codebase size.

    Grep

    Tool name: Grep

    interface GrepInput {
      /**
       * The regular expression pattern to search for
       */
      pattern: string;
      /**
       * File or directory to search in (defaults to cwd)
       */
      path?: string;
      /**
       * Glob pattern to filter files (e.g. "*.js")
       */
      glob?: string;
      /**
       * File type to search (e.g. "js", "py", "rust")
       */
      type?: string;
      /**
       * Output mode: "content", "files_with_matches", or "count"
       */
      output_mode?: 'content' | 'files_with_matches' | 'count';
      /**
       * Case insensitive search
       */
      '-i'?: boolean;
      /**
       * Show line numbers (for content mode)
       */
      '-n'?: boolean;
      /**
       * Lines to show before each match
       */
      '-B'?: number;
      /**
       * Lines to show after each match
       */
      '-A'?: number;
      /**
       * Lines to show before and after each match
       */
      '-C'?: number;
      /**
       * Limit output to first N lines/entries
       */
      head_limit?: number;
      /**
       * Enable multiline mode
       */
      multiline?: boolean;
    }

    Powerful search tool built on ripgrep with regex support.

    KillBash

    Tool name: KillBash

    interface KillShellInput {
      /**
       * The ID of the background shell to kill
       */
      shell_id: string;
    }

    Kills a running background bash shell by its ID.

    NotebookEdit

    Tool name: NotebookEdit

    interface NotebookEditInput {
      /**
       * The absolute path to the Jupyter notebook file
       */
      notebook_path: string;
      /**
       * The ID of the cell to edit
       */
      cell_id?: string;
      /**
       * The new source for the cell
       */
      new_source: string;
      /**
       * The type of the cell (code or markdown)
       */
      cell_type?: 'code' | 'markdown';
      /**
       * The type of edit (replace, insert, delete)
       */
      edit_mode?: 'replace' | 'insert' | 'delete';
    }

    Edits cells in Jupyter notebook files.

    WebFetch

    Tool name: WebFetch

    interface WebFetchInput {
      /**
       * The URL to fetch content from
       */
      url: string;
      /**
       * The prompt to run on the fetched content
       */
      prompt: string;
    }

    Fetches content from a URL and processes it with an AI model.

    WebSearch

    Tool name: WebSearch

    interface WebSearchInput {
      /**
       * The search query to use
       */
      query: string;
      /**
       * Only include results from these domains
       */
      allowed_domains?: string[];
      /**
       * Never include results from these domains
       */
      blocked_domains?: string[];
    }

    Searches the web and returns formatted results.

    TodoWrite

    Tool name: TodoWrite

    interface TodoWriteInput {
      /**
       * The updated todo list
       */
      todos: Array<{
        /**
         * The task description
         */
        content: string;
        /**
         * The task status
         */
        status: 'pending' | 'in_progress' | 'completed';
        /**
         * Active form of the task description
         */
        activeForm: string;
      }>;
    }

    Creates and manages a structured task list for tracking progress.

    ExitPlanMode

    Tool name: ExitPlanMode

    interface ExitPlanModeInput {
      /**
       * The plan to run by the user for approval
       */
      plan: string;
    }

    Exits planning mode and prompts the user to approve the plan.

    ListMcpResources

    Tool name: ListMcpResources

    interface ListMcpResourcesInput {
      /**
       * Optional server name to filter resources by
       */
      server?: string;
    }

    Lists available MCP resources from connected servers.

    ReadMcpResource

    Tool name: ReadMcpResource

    interface ReadMcpResourceInput {
      /**
       * The MCP server name
       */
      server: string;
      /**
       * The resource URI to read
       */
      uri: string;
    }

    Reads a specific MCP resource from a server.

    Tool Output Types

    Documentation of output schemas for all built-in Claude Code tools. These types represent the actual response data returned by each tool.

    ToolOutput

    Note: This is a documentation-only type for clarity. It represents the union of all tool output types.

    type ToolOutput = 
      | TaskOutput
      | BashOutput
      | BashOutputToolOutput
      | EditOutput
      | ReadOutput
      | WriteOutput
      | GlobOutput
      | GrepOutput
      | KillBashOutput
      | NotebookEditOutput
      | WebFetchOutput
      | WebSearchOutput
      | TodoWriteOutput
      | ExitPlanModeOutput
      | ListMcpResourcesOutput
      | ReadMcpResourceOutput;

    Task

    Tool name: Task

    interface TaskOutput {
      /**
       * Final result message from the subagent
       */
      result: string;
      /**
       * Token usage statistics
       */
      usage?: {
        input_tokens: number;
        output_tokens: number;
        cache_creation_input_tokens?: number;
        cache_read_input_tokens?: number;
      };
      /**
       * Total cost in USD
       */
      total_cost_usd?: number;
      /**
       * Execution duration in milliseconds
       */
      duration_ms?: number;
    }

    Returns the final result from the subagent after completing the delegated task.

    Bash

    Tool name: Bash

    interface BashOutput {
      /**
       * Combined stdout and stderr output
       */
      output: string;
      /**
       * Exit code of the command
       */
      exitCode: number;
      /**
       * Whether the command was killed due to timeout
       */
      killed?: boolean;
      /**
       * Shell ID for background processes
       */
      shellId?: string;
    }

    Returns command output with exit status. Background commands return immediately with a shellId.

    BashOutput

    Tool name: BashOutput

    interface BashOutputToolOutput {
      /**
       * New output since last check
       */
      output: string;
      /**
       * Current shell status
       */
      status: 'running' | 'completed' | 'failed';
      /**
       * Exit code (when completed)
       */
      exitCode?: number;
    }

    Returns incremental output from background shells.

    Edit

    Tool name: Edit

    interface EditOutput {
      /**
       * Confirmation message
       */
      message: string;
      /**
       * Number of replacements made
       */
      replacements: number;
      /**
       * File path that was edited
       */
      file_path: string;
    }

    Returns confirmation of successful edits with replacement count.

    Read

    Tool name: Read

    type ReadOutput = 
      | TextFileOutput
      | ImageFileOutput
      | PDFFileOutput
      | NotebookFileOutput;
    
    interface TextFileOutput {
      /**
       * File contents with line numbers
       */
      content: string;
      /**
       * Total number of lines in file
       */
      total_lines: number;
      /**
       * Lines actually returned
       */
      lines_returned: number;
    }
    
    interface ImageFileOutput {
      /**
       * Base64 encoded image data
       */
      image: string;
      /**
       * Image MIME type
       */
      mime_type: string;
      /**
       * File size in bytes
       */
      file_size: number;
    }
    
    interface PDFFileOutput {
      /**
       * Array of page contents
       */
      pages: Array<{
        page_number: number;
        text?: string;
        images?: Array<{
          image: string;
          mime_type: string;
        }>;
      }>;
      /**
       * Total number of pages
       */
      total_pages: number;
    }
    
    interface NotebookFileOutput {
      /**
       * Jupyter notebook cells
       */
      cells: Array<{
        cell_type: 'code' | 'markdown';
        source: string;
        outputs?: any[];
        execution_count?: number;
      }>;
      /**
       * Notebook metadata
       */
      metadata?: Record<string, any>;
    }

    Returns file contents in format appropriate to file type.

    Write

    Tool name: Write

    interface WriteOutput {
      /**
       * Success message
       */
      message: string;
      /**
       * Number of bytes written
       */
      bytes_written: number;
      /**
       * File path that was written
       */
      file_path: string;
    }

    Returns confirmation after successfully writing the file.

    Glob

    Tool name: Glob

    interface GlobOutput {
      /**
       * Array of matching file paths
       */
      matches: string[];
      /**
       * Number of matches found
       */
      count: number;
      /**
       * Search directory used
       */
      search_path: string;
    }

    Returns file paths matching the glob pattern, sorted by modification time.

    Grep

    Tool name: Grep

    type GrepOutput = 
      | GrepContentOutput
      | GrepFilesOutput
      | GrepCountOutput;
    
    interface GrepContentOutput {
      /**
       * Matching lines with context
       */
      matches: Array<{
        file: string;
        line_number?: number;
        line: string;
        before_context?: string[];
        after_context?: string[];
      }>;
      /**
       * Total number of matches
       */
      total_matches: number;
    }
    
    interface GrepFilesOutput {
      /**
       * Files containing matches
       */
      files: string[];
      /**
       * Number of files with matches
       */
      count: number;
    }
    
    interface GrepCountOutput {
      /**
       * Match counts per file
       */
      counts: Array<{
        file: string;
        count: number;
      }>;
      /**
       * Total matches across all files
       */
      total: number;
    }

    Returns search results in the format specified by output_mode.

    KillBash

    Tool name: KillBash

    interface KillBashOutput {
      /**
       * Success message
       */
      message: string;
      /**
       * ID of the killed shell
       */
      shell_id: string;
    }

    Returns confirmation after terminating the background shell.

    NotebookEdit

    Tool name: NotebookEdit

    interface NotebookEditOutput {
      /**
       * Success message
       */
      message: string;
      /**
       * Type of edit performed
       */
      edit_type: 'replaced' | 'inserted' | 'deleted';
      /**
       * Cell ID that was affected
       */
      cell_id?: string;
      /**
       * Total cells in notebook after edit
       */
      total_cells: number;
    }

    Returns confirmation after modifying the Jupyter notebook.

    WebFetch

    Tool name: WebFetch

    interface WebFetchOutput {
      /**
       * AI model's response to the prompt
       */
      response: string;
      /**
       * URL that was fetched
       */
      url: string;
      /**
       * Final URL after redirects
       */
      final_url?: string;
      /**
       * HTTP status code
       */
      status_code?: number;
    }

    Returns the AI's analysis of the fetched web content.

    WebSearch

    Tool name: WebSearch

    interface WebSearchOutput {
      /**
       * Search results
       */
      results: Array<{
        title: string;
        url: string;
        snippet: string;
        /**
         * Additional metadata if available
         */
        metadata?: Record<string, any>;
      }>;
      /**
       * Total number of results
       */
      total_results: number;
      /**
       * The query that was searched
       */
      query: string;
    }

    Returns formatted search results from the web.

    TodoWrite

    Tool name: TodoWrite

    interface TodoWriteOutput {
      /**
       * Success message
       */
      message: string;
      /**
       * Current todo statistics
       */
      stats: {
        total: number;
        pending: number;
        in_progress: number;
        completed: number;
      };
    }

    Returns confirmation with current task statistics.

    ExitPlanMode

    Tool name: ExitPlanMode

    interface ExitPlanModeOutput {
      /**
       * Confirmation message
       */
      message: string;
      /**
       * Whether user approved the plan
       */
      approved?: boolean;
    }

    Returns confirmation after exiting plan mode.

    ListMcpResources

    Tool name: ListMcpResources

    interface ListMcpResourcesOutput {
      /**
       * Available resources
       */
      resources: Array<{
        uri: string;
        name: string;
        description?: string;
        mimeType?: string;
        server: string;
      }>;
      /**
       * Total number of resources
       */
      total: number;
    }

    Returns list of available MCP resources.

    ReadMcpResource

    Tool name: ReadMcpResource

    interface ReadMcpResourceOutput {
      /**
       * Resource contents
       */
      contents: Array<{
        uri: string;
        mimeType?: string;
        text?: string;
        blob?: string;
      }>;
      /**
       * Server that provided the resource
       */
      server: string;
    }

    Returns the contents of the requested MCP resource.

    Permission Types

    PermissionUpdate

    Operations for updating permissions.

    type PermissionUpdate = 
      | {
          type: 'addRules';
          rules: PermissionRuleValue[];
          behavior: PermissionBehavior;
          destination: PermissionUpdateDestination;
        }
      | {
          type: 'replaceRules';
          rules: PermissionRuleValue[];
          behavior: PermissionBehavior;
          destination: PermissionUpdateDestination;
        }
      | {
          type: 'removeRules';
          rules: PermissionRuleValue[];
          behavior: PermissionBehavior;
          destination: PermissionUpdateDestination;
        }
      | {
          type: 'setMode';
          mode: PermissionMode;
          destination: PermissionUpdateDestination;
        }
      | {
          type: 'addDirectories';
          directories: string[];
          destination: PermissionUpdateDestination;
        }
      | {
          type: 'removeDirectories';
          directories: string[];
          destination: PermissionUpdateDestination;
        }

    PermissionBehavior

    type PermissionBehavior = 'allow' | 'deny' | 'ask';

    PermissionUpdateDestination

    type PermissionUpdateDestination = 
      | 'userSettings'     // Global user settings
      | 'projectSettings'  // Per-directory project settings
      | 'localSettings'    // Gitignored local settings
      | 'session'          // Current session only

    PermissionRuleValue

    type PermissionRuleValue = {
      toolName: string;
      ruleContent?: string;
    }

    Other Types

    ApiKeySource

    type ApiKeySource = 'user' | 'project' | 'org' | 'temporary';

    ConfigScope

    type ConfigScope = 'local' | 'user' | 'project';

    NonNullableUsage

    A version of Usage with all nullable fields made non-nullable.

    type NonNullableUsage = {
      [K in keyof Usage]: NonNullable<Usage[K]>;
    }

    Usage

    Token usage statistics (from @anthropic-ai/sdk).

    type Usage = {
      input_tokens: number | null;
      output_tokens: number | null;
      cache_creation_input_tokens?: number | null;
      cache_read_input_tokens?: number | null;
    }

    CallToolResult

    MCP tool result type (from @modelcontextprotocol/sdk/types.js).

    type CallToolResult = {
      content: Array<{
        type: 'text' | 'image' | 'resource';
        // Additional fields vary by type
      }>;
      isError?: boolean;
    }

    AbortError

    Custom error class for abort operations.

    class AbortError extends Error {}

    See also

    • SDK overview - General SDK concepts
    • Python SDK reference - Python SDK documentation
    • CLI reference - Command-line interface
    • Common workflows - Step-by-step guides
      © 2025 ANTHROPIC PBC

      Products

      • Claude
      • Claude Code
      • Max plan
      • Team plan
      • Enterprise plan
      • Download app
      • Pricing
      • Log in

      Features

      • Claude and Slack
      • Claude in Excel

      Models

      • Opus
      • Sonnet
      • Haiku

      Solutions

      • AI agents
      • Code modernization
      • Coding
      • Customer support
      • Education
      • Financial services
      • Government
      • Life sciences

      Claude Developer Platform

      • Overview
      • Developer docs
      • Pricing
      • Amazon Bedrock
      • Google Cloud’s Vertex AI
      • Console login

      Learn

      • Blog
      • Catalog
      • Courses
      • Use cases
      • Connectors
      • Customer stories
      • Engineering at Anthropic
      • Events
      • Powered by Claude
      • Service partners
      • Startups program

      Company

      • Anthropic
      • Careers
      • Economic Futures
      • Research
      • News
      • Responsible Scaling Policy
      • Security and compliance
      • Transparency

      Help and security

      • Availability
      • Status
      • Support center

      Terms and policies

      • Privacy policy
      • Responsible disclosure policy
      • Terms of service: Commercial
      • Terms of service: Consumer
      • Usage policy

      Products

      • Claude
      • Claude Code
      • Max plan
      • Team plan
      • Enterprise plan
      • Download app
      • Pricing
      • Log in

      Features

      • Claude and Slack
      • Claude in Excel

      Models

      • Opus
      • Sonnet
      • Haiku

      Solutions

      • AI agents
      • Code modernization
      • Coding
      • Customer support
      • Education
      • Financial services
      • Government
      • Life sciences

      Claude Developer Platform

      • Overview
      • Developer docs
      • Pricing
      • Amazon Bedrock
      • Google Cloud’s Vertex AI
      • Console login

      Learn

      • Blog
      • Catalog
      • Courses
      • Use cases
      • Connectors
      • Customer stories
      • Engineering at Anthropic
      • Events
      • Powered by Claude
      • Service partners
      • Startups program

      Company

      • Anthropic
      • Careers
      • Economic Futures
      • Research
      • News
      • Responsible Scaling Policy
      • Security and compliance
      • Transparency

      Help and security

      • Availability
      • Status
      • Support center

      Terms and policies

      • Privacy policy
      • Responsible disclosure policy
      • Terms of service: Commercial
      • Terms of service: Consumer
      • Usage policy
      © 2025 ANTHROPIC PBC