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

> Claude Agent SDK を使用して構築されたエージェントを Weave でトレースします。

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="/ja/products/agent-lens/integrations/claude-agents-sdk" />

Claude Agent SDK を使用すると、Claude を活用したエージェントアプリケーションをすばやく構築できます。Claude エージェントに Weave を統合すると、エージェントへのクエリ、モデルの応答、ツールの使用、マルチターンの会話を含む Call を自動的にトレースできます。Weave は取得したデータを project の **Agents** ビューに表示します。

<h2 id="trace-claude-agent-sdk-agents-with-weave">
  Weave で 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 を初期化し、`ClaudeSDKClient` を通じて MCP ツールを使用する Claude エージェントを実行する方法を説明します。Weave は、会話、モデルの 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) と連携し、エージェント スパン、モデルの応答、ツール呼び出しを含む `query()` の呼び出しを自動的にトレースします。

    <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` を project に追加し、CoreWeave Forge のチーム名と project 名を更新してから、通常どおりにエージェントを構築してください。`weave.init` は Claude Agent SDK からのトレースを 取得する 自動パッチ適用を有効にします。

    次のコードは、2 つの 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()` が project へのリンクを出力します。リンクを開くと、エージェントのクエリ、モデルの応答、ツール呼び出しについて取得されたトレースを確認できます。
  </Tab>

  <Tab title="TypeScript">
    Weave はモジュールローダーフックを介して `query()` を自動的にインストルメントします。必要な設定はモジュールシステムによって少し異なります。CommonJS と ESM の違い、および Weave のローダーフックの仕組みについて詳しくは、[TypeScript SDK サードパーティインテグレーションガイド](/ja/products/wandb/weave/guides/integrations/js)をご覧ください。

    * **CommonJS project**: 追加の設定は不要です。自動インストルメンテーションが先に実行されるように、`@anthropic-ai/claude-agent-sdk` より前に `weave` を require してください。
    * **ESM project**: インストルメンテーションが他のモジュールより先に読み込まれるように、`--import=weave/instrument` フラグを指定して Node を起動してください。

    この例では、`wikipedia_search` MCP ツールを定義し、3 ターンの会話を実行します。各ターンは個別の `query()` 呼び出しですが、後続のターンでは最初のターンの `session_id` を `resume` に渡すことで、すべてのターンが Weave Agents ビューで 1 つのセッションとしてグループ化されます。最初の 2 ターンでは Wikipedia のルックアップを実行し、3 番目のターンでは前の会話のコンテキストを使用して、ツール呼び出しなしで要約を生成します。

    ```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` ルートスパンを生成します。後続のターンは同じ `session_id` を再開するため、Weave はすべてのスパンに同じ `gen_ai.conversation.id` を付与し、Agents ビューで 1 つのセッションとしてまとめます。

    例を `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()` によって project へのリンクが出力されます。**Agents** ビューを開くと、次の内容を確認できます。

* 会話のターンを含むセッション
* `invoke_agent` スパンとしてレンダリングされた各ターン (子として `chat` と `execute_tool` がネストされます)
* 各ステップの入力、モデル、出力、トークン使用量、ツール結果の全容

Weave で Agents データを表示する方法の詳細については、[エージェントのアクティビティを表示する](/ja/products/wandb/weave/guides/tracking/view-agent-activity)を参照してください。
