> ## 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

> Agent Lens로 Claude Agent SDK 기반 에이전트를 트레이스하세요.

Claude Agent SDK를 사용하면 Claude 기반 에이전트 애플리케이션을 빠르게 구축할 수 있습니다. Claude 에이전트에 CoreWeave Agent Lens를 통합하면 에이전트 쿼리, 모델 응답, 도구 사용, 멀티턴 대화 등 에이전트의 Call을 자동으로 트레이스할 수 있습니다.

<Note>
  This integration uses the Weights & Biases Weave SDK (`weave`), because the CoreWeave Forge SDK doesn't support this framework yet. Traces you send with Weave appear in Agent Lens, because both products share the same trace data.
</Note>

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

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

    이 가이드에서는 Weave를 초기화하고 `query()`를 통해 MCP 도구를 사용하는 멀티턴 Claude 에이전트를 실행하는 방법을 설명합니다. Agent Lens는 대화, 모델 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 SDK는 [`@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 requests
  ```

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

<h3 id="initialize-agent-lens-in-your-code">
  코드에서 Agent Lens 초기화하기
</h3>

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

    이 예제에서는 `wikipedia_search` MCP 도구를 정의하고 3턴으로 구성된 대화를 실행합니다. 각 턴은 별도의 `query()` 호출이지만, 두 번째 턴부터는 첫 번째 턴의 세션 ID를 `resume`으로 전달합니다. 따라서 모든 턴이 Agent Lens **Conversations** 탭에서 하나의 대화로 그룹화됩니다. 처음 두 턴에서는 Wikipedia 조회가 트리거되고, 세 번째 턴에서는 도구 Call 없이 이전 대화 컨텍스트를 활용해 요약을 생성합니다.

    ```python lines highlight="13,49,55" theme={"system"}
    import anyio
    import requests
    import weave

    from claude_agent_sdk import (
        ClaudeAgentOptions,
        ResultMessage,
        create_sdk_mcp_server,
        query,
        tool,
    )

    weave.init("[YOUR-TEAM]/[YOUR-PROJECT]")

    @tool(
        "wikipedia_search",
        "Search Wikipedia for a topic and return its title and intro paragraph.",
        {"query": str},
    )
    async def wikipedia_search(args: dict) -> dict:
        r = requests.get(
            "https://en.wikipedia.org/w/api.php",
            params={
                "action": "query", "generator": "search", "gsrsearch": args["query"], "gsrlimit": 1,
                "prop": "extracts", "exintro": True, "explaintext": True, "format": "json",
            },
            headers={"User-Agent": "weave-demo"},
        ).json()
        page = next(iter(r["query"]["pages"].values()))
        return {"content": [{"type": "text", "text": f"{page['title']}: {page['extract']}"}]}

    wiki_server = create_sdk_mcp_server(
        name="wiki",
        version="1.0.0",
        tools=[wikipedia_search],
    )

    async def main():
        session_id = None

        for question in [
            "Who founded Anthropic?",
            "What is Claude (the AI assistant)?",
            "Summarize what we discussed in one sentence.",
        ]:
            options = ClaudeAgentOptions(
                mcp_servers={"wiki": wiki_server},
                allowed_tools=["mcp__wiki__wikipedia_search"],
                resume=session_id,
            )
            print(f"USER: {question}")

            async for message in query(prompt=question, options=options):
                if isinstance(message, ResultMessage):
                    session_id = message.session_id
                    print(f"AGENT: {message.result}\n")


    anyio.run(main)
    ```

    각 `query()` 호출은 `invoke_agent` 루트 span을 생성합니다. 후속 턴은 동일한 세션을 재개하므로 Weave는 모든 span에 동일한 `gen_ai.conversation.id`를 기록하고, Agent Lens는 이 span들을 하나의 대화로 묶습니다. 재사용할 ID는 `ResultMessage.session_id`에 담겨 있습니다. 첫 번째 턴에서는 `resume`에 `None`을 전달할 수 있으며, 이 경우 새 세션이 시작됩니다.

    `resume`을 사용하지 않으면 턴마다 새 세션이 시작되어 각각 별도의 대화로 표시됩니다. 단, `ClaudeSDKClient`는 예외입니다. 이 클라이언트는 `async with` 블록이 유지되는 동안 하나의 세션을 열어 두므로, 같은 클라이언트로 보내는 턴은 이미 하나로 묶여 있습니다. Weave는 두 방식 모두에 패치를 적용합니다.
  </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`에 전달하므로 모든 턴이 Agent Lens Conversations에서 하나의 세션으로 묶입니다. 처음 두 턴에서는 Wikipedia 조회가 트리거되고, 세 번째 턴에서는 도구 호출 없이 이전 대화 컨텍스트를 바탕으로 요약을 생성합니다.

    ```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]");

        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`로 세션을 재개하므로, Agent Lens는 모든 span에 동일한 `gen_ai.conversation.id`를 기록하고 Conversations 뷰에서 이를 하나의 세션으로 그룹화합니다.

    예시를 `main.mjs`로 저장한 다음, 로더 훅이 다른 모듈보다 먼저 실행되도록 `--import=weave/instrument` 플래그와 함께 실행하세요.

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

### View your traces in Agent Lens

After the script runs, `weave.init()` prints a link to your project in Weave. The same traces appear in Agent Lens, because both products share the same trace data. To view them in Agent Lens:

1. Navigate to [CoreWeave Forge](https://forge.coreweave.com) and select **Agent Lens** from the product menu.
2. Select your project.
3. In the Agent Lens side menu, select **Conversations**, and then select your conversation.

Each turn renders as an `invoke_agent` span with nested `chat` and `execute_tool` spans. Each span shows its input, model, output, token usage, and tool results.

For more information, see [View agent activity](/products/agent-lens/conversations/view-activity).
