TDTech Digest

091. Agent SDK 레퍼런스 - TypeScript (Agent SDK reference - TypeScript)

  • 원문: English
  • 위치: Agent SDK › SDK references › Agent SDK reference - TypeScript

한 줄 요약

TypeScript Agent SDK(@anthropic-ai/claude-agent-sdk)의 함수·Options·Query 메서드·메시지/훅/도구/권한/샌드박스 타입을 모두 정리한 API 레퍼런스입니다. 원문이 340KB가 넘어 이 노트는 범주별 구조와 자주 쓰는 항목만 정리합니다. 전체 목록은 원문을 참고하세요.

쉽게 말하면

query()에 프롬프트와 옵션을 넣으면 메시지 스트림이 나오고, 그 스트림 객체(Query)로 모델 변경·중단·파일 되감기 같은 제어를 하는 구조입니다. 나머지는 거의 그 옵션과 메시지의 “타입 사전"입니다.

핵심 내용

설치와 번들

npm install @anthropic-ai/claude-agent-sdk
  • 플랫폼별 네이티브 Claude Code 바이너리를 optional dependency(예: @anthropic-ai/claude-agent-sdk-darwin-arm64)로 번들합니다. SDK 버전이 CLI 버전을 따라갑니다(SDK v0.3.191 = Claude Code v2.1.191). 원문에서 “Claude Code vX 필요"라고 하면 같은 패치 번호 이상의 SDK가 필요합니다.
  • ⚠️ optional dependency를 건너뛰면 Native CLI binary for <platform>-<arch> not found → pathToClaudeCodeExecutable로 별도 claude 지정
  • Yarn 1.x 등 libc 필드 미지원 시 glibc·musl 패키지가 둘 다 설치됨(용량 약 2배). 컨테이너에서는 안 맞는 쪽 삭제 가능(SDK v0.2.141+)
  • bun build --compile 단일 실행 파일: 바이너리를 파일 에셋으로 넣고 extractFromBunfs()(v0.3.144+)로 꺼내 pathToClaudeCodeExecutable에 전달
  • 앱과 함께 번들할 땐 @anthropic-ai/claude-agent-sdk/core(v0.3.282+, TS 5.0+). zod, @modelcontextprotocol/sdk를 peer로 가져와 중복을 줄임. InMemorySessionStore, 세션 목록/읽기/포크 헬퍼는 빠짐. ⚠️ 한 프로세스에서 root와 /core를 섞어 쓰지 말 것

함수

함수용도
query({ prompt, options })핵심. prompt는 문자열 또는 AsyncIterable<SDKUserMessage>(스트리밍). Query 반환
startup()서브프로세스를 미리 띄워 초기화 → WarmQuery.query()로 즉시 시작. initializeTimeoutMs 기본 60000
prewarm() (alpha, v0.3.282+)작업 폴더를 모를 때 예비 프로세스 생성 → claim({ prompt, options: { cwd } }). 예비당 약 230~260 MB
tool()Zod 스키마로 타입 안전한 MCP 도구 정의. annotations, searchHint, alwaysLoad
createSdkMcpServer()같은 프로세스 내 MCP 서버. timeout(ms, 1000 이상, v0.3.248+)
listSessions(), getSessionMessages(), getSessionInfo()과거 세션 조회
renameSession(), tagSession(), forkSession()세션 이름·태그·분기. 포크는 파일 체크포인트를 복사하지 않음
resolveSettings() (alpha)CLI를 띄우지 않고 유효 설정과 출처(provenance) 계산
matchDeniedModels() (alpha, v0.3.323+)deniedModels가 막는 모델 확인
  • startup(): initializeTimeoutMs를 비워 두면 느린 SessionStart/Setup 훅 시간은 60초에 포함되지 않습니다(최대 10분 추가). 값을 지정하면 그 값이 절대 한도.
  • prewarm(): resume/continue/forkSession 불가. mcpServers, hooks, canUseTool, settingSources, plugins는 prewarm 시 값으로 고정.
  • ToolAnnotations의 destructiveHint: always_ask 도구에는 명시적으로 true 를 넣으세요. Claude Code는 미설정을 false로 취급해 auto 모드 분류기가 승인할 수 있습니다.

주요 Options (전체는 원문)

