> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreweave.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Claude Agent SDK

> Weave를 사용하여 Claude Agent SDK로 구축한 에이전트를 트레이싱하세요.

export const AgentLensBanner = ({href}) => <Tip>
    <strong>This workflow is also available in CoreWeave Agent Lens.</strong> Agent Lens is the Forge experience built for tracing, monitoring, and analyzing AI agents, with automated insights into agent failures and user intents. It uses the same trace data as Weights & Biases Weave, so the traces you already send appear there with nothing to migrate.{' '}
    <a href={href || '/products/agent-lens'}>{href ? 'See how to do this in Agent Lens' : 'Learn about Agent Lens'}</a>.
  </Tip>;

<AgentLensBanner href="/ko/products/agent-lens/integrations/claude-agents-sdk" />

Claude Agent SDK를 사용하면 Claude 기반 에이전트 애플리케이션을 빠르게 구축할 수 있습니다. Claude 에이전트에 Weave를 통합하여 에이전트 쿼리, 모델 응답, 도구 사용, 여러 턴에 걸친 대화를 포함한 Call을 자동으로 트레이싱할 수 있습니다. Weave는 캡처한 데이터를 프로젝트의 **Agents** 뷰에 표시합니다.

<h2 id="trace-claude-agent-sdk-agents-with-weave">
  Weave로 Claude Agent SDK 에이전트 트레이싱하기
</h2>

