Claude Code SDK

Claude Code SDK를 사용하면 프로그래밍 방식으로 Claude Code의 기능을 애플리케이션에 통합할 수 있습니다. JavaScript/TypeScript, Python, Go 등 다양한 언어를 지원합니다.

설치

JavaScript/TypeScript

# npm
npm install @anthropic-ai/claude-code-sdk

# yarn
yarn add @anthropic-ai/claude-code-sdk

# pnpm
pnpm add @anthropic-ai/claude-code-sdk

Python

# pip
pip install claude-code-sdk

# poetry
poetry add claude-code-sdk

Go

go get github.com/anthropic-ai/claude-code-sdk-go

JavaScript/TypeScript 사용법

기본 사용 예제

import { ClaudeCode } from '@anthropic-ai/claude-code-sdk';

// Claude Code 인스턴스 생성
const claude = new ClaudeCode({
  apiKey: process.env.ANTHROPIC_API_KEY,
  workingDirectory: '/path/to/project'
});

// 코드 분석 요청
const result = await claude.execute({
  prompt: '이 프로젝트의 인증 시스템을 분석해줘',
  allowedTools: ['read', 'grep']
});

console.log(result.response);

스트리밍 응답

// 스트리밍 모드로 실행
const stream = await claude.stream({
  prompt: '테스트를 실행하고 실패를 수정해줘',
  allowedTools: ['read', 'write', 'bash']
});

// 스트림 이벤트 처리
stream.on('message', (message) => {
  console.log('Claude:', message);
});

stream.on('tool_use', (tool) => {
  console.log('도구 사용:', tool.name, tool.parameters);
});

stream.on('complete', () => {
  console.log('작업 완료');
});

도구 제어

// 세밀한 도구 제어
const result = await claude.execute({
  prompt: '보안 취약점을 찾아줘',
  tools: {
    allowed: [
      { name: 'read', patterns: ['*.js', '*.ts'] },
      { name: 'grep' },
      { name: 'bash', commands: ['npm audit'] }
    ],
    disallowed: ['write']
  },
  timeout: 30000 // 30초 타임아웃
});

Python 사용법

기본 사용 예제

from claude_code_sdk import ClaudeCode

# Claude Code 인스턴스 생성
claude = ClaudeCode(
    api_key="your_api_key",
    working_directory="/path/to/project"
)

# 코드 리뷰 요청
result = claude.execute(
    prompt="이 Python 코드를 리뷰하고 개선사항을 제안해줘",
    allowed_tools=["read", "grep"]
)

print(result.response)

비동기 사용

import asyncio
from claude_code_sdk import AsyncClaudeCode

async def main():
    # 비동기 클라이언트 생성
    claude = AsyncClaudeCode(api_key="your_api_key")
    
    # 여러 작업 병렬 실행
    tasks = [
        claude.execute(prompt="테스트 실행"),
        claude.execute(prompt="린팅 실행"),
        claude.execute(prompt="보안 스캔")
    ]
    
    results = await asyncio.gather(*tasks)
    for result in results:
        print(result.response)

asyncio.run(main())

컨텍스트 관리자

# 컨텍스트 관리자로 세션 관리
with ClaudeCode(api_key="your_api_key") as claude:
    # 대화 세션 시작
    session = claude.create_session()
    
    # 연속된 대화
    response1 = session.send("프로젝트 구조를 분석해줘")
    response2 = session.send("주요 모듈들의 의존성을 설명해줘")
    response3 = session.send("개선할 점을 제안해줘")

고급 기능

콜백 핸들러

// 도구 사용 전 확인
claude.setToolHandler('write', async (tool, params) => {
  const confirmed = await askUser(`파일을 수정하시겠습니까? ${params.file}`);
  return confirmed ? 'proceed' : 'skip';
});

// 진행 상황 모니터링
claude.on('progress', (progress) => {
  console.log(`진행률: ${progress.percent}%`);
});

커스텀 도구 정의

// 커스텀 도구 추가
claude.registerTool({
  name: 'database_query',
  description: '데이터베이스 쿼리 실행',
  parameters: {
    query: { type: 'string', required: true }
  },
  handler: async (params) => {
    // 실제 데이터베이스 쿼리 로직
    const result = await db.query(params.query);
    return result;
  }
});

메모리 관리

// 컨텍스트 크기 제한
const claude = new ClaudeCode({
  apiKey: process.env.ANTHROPIC_API_KEY,
  contextWindow: {
    maxTokens: 100000,
    strategy: 'sliding', // 또는 'truncate'
    preserveSystemMessages: true
  }
});

// 대화 히스토리 관리
claude.clearHistory();
claude.resetContext();

에러 처리

try {
  const result = await claude.execute({
    prompt: '코드 분석',
    timeout: 10000
  });
} catch (error) {
  if (error.code === 'TIMEOUT') {
    console.error('작업 시간 초과');
  } else if (error.code === 'RATE_LIMIT') {
    console.error('API 요청 한도 초과');
    await sleep(error.retryAfter);
  } else if (error.code === 'INVALID_API_KEY') {
    console.error('잘못된 API 키');
  }
}

실전 예제

자동화된 코드 리뷰 봇

class CodeReviewBot {
  constructor(apiKey) {
    this.claude = new ClaudeCode({ apiKey });
  }

  async reviewPullRequest(prData) {
    const { files, diff } = prData;
    
    // 변경된 파일 분석
    const review = await this.claude.execute({
      prompt: `다음 PR을 리뷰해주세요:
        변경된 파일: ${files.join(', ')}
        주요 변경사항을 분석하고 개선사항을 제안해주세요.`,
      allowedTools: ['read', 'grep'],
      context: { diff }
    });

    // 리뷰 결과 포맷팅
    return {
      summary: review.summary,
      suggestions: review.suggestions,
      approved: review.riskLevel === 'low'
    };
  }
}

테스트 자동 생성기

async function generateTests(filePath) {
  const claude = new ClaudeCode();
  
  const result = await claude.execute({
    prompt: `${filePath} 파일의 모든 함수에 대한 단위 테스트를 생성해줘.
             Jest를 사용하고 엣지 케이스도 포함해줘.`,
    allowedTools: ['read', 'write'],
    outputFormat: 'test-file'
  });

  // 생성된 테스트 파일 경로 반환
  return result.createdFiles;
}

SDK 설정 옵션

⚙️ 주요 설정 옵션

  • apiKey: Anthropic API 키
  • workingDirectory: 작업 디렉토리 경로
  • model: 사용할 Claude 모델 (기본값: claude-3-opus)
  • maxRetries: 최대 재시도 횟수
  • timeout: 요청 타임아웃 (밀리초)
  • proxy: 프록시 설정
  • debug: 디버그 모드 활성화