범주옵션기본값/메모
기본cwd, model, fallbackModel, effort, thinking, maxTurnsthinking은 지원 모델에서 { type: 'adaptive' }
시스템 프롬프트systemPrompt미지정 시 최소 프롬프트. { type: 'preset', preset: 'claude_code', append }로 Claude Code 프롬프트 사용
도구tools, allowedTools, disallowedTools, toolConfig, toolAliasesallowedTools는 자동 승인일 뿐 제한 아님. disallowedTools의 "Bash(rm *)" 같은 범위 규칙은 bypassPermissions에서도 거부
권한permissionMode, canUseTool, permissionPrompts, allowDangerouslySkipPermissionspermissionPrompts: 'none'은 프롬프트가 필요한 호출을 거부(v2.1.259+)
설정settingSources, settings, managedSettings, projectConfigRootsettingSources 미지정 = user/project/local 전부 로드
세션resume, continue, forkSession, sessionId, persistSession, sessionStore, resumeSessionAtpersistSession: false면 재개 불가
확장mcpServers, strictMcpConfig, agents, agent, skills, plugins, hooksskills와 tools를 같이 쓰면 tools에 'Skill' 포함
비용maxBudgetUsd, taskBudget(alpha)클라이언트 추정치 기준이라 초과 가능, 여유를 두세요
출력outputFormat, includePartialMessages, includeHookEvents, forwardSubagentText, promptSuggestions
실행 환경env, executable, pathToClaudeCodeExecutable, spawnClaudeCodeProcess, stderr, sandbox⚠️ env는 process.env를 대체. { ...process.env, X: '...' }로 전달
기타enableFileCheckpointing, extraArgs, additionalDirectories, verbatimPrompts, title

📝 outputStyle은 Options 필드가 아닙니다. settings 객체나 설정 파일에 넣으세요.

느린/멈춘 API 응답 대응 (env로 전달)

변수기본값
API_TIMEOUT_MS600000 (응답 헤더까지 대기, 스트리밍 시간은 제한 안 함)
CLAUDE_CODE_MAX_RETRIES10, 최대 15 (CLAUDE_CODE_RETRY_WATCHDOG=1이면 상한 해제)
CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS서브에이전트 정지 감시. 스트림 워치독이 켜져 있으면 CLAUDE_STREAM_IDLE_TIMEOUT_MS + 5분
CLAUDE_ENABLE_STREAM_WATCHDOG / CLAUDE_STREAM_IDLE_TIMEOUT_MS기본 켜짐 / 300000(최소값)

Query 객체 주요 메서드

메서드설명
interrupt()중단(스트리밍 입력 모드만)
rewindFiles(id, { dryRun })파일 되감기. enableFileCheckpointing 필요 (073)
setPermissionMode(), setModel()실행 중 변경(스트리밍 입력 모드만)
applyFlagSettings()실행 중 임의 설정 변경(TS 전용). permissions, hooks, agent 등은 다음 턴, model은 현재 턴부터, 시스템 프롬프트는 반영 안 됨. 최상위 키 얕은 병합, null로 해제
updateSettings(source, settings)허용된 키 1개를 디스크에 저장(localSettings: outputStyle, userSettings: effortLevel)
streamInput()멀티턴 입력 추가
supportedCommands/Models/Agents(), mcpServerStatus(), accountInfo(), initializationResult()조회
getContextUsage()/context와 같은 컨텍스트 사용량 분석
readFile(path)세션 파일시스템 읽기(기본 1 MB, 최대 10 MB)
reloadPlugins(), reloadSkills(), reloadOutputStyles()디스크에서 다시 로드
setMcpServers(), reconnectMcpServer(), toggleMcpServer(), setMcpPermissionModeOverride()MCP 관리. override는 bypassPermissions/auto에서만 적용되어 더 엄격하게만 가능
backgroundTasks(), stopTask()Ctrl+B처럼 백그라운드로 보내기 / 중지
seedReadState()읽은 것으로 표시해 File has not been read yet 방지
reinitialize()연결 끊김 후 재초기화(대기 중 권한 요청 재전달)
close()프로세스 강제 종료

설정 소스 (SettingSource)

값위치
'user'~/.claude/settings.json
'project'.claude/settings.json (CLAUDE.md 로드에도 필요)
'local'.claude/settings.local.json

우선순위: local > project > user. allowedTools/settings의 권한 규칙은 파일 규칙에 추가되고, managed 정책과 충돌 시 managed가 이깁니다. []이면 파일 설정 미로드(엔드포인트 관리 정책은 항상 로드).

권한 타입

  • PermissionMode: default, acceptEdits, bypassPermissions(명시적 ask 규칙은 여전히 묻기), plan, dontAsk(묻는 대신 거부), auto(모델 분류기 검토)
  • CanUseTool: 권한 흐름이 프롬프트로 떨어질 때만 호출. allowedTools·allow 규칙·모드로 승인된 호출은 안 거치므로 그런 호출 검사는 PreToolUse 훅을 쓰세요. ⚠️ null 반환은 별도 채널로 응답을 이미 보낸 경우만. 아니면 영원히 대기합니다.
  • PermissionResult: { behavior: "allow", updatedInput?, updatedPermissions? } / { behavior: "deny", message, interrupt? }. updatedPermissions 항목이 4,096개를 넘으면 거부.

