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

# Claude Agent SDK

> Trace an agent built with the Claude Agent SDK using Weave.

The Claude Agent SDK enables you to quickly build agent applications powered by Claude. You can integrate Weave into you Claude agents to automatically trace their calls, including agent queries, model responses, tool use, and multi-turn conversations. Weave displays the captured data in the **Agents** view of your project.

## Trace Claude Agent SDK agents with Weave

<Tabs>
  <Tab title="Python">
    The Weave SDK autopatches the [Claude Agent SDK for Python](https://github.com/anthropics/claude-agent-sdk-python), letting you capture traces from your Claude agents with minimal setup.

    This guide shows how to initialize Weave and run a Claude agent with MCP tools through `ClaudeSDKClient`. Weave automatically traces the conversation, model calls, and tool calls end-to-end.

    ### Prerequisites

    * A W\&B account and [API key](https://wandb.ai/authorize) set as a `WANDB_API_KEY` environment variable.
    * An Anthropic API key set as an `ANTHROPIC_API_KEY` environment variable.
    * Python 3.10+.
  </Tab>

  <Tab title="TypeScript">
    Weave integrates with the [`@anthropic-ai/claude-agent-sdk`](https://github.com/anthropics/claude-agent-sdk) to automatically trace `query()` calls, including agent spans, model responses, and tool calls.

    ### Prerequisites

    * A W\&B account and [API key](https://wandb.ai/authorize) set as a `WANDB_API_KEY` environment variable.
    * An Anthropic API key set as an `ANTHROPIC_API_KEY` environment variable.
    * Node.js 18+.
    * `@anthropic-ai/claude-agent-sdk` version `0.3.178` or later.
  </Tab>
</Tabs>

### Install packages

Install the following packages in your developer environment. The `weave` package captures traces, and `claude-agent-sdk` provides the agent runtime.

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

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

### Initialize Weave in your code

<Tabs>
  <Tab title="Python">
    Add `weave.init` to the project, update your W\&B team and project names, and then build an agent the way you normally would. `weave.init` enables the autopatching that captures traces from the Claude Agent SDK.

    The following code creates a Claude agent with two MCP math tools and runs it while Weave captures the traces.

    ```python lines highlight="11" theme={null}
    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)
    ```

    When the script runs, `weave.init()` prints a link to your project. Open the link to inspect the captured traces for the agent's query, model responses, and tool calls.
  </Tab>

  <Tab title="TypeScript">
    Weave automatically instruments `query()` via module loader hooks. The required setup differs slightly between module systems. For more information on CommonJS versus ESM and how Weave's loader hooks work, see the [TypeScript SDK third-party integration guide](/weave/guides/integrations/js).

    * **CommonJS projects**: No extra configuration needed. Require `weave` before `@anthropic-ai/claude-agent-sdk` so auto-instrumentation runs first.
    * **ESM projects**: Start Node with the `--import=weave/instrument` flag so the instrumentation loads before any other modules.

    This example defines a `wikipedia_search` MCP tool and runs a three-turn conversation. Each turn is a separate `query()` call, but later turns pass `resume` with the first turn's `session_id` so that all turns group as one session in the Weave Agents view. The first two turns trigger Wikipedia lookups, and the third uses the previous conversation context to produce a summary without a tool call.

    ```typescript lines highlight="36" title="main.mjs" theme={null}
    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);
    ```

    Each `query()` call produces an `invoke_agent` root span. Because the follow-up turns resume the same `session_id`, Weave stamps the same `gen_ai.conversation.id` on all spans and groups them as one session in the Agents view.

    Save the example as `main.mjs` and run it with the `--import=weave/instrument` flag so the loader hook runs before any other module:

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

### See your agent traces in the Agents view

After the script runs, `weave.init()` prints a link to your project. Open the **Agents** view to inspect:

* A session containing the conversation's turns.
* Each turn rendered as an `invoke_agent` span with nested `chat` and `execute_tool` children.
* The full input, model, output, token usage, and tool results at each step.

For details about viewing Agents data in Weave, see [View agent activity](/weave/guides/tracking/view-agent-activity).
