Loading...
    • 개발자 가이드
    • API 레퍼런스
    • MCP
    • 리소스
    • 릴리스 노트
    Search...
    ⌘K
    시작하기
    Claude 소개빠른 시작
    모델 및 가격
    모델 개요모델 선택Claude 4.6의 새로운 기능마이그레이션 가이드모델 지원 중단가격
    Claude로 구축하기
    기능 개요Messages API 사용중지 사유 처리프롬프트 모범 사례
    컨텍스트 관리
    컨텍스트 윈도우압축컨텍스트 편집
    기능
    프롬프트 캐싱확장 사고적응형 사고노력 수준메시지 스트리밍배치 처리인용다국어 지원토큰 카운팅임베딩비전PDF 지원Files API검색 결과구조화된 출력
    도구
    개요도구 사용 구현 방법세분화된 도구 스트리밍Bash 도구코드 실행 도구프로그래밍 방식 도구 호출컴퓨터 사용 도구텍스트 편집기 도구웹 페치 도구웹 검색 도구메모리 도구도구 검색 도구
    Agent Skills
    개요빠른 시작모범 사례엔터프라이즈용 SkillsAPI로 Skills 사용
    Agent SDK
    개요빠른 시작TypeScript SDKTypeScript V2 (미리보기)Python SDK마이그레이션 가이드
    API에서 MCP
    MCP 커넥터원격 MCP 서버
    서드파티 플랫폼의 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    프롬프트 엔지니어링
    개요프롬프트 생성기프롬프트 템플릿 사용프롬프트 개선기명확하고 직접적으로 작성예시 사용 (멀티샷 프롬프팅)Claude에게 생각하게 하기 (CoT)XML 태그 사용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
    Agent SDK

    Agent SDK 레퍼런스 - TypeScript

    함수, 타입, 인터페이스를 포함한 TypeScript Agent SDK의 전체 API 레퍼런스입니다.

    새로운 V2 인터페이스(미리보기)를 사용해 보세요: send()와 receive() 패턴을 사용하는 간소화된 인터페이스가 제공되어 멀티턴 대화가 더 쉬워졌습니다. TypeScript V2 미리보기에 대해 자세히 알아보기

    설치

    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 타입 참조)

    반환값

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

    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'로컬 프로젝트 설정 (gitignore됨).claude/settings.local.json

    기본 동작

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

    settingSources를 사용하는 이유

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

    // SDK v0.0.x처럼 모든 설정 로드
    const result = query({
      prompt: "Analyze this code",
      options: {
        settingSources: ['user', 'project', 'local']  // 모든 설정 로드
      }
    });

    특정 설정 소스만 로드:

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

    테스트 및 CI 환경:

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

    SDK 전용 애플리케이션:

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

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

    // CLAUDE.md 파일을 포함하기 위해 프로젝트 설정 로드
    const result = query({
      prompt: "Add a new feature following project conventions",
      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>;
    }

    실행 중 사용자에게 명확화 질문을 합니다. 사용 세부 정보는 승인 및 사용자 입력 처리를 참조하세요.

    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;
      /**
       * 줄 번호 표시 (content 모드용)
       */
      '-n'?: boolean;
      /**
       * 각 매치 전에 표시할 줄 수
       */
      '-B'?: number;
      /**
       * 각 매치 후에 표시할 줄 수
       */
      '-A'?: number;
      /**
       * 각 매치 전후에 표시할 줄 수
       */
      '-C'?: number;
      /**
       * 출력을 처음 N개 줄/항목으로 제한
       */
      head_limit?: number;
      /**
       * 멀티라인 모드 활성화
       */
      multiline?: boolean;
    }

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

    KillBash

    도구 이름: KillBash

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

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

    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'    // Gitignore된 로컬 설정
      | '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 Opus 4.6, Claude Sonnet 4.5, Claude Sonnet 4

    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,
          network: {
            allowLocalBinding: true
          }
        }
      }
    });

    Unix 소켓 보안: allowUnixSockets 옵션은 강력한 시스템 서비스에 대한 접근을 허용할 수 있습니다. 예를 들어, /var/run/docker.sock을 허용하면 Docker API를 통해 전체 호스트 시스템 접근이 사실상 허용되어 샌드박스 격리를 우회합니다. 반드시 필요한 Unix 소켓만 허용하고 각각의 보안 영향을 이해하세요.

    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 핸들러가 이러한 요청을 신중하게 검증하도록 하세요.

    permissionMode가 bypassPermissions로 설정되고 allowUnsandboxedCommands가 활성화된 경우, 모델은 승인 프롬프트 없이 자율적으로 샌드박스 외부에서 명령을 실행할 수 있습니다. 이 조합은 사실상 모델이 샌드박스 격리를 조용히 탈출할 수 있게 합니다.

    참고 항목

    • SDK 개요 - 일반 SDK 개념
    • Python SDK 레퍼런스 - Python SDK 문서
    • CLI 레퍼런스 - 명령줄 인터페이스
    • 일반 워크플로우 - 단계별 가이드

    Was this page helpful?

    • 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