메시지 타입 (SDKMessage 유니언, 40여 종)

자주 쓰는 타입내용
SDKSystemMessage (subtype: "init")세션 시작 정보: tools, mcp_servers, model, permissionMode, claude_code_version 등
SDKAssistantMessagemessage(BetaMessage), parent_tool_use_id, error(rate_limit, overloaded, billing_error, cloud_credential_error 등), agent_id
SDKUserMessage / SDKUserMessageReplay사용자 입력 / 재생된 입력
SDKResultMessage최종 결과. subtype: success, error_max_turns, error_during_execution, error_max_budget_usd, error_max_structured_output_retries. total_cost_usd, usage, modelUsage, num_turns, duration_ms
SDKPartialAssistantMessageincludePartialMessages 시 스트림 이벤트
기타압축 경계, 훅 시작/진행/응답, 작업(task) 시작/진행/알림, 레이트 리밋, 권한 거부, mirror_error, SDKInformationalMessage, SDKConversationResetMessage 등

ModelUsage: inputTokens, outputTokens(thinking 포함), cacheReadInputTokens, cacheCreationInputTokens, webSearchRequests, costUSD(추정치), provider(firstParty, bedrock, vertex 등), costBasis.

훅·도구 타입

  • HookEvent: 33개 이벤트(자세한 표는 072 훅). 이벤트별 *HookInput, 출력은 SyncHookJSONOutput / AsyncHookJSONOutput
  • 도구 입력/출력 타입은 @anthropic-ai/claude-agent-sdk/sdk-tools에서 export (BashInput, FileEditInput, TaskCreateInput 등). Agent 도구의 옛 이름 Task도 별칭으로 허용
  • BUILTIN_TOOL_NAMES, LEGACY_TOOL_NAME_ALIASES(alpha, v0.3.301+): 이름 검증용. ⚠️ MCP·일부 내장 도구가 빠져 있어 이걸로 거부 목록을 만들면 새는 도구가 생깁니다. 전부 막으려면 disallowedTools: ["*"]
  • 타입이 있는 에러 클래스는 AbortError 하나뿐입니다. 나머지는 메시지로 구분(014)

샌드박스 (sandbox 옵션)

속성기본값메모
enabledfalseBash 명령 샌드박스
failIfUnavailabletrue못 띄우면 error_during_execution으로 중단. false면 경고 후 비샌드박스 실행
autoAllowBashIfSandboxedfalse(false 기본값은 SDK v0.3.324+)
allowUnsandboxedCommandstrue모델이 dangerouslyDisableSandbox로 탈출 요청 가능 → 권한 시스템으로 넘어감
excludedCommands[]모델 개입 없이 샌드박스 밖 실행(예: ['docker *'])
network.allowedDomains / deniedDomains[]denied 우선. WebFetch는 제한 안 함(권한 규칙으로)
network.strictAllowlistfalse허용 목록 밖은 묻지 않고 거부. project 설정에선 무시
network.allowUnixSockets[]⚠️ /var/run/docker.sock 허용 = 사실상 호스트 전체 권한
filesystem.allowWrite / denyWrite / denyRead[]
  • ⚠️ 내장 프록시는 호스트 이름 기준이라 TLS를 검사하지 않아 domain fronting 우회 가능성이 있습니다.
  • ⚠️ bypassPermissions + allowUnsandboxedCommands: true 조합은 모델이 조용히 샌드박스를 탈출할 수 있습니다.
for await (const m of query({ prompt: "Build and test my project",
  options: { sandbox: { enabled: true, autoAllowBashIfSandboxed: true, network: { allowLocalBinding: true } } } })) {}

실무 관점

  • SDK 버전 = CLI 버전이므로 원문의 “v2.1.xxx 필요” 표기는 SDK 0.3.xxx로 읽으면 됩니다. 기능별 최소 버전이 매우 촘촘하니 팀 표준 SDK 버전을 정하고 변경 로그를 확인하세요.
  • env 대체 동작, allowedTools가 제한이 아니라는 점, canUseTool이 모든 호출을 보지 않는다는 점이 가장 흔한 보안 함정입니다. 정책 강제는 disallowedTools + PreToolUse 훅 + 샌드박스로 하세요.
  • 멀티테넌트 서버라면 settingSources: [], strictMcpConfig: true, persistSession/sessionStore 전략을 명시적으로 정하는 것이 안전합니다(081).
  • 콜드 스타트가 중요한 서비스는 startup()/prewarm()으로 지연을 줄일 수 있지만, 예비 프로세스마다 수백 MB 메모리가 듭니다.
  • 참고: 093 Python 레퍼런스, 071 권한, 052 MCP, 012 설정 레퍼런스