전제 조건

  • Node.js 18+

설치

NPM에서 @anthropic-ai/claude-code를 설치하세요:

npm install -g @anthropic-ai/claude-code

TypeScript SDK 소스 코드를 보려면 NPM의 @anthropic-ai/claude-code 페이지를 방문하세요.

기본 사용법

TypeScript SDK를 통한 주요 인터페이스는 query 함수로, 메시지가 도착하는 대로 스트리밍하는 비동기 이터레이터를 반환합니다:

import { query } from "@anthropic-ai/claude-code";

for await (const message of query({
  prompt: "시스템 성능 분석",
  abortController: new AbortController(),
  options: {
    maxTurns: 5,
    systemPrompt: "당신은 성능 엔지니어입니다",
    allowedTools: ["Bash", "Read", "WebSearch"]
  }
})) {
  if (message.type === "result") {
    console.log(message.result);
  }
}

구성 옵션

인수타입설명기본값
abortControllerAbortController작업 취소를 위한 중단 컨트롤러new AbortController()
additionalDirectoriesstring[]세션에 포함할 추가 디렉토리undefined
allowedToolsstring[]Claude가 사용할 수 있는 도구 목록기본적으로 모든 도구 활성화
appendSystemPromptstring기본 시스템 프롬프트에 추가할 텍스트undefined
canUseToolCanUseTool도구 사용을 위한 맞춤 권한 함수undefined
continueboolean가장 최근 세션 계속하기false
customSystemPromptstring기본 시스템 프롬프트를 완전히 교체undefined
cwdstring현재 작업 디렉토리process.cwd()
disallowedToolsstring[]Claude가 사용할 수 없는 도구 목록undefined
envDict<string>설정할 환경 변수undefined
executable'bun' | 'deno' | 'node'사용할 JavaScript 런타임Node.js로 실행 시 node, Bun으로 실행 시 bun
executableArgsstring[]실행 파일에 전달할 인수[]
fallbackModelstring기본 모델 실패 시 사용할 모델undefined
maxThinkingTokensnumberClaude의 사고 과정을 위한 최대 토큰undefined
maxTurnsnumber대화 턴의 최대 수undefined
mcpServersRecord<string, McpServerConfig>MCP 서버 구성undefined
modelstring사용할 Claude 모델CLI 구성의 기본값 사용
pathToClaudeCodeExecutablestringClaude Code 실행 파일 경로@anthropic-ai/claude-code와 함께 제공되는 실행 파일
permissionModePermissionMode세션의 권한 모드"default" (옵션: "default", "acceptEdits", "bypassPermissions", "plan")
permissionPromptToolNamestring권한 프롬프트용 MCP 도구 이름undefined
resumestring재개할 세션 IDundefined
stderr(data: string) => voidstderr 출력을 위한 콜백undefined
strictMcpConfigboolean엄격한 MCP 구성 검증 강제undefined

다중 턴 대화

다중 턴 대화의 경우 두 가지 옵션이 있습니다.

응답을 생성하고 재개하거나, 메시지 배열에 대한 비동기/제너레이터를 허용하는 스트리밍 입력 모드를 사용할 수 있습니다. 현재 스트리밍 입력 모드는 메시지를 통해 이미지를 첨부하는 유일한 방법입니다.

세션 관리로 재개

import { query } from "@anthropic-ai/claude-code";

// 가장 최근 대화 계속하기
for await (const message of query({
  prompt: "이제 더 나은 성능을 위해 리팩토링하세요",
  options: { continue: true }
})) {
  if (message.type === "result") console.log(message.result);
}

// 특정 세션 재개
for await (const message of query({
  prompt: "테스트를 업데이트하세요",
  options: {
    resume: "550e8400-e29b-41d4-a716-446655440000",
    maxTurns: 3
  }
})) {
  if (message.type === "result") console.log(message.result);
}

스트리밍 입력 모드

스트리밍 입력 모드를 사용하면 단일 문자열 대신 비동기 이터러블로 메시지를 제공할 수 있습니다. 이를 통해 다중 턴 대화, 이미지 첨부, 동적 메시지 생성이 가능합니다:

import { query } from "@anthropic-ai/claude-code";

// 스트리밍 메시지를 위한 비동기 제너레이터 생성
async function* generateMessages() {
  yield {
    type: "user" as const,
    message: {
      role: "user" as const,
      content: "이 코드베이스 분석을 시작하세요"
    }
  };
  
  // 특정 조건이나 사용자 입력 대기
  await new Promise(resolve => setTimeout(resolve, 1000));
  
  yield {
    type: "user" as const,
    message: {
      role: "user" as const,
      content: "이제 인증 모듈에 집중하세요"
    }
  };
}

// 스트리밍 입력 사용
for await (const message of query({
  prompt: generateMessages(),
  options: {
    maxTurns: 5,
    allowedTools: ["Read", "Grep", "Bash"]
  }
})) {
  if (message.type === "result") {
    console.log(message.result);
  }
}

