Loading...
    • 개발자 가이드
    • API 참조
    • MCP
    • 리소스
    • 릴리스 노트
    Search...
    ⌘K
    첫 단계
    Claude 소개빠른 시작
    모델 및 가격
    모델 개요모델 선택Claude 4.5의 새로운 기능Claude 4.5로 마이그레이션모델 지원 중단가격
    Claude로 구축
    기능 개요Messages API 사용컨텍스트 윈도우프롬프트 작성 모범 사례
    기능
    프롬프트 캐싱컨텍스트 편집확장 사고노력메시지 스트리밍배치 처리인용다국어 지원토큰 계산임베딩비전PDF 지원Files API검색 결과구조화된 출력
    도구
    개요도구 사용 구현 방법세분화된 도구 스트리밍Bash 도구코드 실행 도구프로그래밍 방식 도구 호출컴퓨터 사용 도구텍스트 편집기 도구웹 가져오기 도구웹 검색 도구메모리 도구도구 검색 도구
    에이전트 스킬
    개요빠른 시작모범 사례API와 함께 스킬 사용
    에이전트 SDK
    개요빠른 시작TypeScript SDKTypeScript V2 (미리보기)Python SDK마이그레이션 가이드
    API의 MCP
    MCP 커넥터원격 MCP 서버
    타사 플랫폼의 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    프롬프트 엔지니어링
    개요프롬프트 생성기프롬프트 템플릿 사용프롬프트 개선기명확하고 직접적으로예제 사용 (다중 샷 프롬프팅)Claude가 생각하도록 하기 (CoT)XML 태그 사용Claude에게 역할 부여 (시스템 프롬프트)Claude의 응답 미리 채우기복잡한 프롬프트 연결긴 컨텍스트 팁확장 사고 팁
    테스트 및 평가
    성공 기준 정의테스트 케이스 개발평가 도구 사용지연 시간 감소
    가드레일 강화
    환각 감소출력 일관성 증가탈옥 완화거부 스트리밍프롬프트 유출 감소Claude를 캐릭터로 유지
    관리 및 모니터링
    Admin API 개요사용량 및 비용 APIClaude Code Analytics API
    Console
    Log in
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...

    Solutions

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

    Partners

    • Amazon Bedrock
    • Google Cloud's Vertex AI

    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

    Learn

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

    Help and security

    • Availability
    • Status
    • Support
    • Discord

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    에이전트 SDK

    Agent SDK 참고 자료 - TypeScript

    TypeScript Agent SDK의 완전한 API 참고 자료로, 모든 함수, 타입 및 인터페이스를 포함합니다.

    새로운 V2 인터페이스 시도 (미리보기): send() 및 receive() 패턴을 사용한 간소화된 인터페이스가 이제 사용 가능하며, 다중 턴 대화를 더 쉽게 만듭니다. 자세히 알아보기

    설치

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

    함수

    query()

    Claude Code와 상호작용하기 위한 주요 함수입니다. 메시지가 도착할 때 스트리밍하는 비동기 생성기를 만듭니다.

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

    매개변수

    매개변수타입설명
    promptstring | AsyncIterable<SDKUserMessage>문자열 또는 스트리밍 모드용 비동기 반복 가능 객체로서의 입력 프롬프트
    optionsOptions선택적 구성 객체 (아래 Options 타입 참조)

    반환값

    추가 메서드가 있는 Query 객체를 반환하며, AsyncGenerator<SDKMessage, void>를 확장합니다.

    tool()

    SDK MCP 서버와 함께 사용할 타입 안전 MCP 도구 정의를 만듭니다.

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

    매개변수

    매개변수타입설명
    namestring도구의 이름
    descriptionstring도구가 수행하는 작업에 대한 설명
    inputSchemaSchema extends ZodRawShape도구의 입력 매개변수를 정의하는 Zod 스키마
    handler(args, extra) => Promise<CallToolResult>도구 로직을 실행하는 비동기 함수

    createSdkMcpServer()

    애플리케이션과 동일한 프로세스에서 실행되는 MCP 서버 인스턴스를 만듭니다.

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

    매개변수

    매개변수타입설명
    options.namestringMCP 서버의 이름
    options.versionstring선택적 버전 문자열
    options.toolsArray<SdkMcpToolDefinition>tool()로 생성된 도구 정의 배열

    타입

    Options

    query() 함수의 구성 객체입니다.

    속성타입기본값설명
    abortControllerAbortControllernew AbortController()작업 취소를 위한 컨트롤러
    additionalDirectoriesstring[][]Claude가 접근할 수 있는 추가 디렉토리
    agentsRecord<string, [AgentDefinition](#agentdefinition)>undefined프로그래밍 방식으로 서브에이전트 정의
    allowDangerouslySkipPermissionsbooleanfalse권한 우회 활성화. permissionMode: 'bypassPermissions'를 사용할 때 필수
    allowedToolsstring[]모든 도구허용된 도구 이름 목록
    betasSdkBeta[][]베타 기능 활성화 (예: ['context-1m-2025-08-07'])
    canUseToolCanUseToolundefined도구 사용을 위한 사용자 정의 권한 함수
    continuebooleanfalse가장 최근 대화 계속
    cwdstringprocess.cwd()현재 작업 디렉토리
    disallowedToolsstring[][]허용되지 않는 도구 이름 목록
    enableFileCheckpointingbooleanfalse되감기를 위한 파일 변경 추적 활성화. 파일 체크포인팅 참조
    envDict<string>process.env환경 변수
    executable'bun' | 'deno' | 'node'자동 감지사용할 JavaScript 런타임
    executableArgsstring[][]실행 파일에 전달할 인수
    extraArgsRecord<string, string | null>{}추가 인수
    fallbackModelstringundefined주 모델이 실패할 경우 사용할 모델
    forkSessionbooleanfalseresume으로 재개할 때 원래 세션을 계속하는 대신 새 세션 ID로 포크
    hooksPartial<Record<HookEvent, HookCallbackMatcher[]>>{}이벤트에 대한 후크 콜백
    includePartialMessagesbooleanfalse부분 메시지 이벤트 포함
    maxBudgetUsdnumberundefined쿼리의 최대 예산 (USD)
    maxThinkingTokensnumberundefined사고 프로세스의 최대 토큰
    maxTurnsnumberundefined최대 대화 턴
    mcpServersRecord<string, [McpServerConfig](#mcpserverconfig)>{}MCP 서버 구성
    modelstringCLI의 기본값사용할 Claude 모델
    outputFormat{ type: 'json_schema', schema: JSONSchema }undefined에이전트 결과의 출력 형식 정의. 자세한 내용은 구조화된 출력 참조
    pathToClaudeCodeExecutablestring기본 제공 실행 파일 사용Claude Code 실행 파일의 경로
    permissionModePermissionMode'default'세션의 권한 모드
    permissionPromptToolNamestringundefined권한 프롬프트용 MCP 도구 이름
    pluginsSdkPluginConfig[][]로컬 경로에서 사용자 정의 플러그인 로드. 자세한 내용은 플러그인 참조
    resumestringundefined재개할 세션 ID
    resumeSessionAtstringundefined특정 메시지 UUID에서 세션 재개
    sandboxSandboxSettingsundefined프로그래밍 방식으로 샌드박스 동작 구성. 자세한 내용은 샌드박스 설정 참조
    settingSourcesSettingSource[][] (설정 없음)로드할 파일 시스템 설정 제어. 생략하면 설정이 로드되지 않습니다. 참고: CLAUDE.md 파일을 로드하려면 'project'를 포함해야 합니다
    stderr(data: string) => voidundefinedstderr 출력에 대한 콜백
    strictMcpConfigbooleanfalse엄격한 MCP 검증 적용
    systemPromptstring | { type: 'preset'; preset: 'claude_code'; append?: string }undefined (빈 프롬프트)시스템 프롬프트 구성. 사용자 정의 프롬프트의 경우 문자열을 전달하거나, Claude Code의 시스템 프롬프트를 사용하려면 { type: 'preset', preset: 'claude_code' }를 전달합니다. 프리셋 객체 형식을 사용할 때 append를 추가하여 추가 지침으로 시스템 프롬프트 확장
    toolsstring[] | { type: 'preset'; preset: 'claude_code' }undefined도구 구성. 도구 이름 배열을 전달하거나 프리셋을 사용하여 Claude Code의 기본 도구 가져오기

    Query

    query() 함수에서 반환된 인터페이스입니다.

    interface Query extends AsyncGenerator<SDKMessage, void> {
      interrupt(): Promise<void>;
      rewindFiles(userMessageUuid: string): Promise<void>;
      setPermissionMode(mode: PermissionMode): Promise<void>;
      setModel(model?: string): Promise<void>;
      setMaxThinkingTokens(maxThinkingTokens: number | null): Promise<void>;
      supportedCommands(): Promise<SlashCommand[]>;
      supportedModels(): Promise<ModelInfo[]>;
      mcpServerStatus(): Promise<McpServerStatus[]>;
      accountInfo(): Promise<AccountInfo>;
    }

    메서드

    메서드설명
    interrupt()쿼리 중단 (스트리밍 입력 모드에서만 사용 가능)
    rewindFiles(userMessageUuid)파일을 지정된 사용자 메시지의 상태로 복원합니다. enableFileCheckpointing: true가 필요합니다. 파일 체크포인팅 참조
    setPermissionMode()권한 모드 변경 (스트리밍 입력 모드에서만 사용 가능)
    setModel()모델 변경 (스트리밍 입력 모드에서만 사용 가능)
    setMaxThinkingTokens()최대 사고 토큰 변경 (스트리밍 입력 모드에서만 사용 가능)
    supportedCommands()사용 가능한 슬래시 명령 반환
    supportedModels()표시 정보가 있는 사용 가능한 모델 반환
    mcpServerStatus()연결된 MCP 서버의 상태 반환
    accountInfo()계정 정보 반환

    AgentDefinition

    프로그래밍 방식으로 정의된 서브에이전트의 구성입니다.

    type AgentDefinition = {
      description: string;
      tools?: string[];
      prompt: string;
      model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
    }
    필드필수설명
    description예이 에이전트를 사용할 시기에 대한 자연어 설명
    tools아니오허용된 도구 이름 배열. 생략하면 모든 도구를 상속합니다
    prompt예에이전트의 시스템 프롬프트
    model아니오이 에이전트의 모델 재정의. 생략하면 주 모델을 사용합니다

    SettingSource

    SDK가 로드하는 파일 시스템 기반 구성 소스를 제어합니다.

    type SettingSource = 'user' | 'project' | 'local';
    값설명위치
    'user'전역 사용자 설정~/.claude/settings.json
    'project'공유 프로젝트 설정 (버전 제어됨).claude/settings.json
    'local'로컬 프로젝트 설정 (gitignored).claude/settings.local.json

    기본 동작

    settingSources가 생략되거나 undefined일 때, SDK는 파일 시스템 설정을 로드하지 않습니다. 이는 SDK 애플리케이션에 대한 격리를 제공합니다.

    settingSources를 사용하는 이유는 무엇입니까?

    모든 파일 시스템 설정 로드 (레거시 동작):

    // SDK v0.0.x처럼 모든 설정 로드
    const result = query({
      prompt: "이 코드를 분석하세요",
      options: {
        settingSources: ['user', 'project', 'local']  // 모든 설정 로드
      }
    });

    특정 설정 소스만 로드:

    // 프로젝트 설정만 로드, 사용자 및 로컬 무시
    const result = query({
      prompt: "CI 검사 실행",
      options: {
        settingSources: ['project']  // .claude/settings.json만
      }
    });

    테스트 및 CI 환경:

    // 로컬 설정을 제외하여 CI에서 일관된 동작 보장
    const result = query({
      prompt: "테스트 실행",
      options: {
        settingSources: ['project'],  // 팀 공유 설정만
        permissionMode: 'bypassPermissions'
      }
    });

    SDK 전용 애플리케이션:

    // 모든 것을 프로그래밍 방식으로 정의 (기본 동작)
    // 파일 시스템 종속성 없음 - settingSources는 기본값이 []
    const result = query({
      prompt: "이 PR을 검토하세요",
      options: {
        // settingSources: []는 기본값이므로 지정할 필요 없음
        agents: { /* ... */ },
        mcpServers: { /* ... */ },
        allowedTools: ['Read', 'Grep', 'Glob']
      }
    });

    CLAUDE.md 프로젝트 지침 로드:

    // 프로젝트 설정을 로드하여 CLAUDE.md 파일 포함
    const result = query({
      prompt: "프로젝트 규칙에 따라 새 기능 추가",
      options: {
        systemPrompt: {
          type: 'preset',
          preset: 'claude_code'  // CLAUDE.md를 사용하려면 필수
        },
        settingSources: ['project'],  // 프로젝트 디렉토리에서 CLAUDE.md 로드
        allowedTools: ['Read', 'Write', 'Edit']
      }
    });

    설정 우선순위

    여러 소스가 로드될 때, 설정은 이 우선순위(높음에서 낮음)로 병합됩니다:

    1. 로컬 설정 (.claude/settings.local.json)
    2. 프로젝트 설정 (.claude/settings.json)
    3. 사용자 설정 (~/.claude/settings.json)

    프로그래밍 방식 옵션 (agents, allowedTools 등)은 항상 파일 시스템 설정을 재정의합니다.

    PermissionMode

    type PermissionMode =
      | 'default'           // 표준 권한 동작
      | 'acceptEdits'       // 파일 편집 자동 수락
      | 'bypassPermissions' // 모든 권한 검사 우회
      | 'plan'              // 계획 모드 - 실행 없음

    CanUseTool

    도구 사용을 제어하기 위한 사용자 정의 권한 함수 타입입니다.

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

    PermissionResult

    권한 검사의 결과입니다.

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

    McpServerConfig

    MCP 서버의 구성입니다.

    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

    SDK에서 플러그인을 로드하기 위한 구성입니다.

    type SdkPluginConfig = {
      type: 'local';
      path: string;
    }
    필드타입설명
    type'local''local'이어야 합니다 (현재 로컬 플러그인만 지원됨)
    pathstring플러그인 디렉토리의 절대 또는 상대 경로

    예시:

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

    플러그인 생성 및 사용에 대한 완전한 정보는 플러그인을 참조하세요.

    메시지 타입

    SDKMessage

    쿼리에서 반환된 모든 가능한 메시지의 합집합 타입입니다.

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

    SDKAssistantMessage

    어시스턴트 응답 메시지입니다.

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

    SDKUserMessage

    사용자 입력 메시지입니다.

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

    SDKUserMessageReplay

    필수 UUID가 있는 재생된 사용자 메시지입니다.

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

    SDKResultMessage

    최종 결과 메시지입니다.

    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;
          modelUsage: { [modelName: string]: ModelUsage };
          permission_denials: SDKPermissionDenial[];
          structured_output?: unknown;
        }
      | {
          type: 'result';
          subtype:
            | 'error_max_turns'
            | 'error_during_execution'
            | 'error_max_budget_usd'
            | 'error_max_structured_output_retries';
          uuid: UUID;
          session_id: string;
          duration_ms: number;
          duration_api_ms: number;
          is_error: boolean;
          num_turns: number;
          total_cost_usd: number;
          usage: NonNullableUsage;
          modelUsage: { [modelName: string]: ModelUsage };
          permission_denials: SDKPermissionDenial[];
          errors: string[];
        }

    SDKSystemMessage

    시스템 초기화 메시지입니다.

    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

    스트리밍 부분 메시지 (includePartialMessages가 true일 때만).

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

    SDKCompactBoundaryMessage

    대화 압축 경계를 나타내는 메시지입니다.

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

    SDKPermissionDenial

    거부된 도구 사용에 대한 정보입니다.

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

    후크 타입

    후크 사용에 대한 포괄적인 가이드, 예시 및 일반적인 패턴은 후크 가이드를 참조하세요.

    HookEvent

    사용 가능한 후크 이벤트입니다.

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

    HookCallback

    후크 콜백 함수 타입입니다.

    type HookCallback = (
      input: HookInput, // 모든 후크 입력 타입의 합집합
      toolUseID: string | undefined,
      options: { signal: AbortSignal }
    ) => Promise<HookJSONOutput>;

    HookCallbackMatcher

    선택적 매처가 있는 후크 구성입니다.

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

    HookInput

    모든 후크 입력 타입의 합집합 타입입니다.

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

    BaseHookInput

    모든 후크 입력 타입이 확장하는 기본 인터페이스입니다.

    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: unknown;
    }

    PostToolUseHookInput

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

    PostToolUseFailureHookInput

    type PostToolUseFailureHookInput = BaseHookInput & {
      hook_event_name: 'PostToolUseFailure';
      tool_name: string;
      tool_input: unknown;
      error: string;
      is_interrupt?: boolean;
    }

    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: ExitReason;  // EXIT_REASONS 배열의 문자열
    }

    StopHookInput

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

    SubagentStartHookInput

    type SubagentStartHookInput = BaseHookInput & {
      hook_event_name: 'SubagentStart';
      agent_id: string;
      agent_type: string;
    }

    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;
    }

    PermissionRequestHookInput

    type PermissionRequestHookInput = BaseHookInput & {
      hook_event_name: 'PermissionRequest';
      tool_name: string;
      tool_input: unknown;
      permission_suggestions?: PermissionUpdate[];
    }

    HookJSONOutput

    후크 반환값입니다.

    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;
            updatedInput?: Record<string, unknown>;
          }
        | {
            hookEventName: 'UserPromptSubmit';
            additionalContext?: string;
          }
        | {
            hookEventName: 'SessionStart';
            additionalContext?: string;
          }
        | {
            hookEventName: 'PostToolUse';
            additionalContext?: string;
          };
    }

    도구 입력 타입

    모든 기본 제공 Claude Code 도구의 입력 스키마 문서입니다. 이러한 타입은 @anthropic-ai/claude-agent-sdk에서 내보내지며 타입 안전 도구 상호작용에 사용할 수 있습니다.

    ToolInput

    참고: 이것은 명확성을 위한 문서 전용 타입입니다. 모든 도구 입력 타입의 합집합을 나타냅니다.

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

    Task

    도구 이름: Task

    interface AgentInput {
      /**
       * 작업의 짧은 설명 (3-5 단어)
       */
      description: string;
      /**
       * 에이전트가 수행할 작업
       */
      prompt: string;
      /**
       * 이 작업에 사용할 특화된 에이전트의 유형
       */
      subagent_type: string;
    }

    복잡한 다단계 작업을 자율적으로 처리할 새로운 에이전트를 시작합니다.

    AskUserQuestion

    도구 이름: AskUserQuestion

    interface AskUserQuestionInput {
      /**
       * 사용자에게 물어볼 질문 (1-4개 질문)
       */
      questions: Array<{
        /**
         * 사용자에게 물어볼 완전한 질문입니다. 명확하고 구체적이어야 하며
         * 물음표로 끝나야 합니다.
         */
        question: string;
        /**
         * 칩/태그로 표시되는 매우 짧은 레이블 (최대 12자).
         * 예: "Auth method", "Library", "Approach"
         */
        header: string;
        /**
         * 사용 가능한 선택 (2-4개 옵션). "Other" 옵션은
         * 자동으로 제공됩니다.
         */
        options: Array<{
          /**
           * 이 옵션의 표시 텍스트 (1-5 단어)
           */
          label: string;
          /**
           * 이 옵션이 의미하는 것에 대한 설명
           */
          description: string;
        }>;
        /**
         * 여러 선택을 허용하려면 true로 설정
         */
        multiSelect: boolean;
      }>;
      /**
       * 권한 시스템에서 채워진 사용자 답변입니다.
       * 질문 텍스트를 선택된 옵션 레이블에 매핑합니다.
       * 다중 선택 답변은 쉼표로 구분됩니다.
       */
      answers?: Record<string, string>;
    }

    실행 중에 사용자에게 명확히 하는 질문을 합니다. 사용 세부 정보는 AskUserQuestion 도구 처리를 참조하세요.

    Bash

    도구 이름: Bash

    interface BashInput {
      /**
       * 실행할 명령
       */
      command: string;
      /**
       * 선택적 시간 제한 (밀리초, 최대 600000)
       */
      timeout?: number;
      /**
       * 이 명령이 5-10 단어로 수행하는 작업에 대한 명확하고 간결한 설명
       */
      description?: string;
      /**
       * 이 명령을 백그라운드에서 실행하려면 true로 설정
       */
      run_in_background?: boolean;
    }

    선택적 시간 제한 및 백그라운드 실행을 사용하여 지속적인 셸 세션에서 bash 명령을 실행합니다.

    BashOutput

    도구 이름: BashOutput

    interface BashOutputInput {
      /**
       * 출력을 검색할 백그라운드 셸의 ID
       */
      bash_id: string;
      /**
       * 출력 라인을 필터링하기 위한 선택적 정규식
       */
      filter?: string;
    }

    실행 중이거나 완료된 백그라운드 bash 셸에서 출력을 검색합니다.

    Edit

    도구 이름: Edit

    interface FileEditInput {
      /**
       * 수정할 파일의 절대 경로
       */
      file_path: string;
      /**
       * 바꿀 텍스트
       */
      old_string: string;
      /**
       * 바꿀 텍스트 (old_string과 달라야 함)
       */
      new_string: string;
      /**
       * old_string의 모든 발생을 바꿈 (기본값 false)
       */
      replace_all?: boolean;
    }

    파일에서 정확한 문자열 교체를 수행합니다.

    Read

    도구 이름: Read

    interface FileReadInput {
      /**
       * 읽을 파일의 절대 경로
       */
      file_path: string;
      /**
       * 읽기를 시작할 라인 번호
       */
      offset?: number;
      /**
       * 읽을 라인 수
       */
      limit?: number;
    }

    텍스트, 이미지, PDF 및 Jupyter 노트북을 포함한 로컬 파일 시스템에서 파일을 읽습니다.

    Write

    도구 이름: Write

    interface FileWriteInput {
      /**
       * 쓸 파일의 절대 경로
       */
      file_path: string;
      /**
       * 파일에 쓸 내용
       */
      content: string;
    }

    로컬 파일 시스템에 파일을 쓰고, 존재하면 덮어씁니다.

    Glob

    도구 이름: Glob

    interface GlobInput {
      /**
       * 파일과 일치시킬 glob 패턴
       */
      pattern: string;
      /**
       * 검색할 디렉토리 (기본값 cwd)
       */
      path?: string;
    }

    모든 코드베이스 크기에서 작동하는 빠른 파일 패턴 일치입니다.

    Grep

    도구 이름: Grep

    interface GrepInput {
      /**
       * 검색할 정규식 패턴
       */
      pattern: string;
      /**
       * 검색할 파일 또는 디렉토리 (기본값 cwd)
       */
      path?: string;
      /**
       * 파일을 필터링할 glob 패턴 (예: "*.js")
       */
      glob?: string;
      /**
       * 검색할 파일 타입 (예: "js", "py", "rust")
       */
      type?: string;
      /**
       * 출력 모드: "content", "files_with_matches" 또는 "count"
       */
      output_mode?: 'content' | 'files_with_matches' | 'count';
      /**
       * 대소문자 구분 없는 검색
       */
      '-i'?: boolean;
      /**
       * 라인 번호 표시 (콘텐츠 모드의 경우)
       */
      '-n'?: boolean;
      /**
       * 각 일치 항목 앞에 표시할 라인
       */
      '-B'?: number;
      /**
       * 각 일치 항목 뒤에 표시할 라인
       */
      '-A'?: number;
      /**
       * 각 일치 항목 앞뒤에 표시할 라인
       */
      '-C'?: number;
      /**
       * 출력을 처음 N개 라인/항목으로 제한
       */
      head_limit?: number;
      /**
       * 다중 라인 모드 활성화
       */
      multiline?: boolean;
    }

    정규식 지원이 있는 ripgrep 기반의 강력한 검색 도구입니다.

    KillBash

    도구 이름: KillBash

    interface KillShellInput {
      /**
       * 종료할 백그라운드 셸의 ID
       */
      shell_id: string;
    }

    실행 중인 백그라운드 bash 셸을 ID로 종료합니다.

    NotebookEdit

    도구 이름: NotebookEdit

    interface NotebookEditInput {
      /**
       * 편집할 Jupyter 노트북 파일의 절대 경로
       */
      notebook_path: string;
      /**
       * 편집할 셀의 ID
       */
      cell_id?: string;
      /**
       * 셀의 새로운 소스
       */
      new_source: string;
      /**
       * 셀의 타입 (code 또는 markdown)
       */
      cell_type?: 'code' | 'markdown';
      /**
       * 편집 타입 (replace, insert, delete)
       */
      edit_mode?: 'replace' | 'insert' | 'delete';
    }

    Jupyter 노트북 파일의 셀을 편집합니다.

    WebFetch

    도구 이름: WebFetch

    interface WebFetchInput {
      /**
       * 콘텐츠를 가져올 URL
       */
      url: string;
      /**
       * 가져온 콘텐츠에서 실행할 프롬프트
       */
      prompt: string;
    }

    URL에서 콘텐츠를 가져오고 AI 모델로 처리합니다.

    WebSearch

    도구 이름: WebSearch

    interface WebSearchInput {
      /**
       * 사용할 검색 쿼리
       */
      query: string;
      /**
       * 이 도메인의 결과만 포함
       */
      allowed_domains?: string[];
      /**
       * 이 도메인의 결과는 절대 포함하지 않음
       */
      blocked_domains?: string[];
    }

    웹을 검색하고 형식화된 결과를 반환합니다.

    TodoWrite

    도구 이름: TodoWrite

    interface TodoWriteInput {
      /**
       * 업데이트된 할 일 목록
       */
      todos: Array<{
        /**
         * 작업 설명
         */
        content: string;
        /**
         * 작업 상태
         */
        status: 'pending' | 'in_progress' | 'completed';
        /**
         * 작업 설명의 능동형
         */
        activeForm: string;
      }>;
    }

    진행 상황을 추적하기 위한 구조화된 작업 목록을 만들고 관리합니다.

    ExitPlanMode

    도구 이름: ExitPlanMode

    interface ExitPlanModeInput {
      /**
       * 사용자 승인을 위해 실행할 계획
       */
      plan: string;
    }

    계획 모드를 종료하고 사용자에게 계획 승인을 요청합니다.

    ListMcpResources

    도구 이름: ListMcpResources

    interface ListMcpResourcesInput {
      /**
       * 리소스를 필터링할 선택적 서버 이름
       */
      server?: string;
    }

    연결된 서버의 사용 가능한 MCP 리소스를 나열합니다.

    ReadMcpResource

    도구 이름: ReadMcpResource

    interface ReadMcpResourceInput {
      /**
       * MCP 서버 이름
       */
      server: string;
      /**
       * 읽을 리소스 URI
       */
      uri: string;
    }

    서버에서 특정 MCP 리소스를 읽습니다.

    도구 출력 타입

    모든 기본 제공 Claude Code 도구의 출력 스키마 문서입니다. 이러한 타입은 각 도구에서 반환된 실제 응답 데이터를 나타냅니다.

    ToolOutput

    참고: 이것은 명확성을 위한 문서 전용 타입입니다. 모든 도구 출력 타입의 합집합을 나타냅니다.

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

    Task

    도구 이름: Task

    interface TaskOutput {
      /**
       * 서브에이전트의 최종 결과 메시지
       */
      result: string;
      /**
       * 토큰 사용 통계
       */
      usage?: {
        input_tokens: number;
        output_tokens: number;
        cache_creation_input_tokens?: number;
        cache_read_input_tokens?: number;
      };
      /**
       * USD 단위의 총 비용
       */
      total_cost_usd?: number;
      /**
       * 실행 기간 (밀리초)
       */
      duration_ms?: number;
    }

    위임된 작업을 완료한 후 서브에이전트의 최종 결과를 반환합니다.

    AskUserQuestion

    도구 이름: AskUserQuestion

    interface AskUserQuestionOutput {
      /**
       * 물어본 질문
       */
      questions: Array<{
        question: string;
        header: string;
        options: Array<{
          label: string;
          description: string;
        }>;
        multiSelect: boolean;
      }>;
      /**
       * 사용자가 제공한 답변입니다.
       * 질문 텍스트를 답변 문자열에 매핑합니다.
       * 다중 선택 답변은 쉼표로 구분됩니다.
       */
      answers: Record<string, string>;
    }

    물어본 질문과 사용자의 답변을 반환합니다.

    Bash

    도구 이름: Bash

    interface BashOutput {
      /**
       * 결합된 stdout 및 stderr 출력
       */
      output: string;
      /**
       * 명령의 종료 코드
       */
      exitCode: number;
      /**
       * 시간 제한으로 인해 명령이 종료되었는지 여부
       */
      killed?: boolean;
      /**
       * 백그라운드 프로세스의 셸 ID
       */
      shellId?: string;
    }

    종료 상태와 함께 명령 출력을 반환합니다. 백그라운드 명령은 shellId와 함께 즉시 반환됩니다.

    BashOutput

    도구 이름: BashOutput

    interface BashOutputToolOutput {
      /**
       * 마지막 확인 이후의 새로운 출력
       */
      output: string;
      /**
       * 현재 셸 상태
       */
      status: 'running' | 'completed' | 'failed';
      /**
       * 종료 코드 (완료되었을 때)
       */
      exitCode?: number;
    }

    백그라운드 셸에서 증분 출력을 반환합니다.

    Edit

    도구 이름: Edit

    interface EditOutput {
      /**
       * 확인 메시지
       */
      message: string;
      /**
       * 수행된 교체 수
       */
      replacements: number;
      /**
       * 편집된 파일 경로
       */
      file_path: string;
    }

    성공적인 편집의 확인과 교체 수를 반환합니다.

    Read

    도구 이름: Read

    type ReadOutput = 
      | TextFileOutput
      | ImageFileOutput
      | PDFFileOutput
      | NotebookFileOutput;
    
    interface TextFileOutput {
      /**
       * 줄 번호가 있는 파일 내용
       */
      content: string;
      /**
       * 파일의 총 줄 수
       */
      total_lines: number;
      /**
       * 실제로 반환된 줄 수
       */
      lines_returned: number;
    }
    
    interface ImageFileOutput {
      /**
       * Base64로 인코딩된 이미지 데이터
       */
      image: string;
      /**
       * 이미지 MIME 타입
       */
      mime_type: string;
      /**
       * 파일 크기(바이트)
       */
      file_size: number;
    }
    
    interface PDFFileOutput {
      /**
       * 페이지 내용 배열
       */
      pages: Array<{
        page_number: number;
        text?: string;
        images?: Array<{
          image: string;
          mime_type: string;
        }>;
      }>;
      /**
       * 총 페이지 수
       */
      total_pages: number;
    }
    
    interface NotebookFileOutput {
      /**
       * Jupyter 노트북 셀
       */
      cells: Array<{
        cell_type: 'code' | 'markdown';
        source: string;
        outputs?: any[];
        execution_count?: number;
      }>;
      /**
       * 노트북 메타데이터
       */
      metadata?: Record<string, any>;
    }

    파일 타입에 적합한 형식으로 파일 내용을 반환합니다.

    Write

    도구 이름: Write

    interface WriteOutput {
      /**
       * 성공 메시지
       */
      message: string;
      /**
       * 작성된 바이트 수
       */
      bytes_written: number;
      /**
       * 작성된 파일 경로
       */
      file_path: string;
    }

    파일을 성공적으로 작성한 후 확인을 반환합니다.

    Glob

    도구 이름: Glob

    interface GlobOutput {
      /**
       * 일치하는 파일 경로 배열
       */
      matches: string[];
      /**
       * 찾은 일치 항목 수
       */
      count: number;
      /**
       * 사용된 검색 디렉토리
       */
      search_path: string;
    }

    glob 패턴과 일치하는 파일 경로를 수정 시간 순으로 정렬하여 반환합니다.

    Grep

    도구 이름: Grep

    type GrepOutput = 
      | GrepContentOutput
      | GrepFilesOutput
      | GrepCountOutput;
    
    interface GrepContentOutput {
      /**
       * 컨텍스트가 있는 일치하는 줄
       */
      matches: Array<{
        file: string;
        line_number?: number;
        line: string;
        before_context?: string[];
        after_context?: string[];
      }>;
      /**
       * 총 일치 항목 수
       */
      total_matches: number;
    }
    
    interface GrepFilesOutput {
      /**
       * 일치 항목을 포함하는 파일
       */
      files: string[];
      /**
       * 일치 항목이 있는 파일 수
       */
      count: number;
    }
    
    interface GrepCountOutput {
      /**
       * 파일별 일치 항목 수
       */
      counts: Array<{
        file: string;
        count: number;
      }>;
      /**
       * 모든 파일의 총 일치 항목 수
       */
      total: number;
    }

    output_mode로 지정된 형식의 검색 결과를 반환합니다.

    KillBash

    도구 이름: KillBash

    interface KillBashOutput {
      /**
       * 성공 메시지
       */
      message: string;
      /**
       * 종료된 셸의 ID
       */
      shell_id: string;
    }

    백그라운드 셸을 종료한 후 확인을 반환합니다.

    NotebookEdit

    도구 이름: NotebookEdit

    interface NotebookEditOutput {
      /**
       * 성공 메시지
       */
      message: string;
      /**
       * 수행된 편집의 유형
       */
      edit_type: 'replaced' | 'inserted' | 'deleted';
      /**
       * 영향을 받은 셀 ID
       */
      cell_id?: string;
      /**
       * 편집 후 노트북의 총 셀 수
       */
      total_cells: number;
    }

    Jupyter 노트북을 수정한 후 확인을 반환합니다.

    WebFetch

    도구 이름: WebFetch

    interface WebFetchOutput {
      /**
       * 프롬프트에 대한 AI 모델의 응답
       */
      response: string;
      /**
       * 가져온 URL
       */
      url: string;
      /**
       * 리다이렉트 후의 최종 URL
       */
      final_url?: string;
      /**
       * HTTP 상태 코드
       */
      status_code?: number;
    }

    가져온 웹 콘텐츠에 대한 AI의 분석을 반환합니다.

    WebSearch

    도구 이름: WebSearch

    interface WebSearchOutput {
      /**
       * 검색 결과
       */
      results: Array<{
        title: string;
        url: string;
        snippet: string;
        /**
         * 사용 가능한 경우 추가 메타데이터
         */
        metadata?: Record<string, any>;
      }>;
      /**
       * 총 결과 수
       */
      total_results: number;
      /**
       * 검색된 쿼리
       */
      query: string;
    }

    웹에서 형식이 지정된 검색 결과를 반환합니다.

    TodoWrite

    도구 이름: TodoWrite

    interface TodoWriteOutput {
      /**
       * 성공 메시지
       */
      message: string;
      /**
       * 현재 할 일 통계
       */
      stats: {
        total: number;
        pending: number;
        in_progress: number;
        completed: number;
      };
    }

    현재 작업 통계와 함께 확인을 반환합니다.

    ExitPlanMode

    도구 이름: ExitPlanMode

    interface ExitPlanModeOutput {
      /**
       * 확인 메시지
       */
      message: string;
      /**
       * 사용자가 계획을 승인했는지 여부
       */
      approved?: boolean;
    }

    계획 모드를 종료한 후 확인을 반환합니다.

    ListMcpResources

    도구 이름: ListMcpResources

    interface ListMcpResourcesOutput {
      /**
       * 사용 가능한 리소스
       */
      resources: Array<{
        uri: string;
        name: string;
        description?: string;
        mimeType?: string;
        server: string;
      }>;
      /**
       * 총 리소스 수
       */
      total: number;
    }

    사용 가능한 MCP 리소스 목록을 반환합니다.

    ReadMcpResource

    도구 이름: ReadMcpResource

    interface ReadMcpResourceOutput {
      /**
       * 리소스 내용
       */
      contents: Array<{
        uri: string;
        mimeType?: string;
        text?: string;
        blob?: string;
      }>;
      /**
       * 리소스를 제공한 서버
       */
      server: string;
    }

    요청된 MCP 리소스의 내용을 반환합니다.

    권한 유형

    PermissionUpdate

    권한을 업데이트하기 위한 작업입니다.

    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'     // 전역 사용자 설정
      | 'projectSettings'  // 디렉토리별 프로젝트 설정
      | 'localSettings'    // Gitignored 로컬 설정
      | 'session'          // 현재 세션만

    PermissionRuleValue

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

    기타 유형

    ApiKeySource

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

    SdkBeta

    betas 옵션을 통해 활성화할 수 있는 사용 가능한 베타 기능입니다. 자세한 내용은 베타 헤더를 참조하세요.

    type SdkBeta = 'context-1m-2025-08-07';
    값설명호환 모델
    'context-1m-2025-08-07'100만 토큰 컨텍스트 윈도우 활성화Claude Sonnet 4, Claude Sonnet 4.5

    SlashCommand

    사용 가능한 슬래시 명령에 대한 정보입니다.

    type SlashCommand = {
      name: string;
      description: string;
      argumentHint: string;
    }

    ModelInfo

    사용 가능한 모델에 대한 정보입니다.

    type ModelInfo = {
      value: string;
      displayName: string;
      description: string;
    }

    McpServerStatus

    연결된 MCP 서버의 상태입니다.

    type McpServerStatus = {
      name: string;
      status: 'connected' | 'failed' | 'needs-auth' | 'pending';
      serverInfo?: {
        name: string;
        version: string;
      };
    }

    AccountInfo

    인증된 사용자의 계정 정보입니다.

    type AccountInfo = {
      email?: string;
      organization?: string;
      subscriptionType?: string;
      tokenSource?: string;
      apiKeySource?: string;
    }

    ModelUsage

    결과 메시지에서 반환되는 모델별 사용 통계입니다.

    type ModelUsage = {
      inputTokens: number;
      outputTokens: number;
      cacheReadInputTokens: number;
      cacheCreationInputTokens: number;
      webSearchRequests: number;
      costUSD: number;
      contextWindow: number;
    }

    ConfigScope

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

    NonNullableUsage

    모든 nullable 필드가 non-nullable로 만들어진 Usage의 버전입니다.

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

    Usage

    토큰 사용 통계(@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 도구 결과 타입(@modelcontextprotocol/sdk/types.js에서)입니다.

    type CallToolResult = {
      content: Array<{
        type: 'text' | 'image' | 'resource';
        // 추가 필드는 타입에 따라 다름
      }>;
      isError?: boolean;
    }

    AbortError

    중단 작업을 위한 사용자 정의 오류 클래스입니다.

    class AbortError extends Error {}

    샌드박스 구성

    SandboxSettings

    샌드박스 동작을 위한 구성입니다. 이를 사용하여 명령 샌드박싱을 활성화하고 프로그래밍 방식으로 네트워크 제한을 구성합니다.

    type SandboxSettings = {
      enabled?: boolean;
      autoAllowBashIfSandboxed?: boolean;
      excludedCommands?: string[];
      allowUnsandboxedCommands?: boolean;
      network?: NetworkSandboxSettings;
      ignoreViolations?: SandboxIgnoreViolations;
      enableWeakerNestedSandbox?: boolean;
    }
    속성타입기본값설명
    enabledbooleanfalse명령 실행을 위한 샌드박스 모드 활성화
    autoAllowBashIfSandboxedbooleanfalse샌드박스가 활성화되었을 때 bash 명령 자동 승인
    excludedCommandsstring[][]항상 샌드박스 제한을 우회하는 명령(예: ['docker']). 이들은 모델 개입 없이 자동으로 샌드박스되지 않은 상태로 실행됩니다
    allowUnsandboxedCommandsbooleanfalse모델이 샌드박스 외부에서 명령을 실행하도록 요청할 수 있도록 허용합니다. true일 때 모델은 도구 입력에서 dangerouslyDisableSandbox를 설정할 수 있으며, 이는 권한 시스템으로 폴백됩니다
    networkNetworkSandboxSettingsundefined네트워크 관련 샌드박스 구성
    ignoreViolationsSandboxIgnoreViolationsundefined무시할 샌드박스 위반 구성
    enableWeakerNestedSandboxbooleanfalse호환성을 위해 더 약한 중첩 샌드박스 활성화

    파일 시스템 및 네트워크 액세스 제한은 샌드박스 설정을 통해 구성되지 않습니다. 대신 권한 규칙에서 파생됩니다:

    • 파일 시스템 읽기 제한: 읽기 거부 규칙
    • 파일 시스템 쓰기 제한: 편집 허용/거부 규칙
    • 네트워크 제한: WebFetch 허용/거부 규칙

    명령 실행 샌드박싱을 위해 샌드박스 설정을 사용하고, 파일 시스템 및 네트워크 액세스 제어를 위해 권한 규칙을 사용합니다.

    사용 예시

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

    NetworkSandboxSettings

    샌드박스 모드를 위한 네트워크 관련 구성입니다.

    type NetworkSandboxSettings = {
      allowLocalBinding?: boolean;
      allowUnixSockets?: string[];
      allowAllUnixSockets?: boolean;
      httpProxyPort?: number;
      socksProxyPort?: number;
    }
    속성타입기본값설명
    allowLocalBindingbooleanfalse프로세스가 로컬 포트에 바인딩할 수 있도록 허용(예: 개발 서버의 경우)
    allowUnixSocketsstring[][]프로세스가 액세스할 수 있는 Unix 소켓 경로(예: Docker 소켓)
    allowAllUnixSocketsbooleanfalse모든 Unix 소켓에 대한 액세스 허용
    httpProxyPortnumberundefined네트워크 요청을 위한 HTTP 프록시 포트
    socksProxyPortnumberundefined네트워크 요청을 위한 SOCKS 프록시 포트

    SandboxIgnoreViolations

    특정 샌드박스 위반을 무시하기 위한 구성입니다.

    type SandboxIgnoreViolations = {
      file?: string[];
      network?: string[];
    }
    속성타입기본값설명
    filestring[][]위반을 무시할 파일 경로 패턴
    networkstring[][]위반을 무시할 네트워크 패턴

    샌드박스되지 않은 명령에 대한 권한 폴백

    allowUnsandboxedCommands가 활성화되면 모델은 도구 입력에서 dangerouslyDisableSandbox: true를 설정하여 샌드박스 외부에서 명령을 실행하도록 요청할 수 있습니다. 이러한 요청은 기존 권한 시스템으로 폴백되므로 canUseTool 핸들러가 호출되어 사용자 정의 인증 로직을 구현할 수 있습니다.

    excludedCommands vs allowUnsandboxedCommands:

    • excludedCommands: 항상 자동으로 샌드박스를 우회하는 명령의 정적 목록(예: ['docker']). 모델은 이에 대한 제어 권한이 없습니다.
    • allowUnsandboxedCommands: 모델이 도구 입력에서 dangerouslyDisableSandbox: true를 설정하여 런타임에 샌드박스되지 않은 실행을 요청할지 여부를 결정하도록 합니다.
    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    const result = await query({
      prompt: "Deploy my application",
      options: {
        sandbox: {
          enabled: true,
          allowUnsandboxedCommands: true  // 모델이 샌드박스되지 않은 실행을 요청할 수 있음
        },
        permissionMode: "default",
        canUseTool: async (tool, input) => {
          // 모델이 샌드박스를 우회하도록 요청하는지 확인
          if (tool === "Bash" && input.dangerouslyDisableSandbox) {
            // 모델이 이 명령을 샌드박스 외부에서 실행하기를 원함
            console.log(`Unsandboxed command requested: ${input.command}`);
    
            // 허용하려면 true, 거부하려면 false 반환
            return isCommandAuthorized(input.command);
          }
          return true;
        }
      }
    });

    이 패턴을 통해 다음을 수행할 수 있습니다:

    • 모델 요청 감사: 모델이 샌드박스되지 않은 실행을 요청할 때 로그
    • 허용 목록 구현: 특정 명령만 샌드박스되지 않은 상태로 실행하도록 허용
    • 승인 워크플로우 추가: 권한 있는 작업에 대해 명시적 인증 필요

    dangerouslyDisableSandbox: true로 실행되는 명령은 전체 시스템 액세스 권한이 있습니다. canUseTool 핸들러가 이러한 요청을 신중하게 검증하는지 확인하세요.

    참고 항목

    • SDK 개요 - 일반 SDK 개념
    • Python SDK 참조 - Python SDK 문서
    • CLI 참조 - 명령줄 인터페이스
    • 일반적인 워크플로우 - 단계별 가이드
    • query()
    • tool()
    • createSdkMcpServer()
    • Options
    • Query
    • AgentDefinition
    • SettingSource
    • PermissionMode
    • CanUseTool
    • PermissionResult
    • McpServerConfig
    • SdkPluginConfig
    • SDKMessage
    • SDKAssistantMessage
    • SDKUserMessage
    • SDKUserMessageReplay
    • SDKResultMessage
    • SDKSystemMessage
    • SDKPartialAssistantMessage
    • SDKCompactBoundaryMessage
    • SDKPermissionDenial
    • HookEvent
    • HookCallback
    • HookCallbackMatcher
    • HookInput
    • BaseHookInput
    • HookJSONOutput
    • ToolInput
    • Task
    • AskUserQuestion
    • Bash
    • BashOutput
    • Edit
    • Read
    • Write
    • Glob
    • Grep
    • KillBash
    • NotebookEdit
    • WebFetch
    • WebSearch
    • TodoWrite
    • ExitPlanMode
    • ListMcpResources
    • ReadMcpResource
    • ToolOutput
    • Task
    • AskUserQuestion
    • Bash
    • BashOutput
    • Edit
    • Read
    • Write
    • Glob
    • Grep
    • KillBash
    • NotebookEdit
    • WebFetch
    • WebSearch
    • TodoWrite
    • ExitPlanMode
    • ListMcpResources
    • ReadMcpResource
    • PermissionUpdate
    • PermissionBehavior
    • PermissionUpdateDestination
    • PermissionRuleValue
    • ApiKeySource
    • SdkBeta
    • SlashCommand
    • ModelInfo
    • McpServerStatus
    • AccountInfo
    • ModelUsage
    • ConfigScope
    • NonNullableUsage
    • Usage
    • CallToolResult
    • AbortError
    • SandboxSettings
    • NetworkSandboxSettings
    • SandboxIgnoreViolations