> ## Documentation Index
> Fetch the complete documentation index at: https://wb-21fd5541-mintlify-8476678c.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Claude Agent SDK

> Claude Agent SDK와 함께 W&B Weave를 사용해 에이전트의 쿼리, 도구 호출, 멀티턴 대화를 트레이스하세요.

[Claude Agent SDK](https://github.com/anthropics/claude-agent-sdk-python)는 Claude로 에이전트 애플리케이션을 구축할 수 있도록 Anthropic에서 제공하는 Python SDK입니다. `weave.init()`를 호출하면 W\&B Weave가 Claude Agent SDK call을 자동으로 트레이스하여 쿼리, 도구 사용, 멀티턴 대화를 캡처합니다.

이 가이드에서는 Weave로 Claude Agent SDK 애플리케이션을 계측하여 Weave UI에서 모든 쿼리, 도구 호출, 대화 턴을 확인하는 방법을 보여드립니다. 이 문서는 맞춤형 트레이싱 코드를 작성하지 않고도 종단 간 관측성을 확보하려는 Claude 기반 에이전트 개발자를 위한 것입니다.

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

코드 예제를 실행하기 전에 Weave가 인증하고 트레이스를 프로젝트로 라우팅할 수 있도록 다음 설정을 완료하세요:

* `weave.init()` 호출에서 `your-team-name`을 담당 W\&B 팀 이름으로 바꾸세요.
* 환경 변수에 `WANDB_API_KEY`와 `ANTHROPIC_API_KEY`를 설정하세요. W\&B API 키에 대한 자세한 내용은 [API 키](/ko/platform/app/settings-page/user-settings#api-keys)를 참조하세요.

<div id="installation">
  ## 설치
</div>

환경에서 Weave와 Claude Agent SDK를 모두 사용할 수 있도록 `pip`를 사용해 필요한 의존성을 설치합니다:

```bash theme={null}
pip install weave claude-agent-sdk
```

<div id="get-started">
  ## 시작하기
</div>

이 섹션에서는 Weave가 단일 run에서 Claude Agent SDK의 다양한 사용 패턴을 어떻게 트레이스하는지 보여 주는 전체 예시를 살펴봅니다.

Claude Agent SDK를 사용하기 전에 `weave.init()`를 호출하면 Weave가 SDK를 자동으로 패치하고 모든 쿼리를 트레이스합니다.

다음 예시에서는 세 가지 기능을 보여 줍니다.

* `query()` 함수를 사용한 **간단한 단발성 쿼리**로, 모델 응답과 비용을 포함합니다.
* `ClaudeSDKClient`를 사용한 **MCP 도구 사용**. Claude Agent SDK는 인프로세스 MCP 서버를 통해 맞춤형 도구를 지원합니다.
  * Weave는 에이전트 쿼리와 함께 도구 정의, 도구 호출, 결과를 트레이스합니다.
  * MCP 데모에서는 두 개의 MCP 도구를 정의하고, 이를 사용하는 쿼리를 실행합니다.
* `weave.thread()`가 단일 트레이스로 묶는 **멀티턴 대화**. Weave는 각 턴을 스레드의 하위 항목으로 캡처하므로, Weave UI에서 전체 대화 흐름을 확인할 수 있습니다.

```python lines theme={null}
"""Weave + Claude Agent SDK: 쿼리, 도구, 대화 트레이싱.

`weave.init()`을 호출하여 SDK를 자동으로 패치하세요 — 모든 쿼리, 도구 Call,
멀티턴 대화가 Weave UI에서 확인할 수 있는 트레이스로 기록됩니다.
"""

import anyio

import weave
from claude_agent_sdk import (
    AssistantMessage,
    ClaudeAgentOptions,
    ClaudeSDKClient,
    ResultMessage,
    TextBlock,
    ToolUseBlock,
    create_sdk_mcp_server,
    tool,
)

# --- 1. MCP 도구 정의 ---

@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],
)


# --- 2. 단순 one-shot 쿼리 ---

async def simple_query():
    from claude_agent_sdk import query

    async for msg in query(prompt="What is 2+2?"):
        if isinstance(msg, AssistantMessage):
            for block in msg.content:
                if isinstance(block, TextBlock):
                    print(block.text, end="")
        elif isinstance(msg, ResultMessage):
            print(f"\ncost=${msg.total_cost_usd:.4f}")


# --- 3. MCP 도구 사용 ---

async def tool_query():
    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 msg in client.receive_response():
            if isinstance(msg, AssistantMessage):
                for block in msg.content:
                    if isinstance(block, ToolUseBlock):
                        print(f"  [tool] {block.name}({block.input})")
                    elif isinstance(block, TextBlock):
                        print(block.text, end="")
            elif isinstance(msg, ResultMessage):
                print(f"\ncost=${msg.total_cost_usd:.4f}")


# --- 4. 스레드 컨텍스트를 활용한 멀티턴 대화 ---

async def threaded_conversation():
    with weave.thread("my-conversation") as t:
        print(f"thread_id={t.thread_id}")

        async with ClaudeSDKClient() as client:
            for prompt in [
                "Name a famous sorting algorithm.",
                "What is its time complexity?",
            ]:
                await client.query(prompt)
                reply = ""
                async for msg in client.receive_response():
                    if isinstance(msg, AssistantMessage):
                        reply += "".join(
                            b.text for b in msg.content if isinstance(b, TextBlock)
                        )
                    elif isinstance(msg, ResultMessage):
                        print(f"Q: {prompt}\nA: {reply.strip()[:120]}\n")


# --- 모든 예시 실행 ---

async def main():
    print("=== Simple Query ===")
    await simple_query()

    print("\n=== MCP Tool Use ===")
    await tool_query()

    print("\n=== Multi-Turn Thread ===")
    await threaded_conversation()


if __name__ == "__main__":
    weave.init("your-team-name/claude-agent-sdk-demo")
    anyio.run(main)
```

<div id="view-traces">
  ## 트레이스 보기
</div>

예제를 실행한 후에는 Weave가 프로젝트에 일련의 트레이스를 기록하며, 이를 사용해 에이전트의 동작을 디버그하고 분석할 수 있습니다.

예제를 실행하면 Weave가 Weave 대시보드로 연결되는 링크를 출력합니다. 링크를 열어 쿼리 입력, 모델 응답, 도구 호출, 대화 스레드를 포함한 트레이스를 확인하세요.
