> ## 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 の呼び出しを自動的にトレースし、クエリ、ツールの使用状況、複数ターンの会話を記録します。

このガイドでは、Claude Agent SDK アプリケーションを Weave で計装し、Weave UI で各クエリ、ツール呼び出し、会話の各ターンを確認する方法を説明します。これは、カスタムのトレースコードを記述せずにエンドツーエンドの可観測性を実現したい、Claude ベースのエージェントを構築する開発者を対象としています。

<div id="prerequisites">
  ## 前提条件
</div>

コード例を実行する前に、Weave が認証を行い、トレースを project にルーティングできるよう、以下のセットアップを完了してください。

* `weave.init()` の呼び出しで、`your-team-name` をご利用の W\&B チーム名に置き換えます。
* 環境変数に `WANDB_API_KEY` と `ANTHROPIC_API_KEY` を設定します。W\&B APIキーの詳細は、[API keys](/ja/platform/app/settings-page/user-settings#api-keys) を参照してください。

<div id="installation">
  ## インストール
</div>

`pip` を使用して、Weave と Claude Agent SDK の両方を環境で利用できるように、必要な依存関係をインストールします。

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

<div id="get-started">
  ## はじめに
</div>

このセクションでは、1 つの run の中で Weave が Claude Agent SDK のさまざまな使用パターンをどのようにトレースするかを示す、完全な例を紹介します。

Claude Agent SDK を使用する前に `weave.init()` を呼び出すと、Weave は自動的に SDK にパッチを適用し、すべてのクエリをトレースします。

次の例では、3 つの機能を紹介します。

* `query()` 関数を使用した**シンプルな単発クエリ**。モデルの応答とコストも含まれます。
* `ClaudeSDKClient` を使用した **MCP ツール の利用**。Claude Agent SDK は、インプロセスの MCP server を通じて custom ツール をサポートします。
  * Weave は、ツール の定義、ツール の呼び出し、結果をエージェントのクエリとあわせてトレースします。
  * この MCP デモでは、2 つの MCP ツール を定義し、それらを使用するクエリを実行します。
* `weave.thread()` によって 1 つのトレースにグループ化される**複数ターンの会話**。Weave は各ターンをスレッドの子として取得するため、Weave UI で会話全体の流れを確認できます。

```python lines theme={null}
"""Weave + Claude Agent SDK: tracing queries, tools, and conversations.

Call `weave.init()` to auto-patch the SDK — every query, tool call, and
multi-turn conversation is recorded as a trace you can inspect in the 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. シンプルなワンショットクエリ ---

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 は project に一連のトレースを記録します。これらのトレースは、エージェントの動作のデバッグや分析に使用できます。

この例を実行すると、Weave ダッシュボードへのリンクが表示されます。リンクを開くと、クエリの入力、モデルの応答、ツール呼び出し、会話スレッドなどを含むトレースを確認できます。
