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

# LangGraph

> Trace LangGraph agent workflows with automatic callback propagation

# LangGraph

LangGraph is built on LangChain's `Runnable` system. The same `MutagentCallbackHandler` from `@mutagent/langchain` works automatically for all LangGraph graphs — every node execution, LLM call, tool invocation, and retriever query within the graph is captured without any LangGraph-specific instrumentation.

<Note>
  Both `@mutagent/langchain` and `@mutagent/langgraph` packages are available for LangGraph integration. The `@mutagent/langchain` callback handler propagates through the entire graph execution tree via LangChain's `inheritable_handlers` mechanism.
</Note>

## Installation

<CodeGroup>
  ```bash bun theme={null}
  bun add @mutagent/langchain @mutagent/sdk
  ```

  ```bash npm theme={null}
  npm install @mutagent/langchain @mutagent/sdk
  ```

  ```bash yarn theme={null}
  yarn add @mutagent/langchain @mutagent/sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @mutagent/langchain @mutagent/sdk
  ```
</CodeGroup>

**Peer dependencies:** `@mutagent/sdk >=0.1.0`, `@langchain/langgraph >=1.0.1`

## Quick Start

<Steps>
  <Step title="Initialize tracing">
    Call `initTracing()` once at application startup.

    ```typescript theme={null}
    import { initTracing } from '@mutagent/sdk/tracing';

    initTracing({ apiKey: process.env.MUTAGENT_API_KEY! });
    ```
  </Step>

  <Step title="Create the callback handler">
    ```typescript theme={null}
    import { MutagentCallbackHandler } from '@mutagent/langchain';

    const handler = new MutagentCallbackHandler({
      sessionId: 'my-session',  // optional
      userId: 'user-123',       // optional
    });
    ```
  </Step>

  <Step title="Pass to graph.invoke()">
    ```typescript theme={null}
    const result = await graph.invoke(input, {
      callbacks: [handler],
    });
    // Full graph execution tree is automatically traced
    ```
  </Step>
</Steps>

## Full Example

```typescript theme={null}
import { initTracing } from '@mutagent/sdk/tracing';
import { MutagentCallbackHandler } from '@mutagent/langchain';
import { StateGraph, MessagesAnnotation } from '@langchain/langgraph';
import { ChatOpenAI } from '@langchain/openai';

// 1. Initialize SDK tracing (once at app startup)
initTracing({ apiKey: process.env.MUTAGENT_API_KEY! });

// 2. Build your LangGraph graph as usual
const model = new ChatOpenAI({ model: 'gpt-4o' });

const callModel = async (state: typeof MessagesAnnotation.State) => {
  const response = await model.invoke(state.messages);
  return { messages: [response] };
};

const graph = new StateGraph(MessagesAnnotation)
  .addNode('agent', callModel)
  .addEdge('__start__', 'agent')
  .addEdge('agent', '__end__')
  .compile();

// 3. Create the handler and invoke
const handler = new MutagentCallbackHandler();
const result = await graph.invoke(
  { messages: [{ role: 'user', content: 'Hello!' }] },
  { callbacks: [handler] },
);
```

## How Callback Propagation Works

When you pass the `MutagentCallbackHandler` to `graph.invoke()`, LangChain's callback system automatically propagates it through the entire execution tree:

<Mermaid>
  graph TD
  G\["graph.invoke() — chain span"] --> N1\["node: agent — chain span"]
  N1 --> L1\["ChatOpenAI — llm.chat span"]
  L1 --> T1\["tool: search — tool span"]
  G --> N2\["node: agent (2nd pass) — chain span"]
  N2 --> L2\["ChatOpenAI — llm.chat span"]
</Mermaid>

The callback handler uses LangChain's `inheritable_handlers` — meaning every child `Runnable` (nodes, LLMs, tools, retrievers) inside the graph automatically receives the handler. You do not need to pass it to individual nodes.

## What Gets Traced

| Event            | Span Kind   | Data Captured                     |
| ---------------- | ----------- | --------------------------------- |
| Graph invocation | `chain`     | Graph name, input/output          |
| Node execution   | `chain`     | Node name, input/output           |
| LLM call         | `llm.chat`  | Messages, model, token usage      |
| Tool call        | `tool`      | Tool name, input/output           |
| Retriever query  | `retrieval` | Query string, retrieved documents |
| Errors           | Any         | Error message, status             |

## Handler Options

```typescript theme={null}
const handler = new MutagentCallbackHandler({
  sessionId: 'chat-session-123',  // Group traces by session
  userId: 'user-456',             // Attribute traces to a user
  tags: ['production', 'v2'],     // Filter traces by tag
  metadata: { version: '2.0' },   // Custom metadata
});
```

| Option      | Type                      | Description                         |
| ----------- | ------------------------- | ----------------------------------- |
| `sessionId` | `string`                  | Group related traces into a session |
| `userId`    | `string`                  | Attribute traces to a specific user |
| `tags`      | `string[]`                | Tags for filtering in the dashboard |
| `metadata`  | `Record<string, unknown>` | Custom key-value metadata           |

## Migration from `@mutagent/langgraph`

<Warning>
  `@mutagent/langgraph` and its `MutagentGraphTracer` are **deprecated**. The package now re-exports `MutagentCallbackHandler` from `@mutagent/langchain` for backwards compatibility, but will be removed in a future version.
</Warning>

**Before (deprecated):**

```typescript theme={null}
import { MutagentGraphTracer } from '@mutagent/langgraph';
const tracer = new MutagentGraphTracer();
tracer.handleGraphStart('my-graph', inputs);
// ... manually call every node/edge transition
tracer.handleGraphEnd(outputs);
```

**After (recommended):**

```typescript theme={null}
import { MutagentCallbackHandler } from '@mutagent/langchain';
const handler = new MutagentCallbackHandler();
const result = await graph.invoke(input, { callbacks: [handler] });
```

## CLI Shortcut

```bash theme={null}
mutagent integrate langgraph
```

## Python

Looking for the Python LangGraph integration? See the [Python LangGraph guide](/integrations/python/langgraph).
