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

# Trace Claude Code applications

This guide shows you how to automatically send conversations from the [Claude Code CLI](https://code.claude.com/docs/en/overview) to LangSmith.

Once configured, each Claude Code project can opt in to sending traces to LangSmith. Each trace includes user messages, tool calls, compaction, subagent runs, and assistant responses. System prompts are not included, because Claude Code does not return them in conversation transcripts.

## Prerequisites

Before setting up tracing, ensure you have:

* [**Claude Code CLI**](https://code.claude.com/docs/en/overview) installed.
* A [**LangSmith API key**](https://smith.langchain.com/settings/apikeys).
* [**Node.js**](https://nodejs.org/) installed.

## Getting started

From within Claude Code, run:

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
/plugin marketplace add langchain-ai/langsmith-claude-code-plugins
/plugin install langsmith-tracing@langsmith-claude-code-plugins
/reload-plugins
```

To update the plugin, run:

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
/plugin marketplace update langsmith-claude-code-plugins
/reload-plugins
```

<Note> If you are migrating from the previously recommended version of tracing Claude Code with manually created stop hooks, see [Migrating from the manual stop hook](#migrating-from-the-manual-stop-hook). </Note>

### Setting environment variables

**Option 1: Project-level configuration (recommended)**

The plugin requires the following environment variables:

* `TRACE_TO_LANGSMITH: "true"` - Enables tracing for this project. Remove or set to `false` to disable tracing.
* `CC_LANGSMITH_API_KEY` - Your LangSmith API key
* `CC_LANGSMITH_PROJECT` - The LangSmith project name where traces are sent
* (optional) `CC_LANGSMITH_METADATA` - JSON object of custom metadata to attach to all runs (e.g. PR URL, author)
* (optional) `CC_LANGSMITH_DEBUG: "true"` - Enables detailed debug logging. Remove or set to `false` to disable debug logging.

The easiest way to get set up is to create or edit [Claude Code's project settings file](https://code.claude.com/docs/en/settings#:~:text=Project%20settings%20are%20saved%20in%20your%20project%20directory%3A). Create a `.claude/settings.local.json` in your project directory and populate it as follows:

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  "env": {
    "TRACE_TO_LANGSMITH": "true",
    "CC_LANGSMITH_API_KEY": "<LangSmith API key>",
    "CC_LANGSMITH_PROJECT": "my-project"
  }
}
```

<Note> Alternatively, to enable tracing to LangSmith for all Claude Code sessions, you can add the above JSON to your [global Claude Code settings.json](https://code.claude.com/docs/en/settings#:~:text=User%20settings%20are%20defined%20in%20~/.claude/settings.json%20and%20apply%20to%20all%20projects.) file. </Note>

**Option 2: Shell environment variables**

Run the following commands in your shell or add them to your shell configuration file (`~/.zshrc`, `~/.bashrc`, or `~/.bash_profile`):

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
export TRACE_TO_LANGSMITH="true"
export CC_LANGSMITH_API_KEY="<LangSmith API key>"
export CC_LANGSMITH_PROJECT="my-project"
```

## Verify setup

Traces will appear complete in LangSmith after Claude Code responds. Note that if you interrupt a run while it is in progress, the plugin will only flush that run when you send the next message or end the session.

In LangSmith, you'll see:

* Each message to Claude Code appears as a trace.
* All turns from the same Claude Code session are grouped using a shared `thread_id` and can be viewed in the **Threads** tab of a project.

## Custom metadata

Set the `CC_LANGSMITH_METADATA` environment variable to a JSON object to attach custom metadata to all traced runs. This is useful for tagging traces with contextual information such as PR URLs, authors, or environment names.

<Tabs>
  <Tab title="Settings file (recommended)">
    ```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    {
      "env": {
        "TRACE_TO_LANGSMITH": "true",
        "CC_LANGSMITH_API_KEY": "<LangSmith API key>",
        "CC_LANGSMITH_PROJECT": "my-project",
        "CC_LANGSMITH_METADATA": "{\"author\":\"jane\",\"environment\":\"development\"}"
      }
    }
    ```
  </Tab>

  <Tab title="Shell environment variable">
    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    export CC_LANGSMITH_METADATA='{"author":"jane","environment":"development"}'
    ```
  </Tab>
</Tabs>

The metadata keys and values will appear on all runs in LangSmith, which you can use to filter and search traces.

## Usage with GitHub Actions

You can use this plugin with [`anthropics/claude-code-action`](https://github.com/anthropics/claude-code-action) to trace Claude Code runs in CI. Add the following to your workflow:

```yaml theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
- uses: anthropics/claude-code-action@v1
  env:
    TRACE_TO_LANGSMITH: "true"
    CC_LANGSMITH_API_KEY: ${{ secrets.LANGSMITH_API_KEY }}
    CC_LANGSMITH_PROJECT: "my-project"
    CC_LANGSMITH_METADATA: |
      {
        "pr_url": "${{ github.event.pull_request.html_url || '' }}",
        "pr_number": "${{ github.event.pull_request.number || '' }}",
        "pr_author": "${{ github.event.pull_request.user.login || '' }}",
        "repository": "${{ github.repository }}",
        "commit_sha": "${{ github.sha }}",
        "trigger": "${{ github.event_name }}"
      }
  with:
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
    github_token: ${{ secrets.GITHUB_TOKEN }}
    plugin_marketplaces: |
      https://github.com/langchain-ai/langsmith-claude-code-plugins.git
    plugins: |
      langsmith-tracing@langsmith-claude-code-plugins
    prompt: |
      Your prompt here
```

Make sure to add `LANGSMITH_API_KEY` and `ANTHROPIC_API_KEY` as [repository secrets](https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions).

This lets you correlate traces back to specific PRs, commits, and authors in LangSmith.

## Nesting traces under an existing run

You can also set an environment variable named `CC_LANGSMITH_PARENT_DOTTED_ORDER` to nest all Claude Code traces as children of an existing LangSmith run. This is useful when Claude Code is invoked programmatically as part of a larger traced workflow.

**Python**

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import subprocess
from langsmith import traceable, get_current_run_tree


os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_API_KEY"] = "<LangSmith API key>"
os.environ["LANGSMITH_PROJECT"] = "claude-code"

@traceable
def run_claude(prompt: str):
    run_tree = get_current_run_tree()
    subprocess.run(
        ["claude", "-p", prompt],
        env={
            **os.environ,
            "TRACE_TO_LANGSMITH": "true",
            "CC_LANGSMITH_API_KEY": "<LangSmith API key>",
            "CC_LANGSMITH_PROJECT": "claude-code",
            "CC_LANGSMITH_PARENT_DOTTED_ORDER": run_tree.dotted_order,
        },
    )
```

**TypeScript**

```ts theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { traceable, getCurrentRunTree } from "langsmith/traceable";
import { execSync } from "node:child_process";

process.env.LANGSMITH_TRACING = "true";
process.env.LANGSMITH_API_KEY = "<LangSmith API key>";
process.env.LANGSMITH_PROJECT = "claude-code";

const runClaude = traceable(
  async (prompt: string) => {
    const runTree = getCurrentRunTree();
    const pluginDir = new URL(".", import.meta.url).pathname;
    const res = execSync(`claude -p "${prompt}" --plugin-dir '${pluginDir}'`, {
      env: {
        ...process.env,
        TRACE_TO_LANGSMITH: "true",
        CC_LANGSMITH_API_KEY: "<LangSmith API key>",
        CC_LANGSMITH_PROJECT: "claude-code",
        CC_LANGSMITH_PARENT_DOTTED_ORDER: runTree.dotted_order,
      },
    });
    return res.toString();
  },
  { name: "run_claude" },
);
```

The resulting trace hierarchy looks like:

```
Your outer run (chain)
└── Claude Code Turn (chain)
    ├── Claude (llm)
    ├── Read (tool)
    └── Claude (llm)
```

## Trace to multiple destinations (replicas)

You can trace to multiple LangSmith projects or workspaces simultaneously using the `CC_LANGSMITH_RUNS_ENDPOINTS` environment variable. Set `CC_LANGSMITH_RUNS_ENDPOINTS` to a JSON array of replica configurations. This overrides other client settings.

Tracing to multiple [replicas](/langsmith/log-traces-to-project) is useful for:

* Sending traces to both a production and staging project
* Tracing to multiple workspaces with different API keys
* Adding extra metadata to specific replica destinations

Each replica object supports the following fields:

| Field         | Required | Description                                                     |
| ------------- | -------- | --------------------------------------------------------------- |
| `apiUrl`      | Yes      | LangSmith API URL (typically `https://api.smith.langchain.com`) |
| `apiKey`      | Yes      | API key for the destination workspace                           |
| `projectName` | Yes      | Project name in the destination workspace                       |
| `updates`     | No       | Optional metadata/fields to override on the replicated runs     |

There are two ways to set the `CC_LANGSMITH_RUNS_ENDPOINTS` environment variable:

<Tabs>
  <Tab title="Settings file (recommended)">
    In your local `.claude/settings.local.json` or global `~/.claude/settings.json`:

    ```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    {
      "env": {
        "TRACE_TO_LANGSMITH": "true",
        "CC_LANGSMITH_RUNS_ENDPOINTS": "[{\"apiUrl\":\"https://api.smith.langchain.com\",\"apiKey\":\"ls__key_workspace_a\",\"projectName\":\"project-prod\"},{\"apiUrl\":\"https://api.smith.langchain.com\",\"apiKey\":\"ls__key_workspace_b\",\"projectName\":\"project-staging\",\"updates\":{\"metadata\":{\"environment\":\"staging\"}}}]"
      }
    }
    ```

    <Tip>
      To generate the escaped JSON string, use:

      ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      echo '[{"apiUrl":"...","apiKey":"...","projectName":"..."}]' | jq -cR .
      ```
    </Tip>
  </Tab>

  <Tab title="Shell environment variable">
    **Option 2: Shell environment variable**

    Add to your `~/.zshrc`, `~/.bashrc`, or `~/.bash_profile`:

    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    export CC_LANGSMITH_RUNS_ENDPOINTS='[{"apiUrl":"https://api.smith.langchain.com","apiKey":"ls__key_workspace_a","projectName":"project-prod"},{"apiUrl":"https://api.smith.langchain.com","apiKey":"ls__key_workspace_b","projectName":"project-staging","updates":{"metadata":{"environment":"staging"}}}]'
    ```
  </Tab>
</Tabs>

## Troubleshooting

### No traces appearing in LangSmith

1. **Check the hook is running**:
   ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
   tail -f ~/.claude/state/hook.log
   ```
   You should see log entries after each Claude response.

2. **Verify environment variables**:
   * Check that `TRACE_TO_LANGSMITH="true"` in your project's `.claude/settings.local.json`
   * Verify your Personal Access Token (PAT) is correct (starts with `lsv2_pt_`)
   * Ensure the project name exists in LangSmith

3. **Enable debug mode** to see detailed API activity:
   ```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
   {
     "env": {
       "CC_LANGSMITH_DEBUG": "true"
     }
   }
   ```
   Then check logs for API calls and HTTP status codes.

### Subagent runs do not appear after user interruption

Currently, subagents are only traced upon completion. This means if you interrupt a conversation turn in the middle of a subagent run,
the subagent's child runs will not be traced.

### Managing log file size

The hook logs all activity to `~/.claude/state/hook.log`. With debug mode enabled, this file can grow large:

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# View log file size
ls -lh ~/.claude/state/hook.log

# Clear logs if needed
> ~/.claude/state/hook.log
```

## Migrating from the manual stop hook

If you were using the previous version of tracing Claude Code with LangSmith, you will need to remove `~/.claude/hooks/stop_hook.sh` and remove the reference to the hook from any previous `settings.local.json` or `settings.json` files you added it to previously, then following the [plugin installation instructions](#getting-started) above.

## Source code

The plugin is open-source under the MIT license and is available in [this GitHub repo](https://github.com/langchain-ai/langsmith-claude-code-plugins).

***

<div className="source-links">
  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>

  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/langsmith/trace-claude-code.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>
</div>