이미지가 포함된 스트리밍 입력

스트리밍 입력 모드는 메시지를 통해 이미지를 첨부하는 유일한 방법입니다:

import { query } from "@anthropic-ai/claude-code";
import { readFileSync } from "fs";

async function* messagesWithImage() {
  // 텍스트와 함께 이미지 전송
  yield {
    type: "user" as const,
    message: {
      role: "user" as const,
      content: [
        {
          type: "text",
          text: "이 스크린샷을 분석하고 개선 사항을 제안하세요"
        },
        {
          type: "image",
          source: {
            type: "base64",
            media_type: "image/png",
            data: readFileSync("screenshot.png", "base64")
          }
        }
      ]
    }
  };
}

for await (const message of query({
  prompt: messagesWithImage()
})) {
  if (message.type === "result") console.log(message.result);
}

맞춤 시스템 프롬프트

시스템 프롬프트는 에이전트의 역할, 전문성, 행동을 정의합니다:

import { query } from "@anthropic-ai/claude-code";

// SRE 인시던트 대응 에이전트
for await (const message of query({
  prompt: "API가 다운되었습니다. 조사하세요",
  options: {
    systemPrompt: "당신은 SRE 전문가입니다. 문제를 체계적으로 진단하고 실행 가능한 솔루션을 제공하세요.",
    maxTurns: 3
  }
})) {
  if (message.type === "result") console.log(message.result);
}

// 기본 시스템 프롬프트에 추가
for await (const message of query({
  prompt: "이 함수를 리팩토링하세요",
  options: {
    appendSystemPrompt: "항상 포괄적인 오류 처리와 단위 테스트를 포함하세요.",
    maxTurns: 2
  }
})) {
  if (message.type === "result") console.log(message.result);
}

MCP를 통한 맞춤 도구

Model Context Protocol (MCP)을 사용하면 에이전트에게 맞춤 도구와 기능을 제공할 수 있습니다:

import { query } from "@anthropic-ai/claude-code";

// 모니터링 도구가 있는 SRE 에이전트
for await (const message of query({
  prompt: "결제 서비스 장애를 조사하세요",
  options: {
    mcpConfig: "sre-tools.json",
    allowedTools: ["mcp__datadog", "mcp__pagerduty", "mcp__kubernetes"],
    systemPrompt: "당신은 SRE입니다. 모니터링 데이터를 사용하여 문제를 진단하세요.",
    maxTurns: 4
  }
})) {
  if (message.type === "result") console.log(message.result);
}

MCP를 사용한 맞춤 도구

MCP를 사용하여 맞춤 도구를 구현할 수 있습니다. 예를 들어 맞춤 권한 처리 도구를 만드는 방법은 다음과 같습니다.

const server = new McpServer({
  name: "Test permission prompt MCP Server",
  version: "0.0.1",
});

server.tool(
  "approval_prompt",
  '권한 확인 시뮬레이션 - 입력에 "allow"가 포함되면 승인, 그렇지 않으면 거부',
  {
    tool_name: z.string().describe("권한을 요청하는 도구의 이름"),
    input: z.object({}).passthrough().describe("도구의 입력"),
    tool_use_id: z.string().optional().describe("고유한 도구 사용 요청 ID"),
  },
  async ({ tool_name, input }) => {
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify(
            JSON.stringify(input).includes("allow")
              ? {
                  behavior: "allow",
                  updatedInput: input,
                }
              : {
                  behavior: "deny",
                  message: "테스트 approval_prompt 도구에 의해 권한이 거부되었습니다",
                }
          ),
        },
      ],
    };
  }
);

// SDK에서 사용
import { query } from "@anthropic-ai/claude-code";

for await (const message of query({
  prompt: "코드베이스를 분석하세요",
  options: {
    permissionPromptTool: "mcp__test-server__approval_prompt",
    mcpConfig: "my-config.json",
    allowedTools: ["Read", "Grep"]
  }
})) {
  if (message.type === "result") console.log(message.result);
}

출력 형식

텍스트 출력 (기본값)

// 기본 텍스트 출력
for await (const message of query({
  prompt: "src/components/Header.tsx 파일을 설명하세요"
})) {
  if (message.type === "result") {
    console.log(message.result);
    // 출력: 이것은 다음을 보여주는 React 컴포넌트입니다...
  }
}

JSON 출력

// JSON과 같은 접근을 위해 모든 메시지 수집
const messages = [];
for await (const message of query({
  prompt: "데이터 레이어는 어떻게 작동하나요?"
})) {
  messages.push(message);
}

// 메타데이터와 함께 결과 메시지 접근
const result = messages.find(m => m.type === "result");
console.log({
  result: result.result,
  cost: result.total_cost_usd,
  duration: result.duration_ms
});

입력 형식

// 직접 프롬프트
for await (const message of query({
  prompt: "이 코드를 설명하세요"
})) {
  if (message.type === "result") console.log(message.result);
}

