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

> Trace an agent built with the Claude Agent SDK using 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="/products/agent-lens/integrations/claude-agents-sdk" />

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 multi-turn Claude agent with MCP tools through `query()`. Weave automatically traces the conversation, model calls, and tool calls end-to-end.

    ### Prerequisites

    * A CoreWeave Forge account and [API key](https://forge.coreweave.com/settings#apikeys) 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 CoreWeave Forge account and [API key](https://forge.coreweave.com/settings#apikeys) 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, `claude-agent-sdk` provides the agent runtime, and the remaining packages support the example tool.

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

### Initialize Weave in your code

<Tabs>
  <Tab title="Python">
    Add `weave.init` to the project, update your CoreWeave Forge 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.

    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 conversation 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.

    ```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-name>")

    @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)
    ```

    Each `query()` call produces an `invoke_agent` root span. Because the follow-up turns resume the same session, Weave stamps the same `gen_ai.conversation.id` on all spans and groups them as one conversation in the Agents view. `ResultMessage.session_id` carries the ID to reuse, and `resume` accepts `None` on the first turn, which starts a new session.

    Without `resume`, each turn starts its own session and appears as a separate conversation. `ClaudeSDKClient` is the exception: it holds one session open for the lifetime of the `async with` block, so turns you send through the same client are already grouped. Weave patches both paths.
  </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](/products/wandb/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={"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);
    ```

    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={"system"}
    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](/products/wandb/weave/guides/tracking/view-agent-activity).