<Tabs>
  <Tab title="Python">
    Weave SDK는 [Python용 Claude Agent SDK](https://github.com/anthropics/claude-agent-sdk-python)를 자동 패치하여 최소한의 설정으로 Claude 에이전트의 트레이스를 캡처할 수 있게 합니다.

    이 가이드에서는 Weave를 초기화하고 `ClaudeSDKClient`를 통해 MCP 도구를 사용하는 Claude 에이전트를 실행하는 방법을 설명합니다. Weave는 대화, 모델 Call, 도구 Call을 처음부터 끝까지 자동으로 트레이싱합니다.

    <h3 id="prerequisites">
      사전 요구 사항
    </h3>

    * CoreWeave Forge 계정과 `WANDB_API_KEY` 환경 변수로 설정한 [API 키](https://forge.coreweave.com/settings#apikeys).
    * `ANTHROPIC_API_KEY` 환경 변수로 설정한 Anthropic API 키.
    * Python 3.10 이상.
  </Tab>

  <Tab title="TypeScript">
    Weave는 [`@anthropic-ai/claude-agent-sdk`](https://github.com/anthropics/claude-agent-sdk)와 통합하여 에이전트 span, 모델 응답, 도구 Call을 포함한 `query()` Call을 자동으로 트레이싱합니다.

    <h3 id="prerequisites-2">
      사전 요구 사항
    </h3>

    * CoreWeave Forge 계정과 `WANDB_API_KEY` 환경 변수로 설정한 [API 키](https://forge.coreweave.com/settings#apikeys).
    * `ANTHROPIC_API_KEY` 환경 변수로 설정한 Anthropic API 키.
    * Node.js 18 이상.
    * `@anthropic-ai/claude-agent-sdk` 버전 `0.3.178` 이상.
  </Tab>
</Tabs>

<h3 id="install-packages">
  패키지 설치
</h3>

개발 환경에 다음 패키지를 설치하세요. `weave` 패키지는 트레이스를 캡처하며, `claude-agent-sdk`는 에이전트 런타임을 제공합니다.

<CodeGroup>
  ```bash Python theme={"system"}
  pip install weave claude-agent-sdk
  ```

  ```bash TypeScript theme={"system"}
  npm install weave @anthropic-ai/claude-agent-sdk
  ```
</CodeGroup>

<h3 id="initialize-weave-in-your-code">
  코드에서 Weave 초기화
</h3>

<Tabs>
  <Tab title="Python">
    프로젝트에 `weave.init`을 추가하고, CoreWeave Forge 팀 및 프로젝트 이름을 업데이트한 다음, 평소처럼 에이전트를 구축하세요. `weave.init`은 Claude Agent SDK의 트레이스를 자동으로 수집하고 기록하는 자동 패치 기능을 활성화합니다.

    다음 코드는 두 개의 MCP 수학 도구를 사용하는 Claude 에이전트를 생성하고 실행하며, Weave는 실행 중 트레이스를 수집하고 기록합니다.

    ```python lines highlight="11" theme={"system"}
    import anyio
    import weave

    from claude_agent_sdk import (
        ClaudeAgentOptions,
        ClaudeSDKClient,
        create_sdk_mcp_server,
        tool,
    )

    weave.init("<your-team>/<your-project-name>")

    @tool("add", "Add two numbers", {"a": float, "b": float})
    async def add(args: dict) -> dict:
        return {"content": [{"type": "text", "text": str(args["a"] + args["b"])}]}

    @tool("multiply", "Multiply two numbers", {"a": float, "b": float})
    async def multiply(args: dict) -> dict:
        return {"content": [{"type": "text", "text": str(args["a"] * args["b"])}]}

    math_server = create_sdk_mcp_server(
        name="math",
        version="1.0.0",
        tools=[add, multiply],
    )

    async def main():
        options = ClaudeAgentOptions(
            mcp_servers={"math": math_server},
            allowed_tools=["mcp__math__add", "mcp__math__multiply"],
        )

        async with ClaudeSDKClient(options=options) as client:
            await client.query("Using the math tools, compute (3 + 7) * 2.")

            async for message in client.receive_response():
                print(message)


    anyio.run(main)
    ```

    스크립트가 실행되면 `weave.init()`이 프로젝트 링크를 출력합니다. 링크를 열어 에이전트의 쿼리, 모델 응답 및 도구 Call에 대해 캡처된 트레이스를 확인하세요.
  </Tab>

  <Tab title="TypeScript">
    Weave는 모듈 로더 훅을 통해 `query()`를 자동으로 계측합니다. 필요한 설정은 모듈 시스템에 따라 약간 다릅니다. CommonJS와 ESM의 차이점 및 Weave'의 로더 훅 작동 방식에 대한 자세한 내용은 [TypeScript SDK 서드 파티 인테그레이션 가이드](/ko/products/wandb/weave/guides/integrations/js)를 참조하세요.

    * **CommonJS 프로젝트**: 추가 설정이 필요하지 않습니다. 자동 계측이 먼저 실행되도록 `@anthropic-ai/claude-agent-sdk`보다 먼저 `weave`를 require하세요.
    * **ESM 프로젝트**: 다른 모듈보다 먼저 계측이 로드되도록 `--import=weave/instrument` 플래그로 Node를 시작하세요.

    이 예제는 `wikipedia_search` MCP 도구를 정의하고 세 턴으로 구성된 대화를 실행합니다. 각 턴은 별도의 `query()` 호출이지만, 이후 턴에서는 첫 번째 턴의 `session_id`와 함께 `resume`을 전달하여 Weave Agents 뷰에서 모든 턴을 하나의 세션으로 그룹화합니다. 처음 두 턴은 Wikipedia 검색을 트리거하고, 세 번째 턴은 이전 대화 컨텍스트를 사용하여 도구 Call 없이 요약을 생성합니다.

    ```typescript lines highlight="36" title="main.mjs" theme={"system"}
    import * as weave from "weave";
    import { createSdkMcpServer, query, tool, type Options } from "@anthropic-ai/claude-agent-sdk";
    import { z } from "zod";

    const wikipediaSearch = tool(
        "wikipedia_search",
        "Search Wikipedia for a topic and return its title and intro paragraph.",
        { query: z.string().describe("The topic to search for") },
        async ({ query }) => {
        const url = new URL("https://en.wikipedia.org/w/api.php");
        url.search = new URLSearchParams({
            action: "query",
            generator: "search",
            gsrsearch: query,
            gsrlimit: "1",
            prop: "extracts",
            exintro: "true",
            explaintext: "true",
            format: "json",
        }).toString();

        const response = await fetch(url, { headers: { "User-Agent": "weave-demo" } });
        const data = await response.json();
        const page = Object.values(data.query.pages)[0] as { title: string; extract: string };
        return { content: [{ type: "text" as const, text: `${page.title}: ${page.extract}` }] };
        },
    );

    const wikiServer = createSdkMcpServer({
        name: "wiki",
        version: "1.0.0",
        tools: [wikipediaSearch],
    });

    async function main() {
        await weave.init("<your-team>/<your-project-name>");

        const baseOptions: Options = {
        model: "claude-sonnet-4-5",
        maxTurns: 4,
        mcpServers: { wiki: wikiServer },
        allowedTools: ["mcp__wiki__wikipedia_search"],
        };

        const questions = [
        "Who founded Anthropic?",
        "What is Claude (the AI assistant)?",
        "Summarize what we discussed in one sentence.",
        ];

        let sessionId: string | undefined;

        for (const prompt of questions) {
        const options: Options = sessionId
            ? { ...baseOptions, resume: sessionId }
            : baseOptions;

        console.log(`USER: ${prompt}`);
        for await (const message of query({ prompt, options })) {
            if (message.type === "system" && message.subtype === "init") {
            sessionId ??= message.session_id;
            }
            if (message.type === "result" && message.subtype === "success") {
            console.log(`AGENT: ${message.result}\n`);
            }
        }
        }
    }

    main().catch(console.error);
    ```

    각 `query()` 호출은 `invoke_agent` 루트 span을 생성합니다. 후속 턴은 동일한 `session_id`로 재개되므로, Weave는 모든 span에 동일한 `gen_ai.conversation.id`를 기록하고 Agents 뷰에서 하나의 세션으로 그룹화합니다.

    예시를 `main.mjs`로 저장하고 `--import=weave/instrument` 플래그로 실행하여 로더 훅이 다른 모든 모듈보다 먼저 실행되도록 하세요:

    ```bash theme={"system"}
    node --import=weave/instrument main.mjs
    ```
  </Tab>
</Tabs>

<h3 id="see-your-agent-traces-in-the-agents-view">
  Agents 뷰에서 에이전트 트레이스 확인하기
</h3>

스크립트가 실행되면 `weave.init()`이 프로젝트 링크를 출력합니다. **Agents** 뷰를 열어 다음을 확인하세요:

* 대화의 턴을 포함하는 세션.
* 중첩된 `chat` 및 `execute_tool` 하위 항목이 있는 `invoke_agent` span으로 표시되는 각 턴.
* 각 단계의 전체 입력, 모델, 출력, 토큰 사용량 및 도구 결과.

Weave에서 Agents 데이터를 확인하는 방법에 대한 자세한 내용은 [에이전트 활동 확인하기](/ko/products/wandb/weave/guides/tracking/view-agent-activity)를 참조하세요.
