Loading...
    • 개발자 가이드
    • API 참고자료
    • MCP
    • 리소스
    • 릴리스 노트
    Search...
    ⌘K

    첫 번째 단계

    Claude 소개빠른 시작

    모델 및 가격

    모델 개요모델 선택하기Claude 4.5의 새로운 기능Claude 4.5로 마이그레이션모델 지원 중단가격 정책

    Claude로 빌드하기

    기능 개요Messages API 작업컨텍스트 윈도우프롬프트 작성 모범 사례

    기능

    프롬프트 캐싱컨텍스트 편집확장된 사고스트리밍 메시지배치 처리인용다국어 지원토큰 카운팅임베딩비전PDF 지원Files API검색 결과Google Sheets 애드온

    도구

    개요도구 사용을 구현하는 방법토큰 효율적인 도구 사용세밀한 도구 스트리밍Bash 도구코드 실행 도구컴퓨터 사용 도구텍스트 편집기 도구웹 페치 도구웹 검색 도구메모리 도구

    에이전트 스킬

    개요빠른 시작Skill 작성 모범 사례Skills 사용하기

    Agent SDK

    개요Agent SDK 참조 - TypeScriptPython SDK

    가이드

    스트리밍 입력권한 처리세션 관리Agent SDK 호스팅시스템 프롬프트 수정하기SDK에서의 MCP사용자 정의 도구SDK의 서브에이전트SDK의 슬래시 명령어SDK의 에이전트 스킬비용 및 사용량 추적할 일 목록SDK의 플러그인

    API의 MCP

    MCP 커넥터원격 MCP 서버

    타사 플랫폼의 Claude

    Amazon BedrockVertex AI

    프롬프트 엔지니어링

    개요프롬프트 생성기프롬프트 템플릿 사용하기프롬프트 개선기명확하고 직접적으로예시(멀티샷 프롬프팅) 사용Claude가 생각하도록 하기(CoT)XML 태그 사용Claude에게 역할 부여하기 (시스템 프롬프트)Claude의 응답 미리 채우기복잡한 프롬프트 체이닝긴 컨텍스트 팁확장 사고 팁

    테스트 및 평가

    성공 기준 정의하기테스트 케이스 개발평가 도구 사용하기지연 시간 줄이기

    보안 강화

    환각 현상 줄이기출력 일관성 높이기탈옥 완화handle-streaming-refusals프롬프트 유출 감소Claude의 캐릭터 유지

    관리 및 모니터링

    Admin API 개요사용량 및 비용 APIClaude Code Analytics API
    Console
    가이드

    사용자 정의 도구

    Claude Agent SDK 기능을 확장하기 위한 사용자 정의 도구를 구축하고 통합하세요

    사용자 정의 도구를 사용하면 인프로세스 MCP 서버를 통해 자체 기능으로 Claude Code의 기능을 확장할 수 있으며, Claude가 외부 서비스, API와 상호 작용하거나 특수한 작업을 수행할 수 있습니다.

    사용자 정의 도구 생성

    createSdkMcpServer와 tool 헬퍼 함수를 사용하여 타입 안전한 사용자 정의 도구를 정의하세요:

    TypeScript
    import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
    import { z } from "zod";
    
    // 사용자 정의 도구로 SDK MCP 서버 생성
    const customServer = createSdkMcpServer({
      name: "my-custom-tools",
      version: "1.0.0",
      tools: [
        tool(
          "get_weather",
          "좌표를 사용하여 위치의 현재 온도 가져오기",
          {
            latitude: z.number().describe("위도 좌표"),
            longitude: z.number().describe("경도 좌표")
          },
          async (args) => {
            const response = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${args.latitude}&longitude=${args.longitude}&current=temperature_2m&temperature_unit=fahrenheit`);
            const data = await response.json();
    
            return {
              content: [{
                type: "text",
                text: `온도: ${data.current.temperature_2m}°F`
              }]
            };
          }
        )
      ]
    });
    Python
    from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeSDKClient, ClaudeAgentOptions
    from typing import Any
    import aiohttp
    
    # @tool 데코레이터를 사용하여 사용자 정의 도구 정의
    @tool("get_weather", "좌표를 사용하여 위치의 현재 온도 가져오기", {"latitude": float, "longitude": float})
    async def get_weather(args: dict[str, Any]) -> dict[str, Any]:
        # 날씨 API 호출
        async with aiohttp.ClientSession() as session:
            async with session.get(
                f"https://api.open-meteo.com/v1/forecast?latitude={args['latitude']}&longitude={args['longitude']}&current=temperature_2m&temperature_unit=fahrenheit"
            ) as response:
                data = await response.json()
    
        return {
            "content": [{
                "type": "text",
                "text": f"온도: {data['current']['temperature_2m']}°F"
            }]
        }
    
    # 사용자 정의 도구로 SDK MCP 서버 생성
    custom_server = create_sdk_mcp_server(
        name="my-custom-tools",
        version="1.0.0",
        tools=[get_weather]  # 데코레이트된 함수 전달
    )

    사용자 정의 도구 사용

    mcpServers 옵션을 통해 사용자 정의 서버를 딕셔너리/객체로 query 함수에 전달하세요.

    중요: 사용자 정의 MCP 도구는 스트리밍 입력 모드가 필요합니다. prompt 매개변수에 비동기 제너레이터/이터러블을 사용해야 하며, 단순한 문자열은 MCP 서버와 함께 작동하지 않습니다.

    도구 이름 형식

    MCP 도구가 Claude에 노출될 때, 이름은 특정 형식을 따릅니다:

    • 패턴: mcp__{server_name}__{tool_name}
    • 예시: 서버 my-custom-tools의 get_weather라는 도구는 mcp__my-custom-tools__get_weather가 됩니다

    허용된 도구 구성

    allowedTools 옵션을 통해 Claude가 사용할 수 있는 도구를 제어할 수 있습니다:

    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    // 스트리밍 입력으로 쿼리에서 사용자 정의 도구 사용
    async function* generateMessages() {
      yield {
        type: "user" as const,
        message: {
          role: "user" as const,
          content: "샌프란시스코의 날씨는 어떤가요?"
        }
      };
    }
    
    for await (const message of query({
      prompt: generateMessages(),  // 스트리밍 입력을 위한 비동기 제너레이터 사용
      options: {
        mcpServers: {
          "my-custom-tools": customServer  // 배열이 아닌 객체/딕셔너리로 전달
        },
        // 선택적으로 Claude가 사용할 수 있는 도구 지정
        allowedTools: [
          "mcp__my-custom-tools__get_weather",  // 날씨 도구 허용
          // 필요에 따라 다른 도구 추가
        ],
        maxTurns: 3
      }
    })) {
      if (message.type === "result" && message.subtype === "success") {
        console.log(message.result);
      }
    }

    다중 도구 예시

    MCP 서버에 여러 도구가 있을 때, 선택적으로 허용할 수 있습니다:

    const multiToolServer = createSdkMcpServer({
      name: "utilities",
      version: "1.0.0",
      tools: [
        tool("calculate", "계산 수행", { /* ... */ }, async (args) => { /* ... */ }),
        tool("translate", "텍스트 번역", { /* ... */ }, async (args) => { /* ... */ }),
        tool("search_web", "웹 검색", { /* ... */ }, async (args) => { /* ... */ })
      ]
    });
    
    // 스트리밍 입력으로 특정 도구만 허용
    async function* generateMessages() {
      yield {
        type: "user" as const,
        message: {
          role: "user" as const,
          content: "5 + 3을 계산하고 'hello'를 스페인어로 번역해주세요"
        }
      };
    }
    
    for await (const message of query({
      prompt: generateMessages(),  // 스트리밍 입력을 위한 비동기 제너레이터 사용
      options: {
        mcpServers: {
          utilities: multiToolServer
        },
        allowedTools: [
          "mcp__utilities__calculate",   // 계산기 허용
          "mcp__utilities__translate",   // 번역기 허용
          // "mcp__utilities__search_web"는 허용되지 않음
        ]
      }
    })) {
      // 메시지 처리
    }

    Python에서의 타입 안전성

    @tool 데코레이터는 타입 안전성을 위한 다양한 스키마 정의 접근 방식을 지원합니다:

    import { z } from "zod";
    
    tool(
      "process_data",
      "타입 안전성을 가진 구조화된 데이터 처리",
      {
        // Zod 스키마는 런타임 검증과 TypeScript 타입을 모두 정의
        data: z.object({
          name: z.string(),
          age: z.number().min(0).max(150),
          email: z.string().email(),
          preferences: z.array(z.string()).optional()
        }),
        format: z.enum(["json", "csv", "xml"]).default("json")
      },
      async (args) => {
        // args는 스키마를 기반으로 완전히 타입이 지정됨
        // TypeScript는 args.data.name이 string, args.data.age가 number 등임을 알고 있음
        console.log(`${args.data.name}의 데이터를 ${args.format}으로 처리 중`);
        
        // 처리 로직
        return {
          content: [{
            type: "text",
            text: `${args.data.name}의 데이터 처리됨`
          }]
        };
      }
    )

    오류 처리

    의미 있는 피드백을 제공하기 위해 오류를 우아하게 처리하세요:

    tool(
      "fetch_data",
      "API에서 데이터 가져오기",
      {
        endpoint: z.string().url().describe("API 엔드포인트 URL")
      },
      async (args) => {
        try {
          const response = await fetch(args.endpoint);
          
          if (!response.ok) {
            return {
              content: [{
                type: "text",
                text: `API 오류: ${response.status} ${response.statusText}`
              }]
            };
          }
          
          const data = await response.json();
          return {
            content: [{
              type: "text",
              text: JSON.stringify(data, null, 2)
            }]
          };
        } catch (error) {
          return {
            content: [{
              type: "text",
              text: `데이터 가져오기 실패: ${error.message}`
            }]
          };
        }
      }
    )

    예시 도구

    데이터베이스 쿼리 도구

    const databaseServer = createSdkMcpServer({
      name: "database-tools",
      version: "1.0.0",
      tools: [
        tool(
          "query_database",
          "데이터베이스 쿼리 실행",
          {
            query: z.string().describe("실행할 SQL 쿼리"),
            params: z.array(z.any()).optional().describe("쿼리 매개변수")
          },
          async (args) => {
            const results = await db.query(args.query, args.params || []);
            return {
              content: [{
                type: "text",
                text: `${results.length}개 행 발견:\n${JSON.stringify(results, null, 2)}`
              }]
            };
          }
        )
      ]
    });

    API 게이트웨이 도구

    const apiGatewayServer = createSdkMcpServer({
      name: "api-gateway",
      version: "1.0.0",
      tools: [
        tool(
          "api_request",
          "외부 서비스에 인증된 API 요청 만들기",
          {
            service: z.enum(["stripe", "github", "openai", "slack"]).describe("호출할 서비스"),
            endpoint: z.string().describe("API 엔드포인트 경로"),
            method: z.enum(["GET", "POST", "PUT", "DELETE"]).describe("HTTP 메서드"),
            body: z.record(z.any()).optional().describe("요청 본문"),
            query: z.record(z.string()).optional().describe("쿼리 매개변수")
          },
          async (args) => {
            const config = {
              stripe: { baseUrl: "https://api.stripe.com/v1", key: process.env.STRIPE_KEY },
              github: { baseUrl: "https://api.github.com", key: process.env.GITHUB_TOKEN },
              openai: { baseUrl: "https://api.openai.com/v1", key: process.env.OPENAI_KEY },
              slack: { baseUrl: "https://slack.com/api", key: process.env.SLACK_TOKEN }
            };
            
            const { baseUrl, key } = config[args.service];
            const url = new URL(`${baseUrl}${args.endpoint}`);
            
            if (args.query) {
              Object.entries(args.query).forEach(([k, v]) => url.searchParams.set(k, v));
            }
            
            const response = await fetch(url, {
              method: args.method,
              headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
              body: args.body ? JSON.stringify(args.body) : undefined
            });
            
            const data = await response.json();
            return {
              content: [{
                type: "text",
                text: JSON.stringify(data, null, 2)
              }]
            };
          }
        )
      ]
    });

    계산기 도구

    const calculatorServer = createSdkMcpServer({
      name: "calculator",
      version: "1.0.0",
      tools: [
        tool(
          "calculate",
          "수학적 계산 수행",
          {
            expression: z.string().describe("평가할 수학 표현식"),
            precision: z.number().optional().default(2).describe("소수점 정밀도")
          },
          async (args) => {
            try {
              // 프로덕션에서는 안전한 수학 평가 라이브러리 사용
              const result = eval(args.expression); // 예시 전용!
              const formatted = Number(result).toFixed(args.precision);
              
              return {
                content: [{
                  type: "text",
                  text: `${args.expression} = ${formatted}`
                }]
              };
            } catch (error) {
              return {
                content: [{
                  type: "text",
                  text: `오류: 잘못된 표현식 - ${error.message}`
                }]
              };
            }
          }
        ),
        tool(
          "compound_interest",
          "투자의 복리 이자 계산",
          {
            principal: z.number().positive().describe("초기 투자 금액"),
            rate: z.number().describe("연간 이자율 (소수로, 예: 5%의 경우 0.05)"),
            time: z.number().positive().describe("투자 기간(년)"),
            n: z.number().positive().default(12).describe("연간 복리 빈도")
          },
          async (args) => {
            const amount = args.principal * Math.pow(1 + args.rate / args.n, args.n * args.time);
            const interest = amount - args.principal;
            
            return {
              content: [{
                type: "text",
                text: `투자 분석:\n` +
                      `원금: $${args.principal.toFixed(2)}\n` +
                      `이율: ${(args.rate * 100).toFixed(2)}%\n` +
                      `기간: ${args.time}년\n` +
                      `복리: 연 ${args.n}회\n\n` +
                      `최종 금액: $${amount.toFixed(2)}\n` +
                      `이자 수익: $${interest.toFixed(2)}\n` +
                      `수익률: ${((interest / args.principal) * 100).toFixed(2)}%`
              }]
            };
          }
        )
      ]
    });

    관련 문서

    • TypeScript SDK 참조
    • Python SDK 참조
    • MCP 문서
    • SDK 개요
    • Python에서의 타입 안전성
    • API 게이트웨이 도구
    © 2025 ANTHROPIC PBC

    Products

    • Claude
    • Claude Code
    • Max plan
    • Team plan
    • Enterprise plan
    • Download app
    • Pricing
    • Log in

    Features

    • Claude and Slack
    • Claude in Excel

    Models

    • Opus
    • Sonnet
    • Haiku

    Solutions

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

    Claude Developer Platform

    • Overview
    • Developer docs
    • Pricing
    • Amazon Bedrock
    • Google Cloud’s Vertex AI
    • Console login

    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

    Help and security

    • Availability
    • Status
    • Support center

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy

    Products

    • Claude
    • Claude Code
    • Max plan
    • Team plan
    • Enterprise plan
    • Download app
    • Pricing
    • Log in

    Features

    • Claude and Slack
    • Claude in Excel

    Models

    • Opus
    • Sonnet
    • Haiku

    Solutions

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

    Claude Developer Platform

    • Overview
    • Developer docs
    • Pricing
    • Amazon Bedrock
    • Google Cloud’s Vertex AI
    • Console login

    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

    Help and security

    • Availability
    • Status
    • Support center

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    © 2025 ANTHROPIC PBC