// 변수에서
const userInput = "이 코드를 설명하세요";
for await (const message of query({ prompt: userInput })) {
  if (message.type === "result") console.log(message.result);
}

에이전트 통합 예제

SRE 인시던트 대응 에이전트

import { query } from "@anthropic-ai/claude-code";

// 자동화된 인시던트 대응 에이전트
async function investigateIncident(
  incidentDescription: string,
  severity = "medium"
) {
  const messages = [];

  for await (const message of query({
    prompt: `인시던트: ${incidentDescription} (심각도: ${severity})`,
    options: {
      systemPrompt: "당신은 SRE 전문가입니다. 문제를 진단하고, 영향을 평가하며, 즉각적인 행동 항목을 제공하세요.",
      maxTurns: 6,
      allowedTools: ["Bash", "Read", "WebSearch", "mcp__datadog"],
      mcpConfig: "monitoring-tools.json"
    }
  })) {
    messages.push(message);
  }

  return messages.find(m => m.type === "result");
}

// 사용법
const result = await investigateIncident("결제 API가 500 오류를 반환합니다", "high");
console.log(result.result);

자동화된 보안 검토

import { query } from "@anthropic-ai/claude-code";
import { execSync } from "child_process";

async function auditPR(prNumber: number) {
  // PR diff 가져오기
  const prDiff = execSync(`gh pr diff ${prNumber}`, { encoding: 'utf8' });

  const messages = [];
  for await (const message of query({
    prompt: prDiff,
    options: {
      systemPrompt: "당신은 보안 엔지니어입니다. 이 PR에서 취약점, 안전하지 않은 패턴, 규정 준수 문제를 검토하세요.",
      maxTurns: 3,
      allowedTools: ["Read", "Grep", "WebSearch"]
    }
  })) {
    messages.push(message);
  }

  return messages.find(m => m.type === "result");
}

// 사용법
const report = await auditPR(123);
console.log(JSON.stringify(report, null, 2));

다중 턴 법무 어시스턴트

import { query } from "@anthropic-ai/claude-code";

async function legalReview() {
  // 법무 검토 세션 시작
  let sessionId: string;

  for await (const message of query({
    prompt: "법무 검토 세션을 시작하세요",
    options: { maxTurns: 1 }
  })) {
    if (message.type === "system" && message.subtype === "init") {
      sessionId = message.session_id;
    }
  }

  // 동일한 세션을 사용한 다단계 검토
  const steps = [
    "contract.pdf에서 책임 조항을 검토하세요",
    "GDPR 요구사항 준수를 확인하세요",
    "위험에 대한 경영진 요약을 생성하세요"
  ];

  for (const step of steps) {
    for await (const message of query({
      prompt: step,
      options: { resume: sessionId, maxTurns: 2 }
    })) {
      if (message.type === "result") {
        console.log(`단계: ${step}`);
        console.log(message.result);
      }
    }
  }
}

메시지 스키마

JSON API에서 반환되는 메시지는 다음 스키마에 따라 엄격하게 타입이 지정됩니다:

type SDKMessage =
  // 어시스턴트 메시지
  | {
      type: "assistant";
      uuid: string;
      session_id: string;
      message: Message; // Anthropic SDK에서
      parent_tool_use_id: string | null;
    }

  // 사용자 메시지 (입력)
  | {
      type: "user";
      uuid?: string;
      session_id: string;
      message: MessageParam; // Anthropic SDK에서
      parent_tool_use_id: string | null;
    }

  // 사용자 메시지 (출력/재생, 필수 UUID 포함)
  | {
      type: "user";
      uuid: string;
      session_id: string;
      message: MessageParam; // Anthropic SDK에서
      parent_tool_use_id: string | null;
    }

  // 성공 시 마지막 메시지로 방출
  | {
      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: Usage;
      permission_denials: SDKPermissionDenial[];
    }

  // 오류 또는 최대 턴 시 마지막 메시지로 방출
  | {
      type: "result";
      subtype: "error_max_turns" | "error_during_execution";
      uuid: UUID;
      session_id: string;
      duration_ms: number;
      duration_api_ms: number;
      is_error: boolean;
      num_turns: number;
      total_cost_usd: number;
      usage: Usage;
      permission_denials: SDKPermissionDenial[];
    }

  // 대화 시작 시 첫 번째 메시지로 방출
  | {
      type: "system";
      subtype: "init";
      uuid: UUID;
      session_id: string;
      apiKeySource: "user" | "project" | "org" | "temporary";
      cwd: string;
      tools: string[];
      mcp_servers: {
        name: string;
        status: string;
      }[];
      model: string;
      permissionMode: "default" | "acceptEdits" | "bypassPermissions" | "plan";
      slash_commands: string[];
      output_style: string;
    };

  type SDKPermissionDenial = {
    tool_name: string;
    tool_use_id: string;
    tool_input: Record<string, unknown>;
  }

추가 지원 타입:

Message, MessageParam, Usage 타입은 Anthropic TypeScript SDK에서 사용할 수 있습니다.

관련 리소스