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

# Observability

> Trace LangChainMCPAgent runs with Langfuse or custom LangChain callbacks.

`LangChainMCPAgent` passes callbacks, metadata, and tags into LangChain agent execution. Use the built-in Langfuse integration or provide your own LangChain callbacks.

## Trace a run with Langfuse

Install both Langfuse packages:

```bash theme={null}
npm install langfuse langfuse-langchain
```

Set credentials before the process imports `@mcp-use/agent/langchain`:

```bash theme={null}
export LANGFUSE_PUBLIC_KEY="pk-lf-..."
export LANGFUSE_SECRET_KEY="sk-lf-..."
export LANGFUSE_HOST="https://cloud.langfuse.com"
```

Then initialize and run the agent:

```typescript theme={null}
import { ChatOpenAI } from "@langchain/openai";
import { MCPClient } from "@mcp-use/client";
import { LangChainMCPAgent } from "@mcp-use/agent/langchain";

async function main() {
  const client = new MCPClient({
    mcpServers: {
      filesystem: {
        command: "npx",
        args: ["-y", "@modelcontextprotocol/server-filesystem", "./"],
      },
    },
  });

  const agent = new LangChainMCPAgent({
    llm: new ChatOpenAI({ model: "gpt-4o", temperature: 0 }),
    client,
  });

  agent.setMetadata({
    trace_name: "project-audit",
    session_id: "session-123",
    user_id: "user-456",
    environment: "production",
  });
  agent.setTags(["docs", "project-audit"]);

  try {
    await agent.initialize();
    const result = await agent.run({
      prompt: "Inspect package.json and summarize the project scripts.",
    });
    console.log(result);
  } finally {
    await agent.flush();
    await agent.close();
  }
}

main().catch(console.error);
```

Initialization auto-detects Langfuse only when both keys are present and `langfuse-langchain` can be imported. If no handler is available, the agent still runs without traces.

## Add metadata and tags

`setMetadata()` merges new values into existing metadata. `setTags()` appends tags and removes duplicates. Both apply to later `stream()` and `streamEvents()` executions.

Two metadata keys also control LangChain and Langfuse behavior:

* `trace_name` sets the LangChain run name. The default is `mcp-use-agent`.
* `session_id` is forwarded as the Langfuse session ID.

The built-in Langfuse handler also recognizes `user_id`, adds MCP server metadata during initialization, and adds environment and agent tags when configured.

Metadata keys replace characters outside letters, numbers, underscores, and hyphens with `_`. Arrays keep only primitive values. Serializable objects longer than 1,000 characters are stored as truncated strings. Unsupported or circular values are skipped.

Tags allow letters, numbers, underscores, colons, and hyphens. Invalid characters become `_`, and tags longer than 50 characters are removed.

## Use custom callbacks

Constructor callbacks replace auto-detected callbacks; they are not merged with the built-in Langfuse handler.

```typescript theme={null}
import { ChatOpenAI } from "@langchain/openai";
import { CallbackHandler } from "langfuse-langchain";
import { MCPClient } from "@mcp-use/client";
import { LangChainMCPAgent } from "@mcp-use/agent/langchain";

const callback = new CallbackHandler({
  publicKey: process.env.LANGFUSE_PUBLIC_KEY,
  secretKey: process.env.LANGFUSE_SECRET_KEY,
  baseUrl: process.env.LANGFUSE_HOST,
});

const agent = new LangChainMCPAgent({
  llm: new ChatOpenAI({ model: "gpt-4o" }),
  client: new MCPClient({ mcpServers }),
  callbacks: [callback],
});

try {
  await agent.initialize();
  console.log(await agent.run({ prompt: "Complete the traced task." }));
} finally {
  await agent.flush();
  await agent.close();
}
```

Custom callback objects receive normal LangChain lifecycle events. If a callback implements `flushAsync()`, `agent.flush()` calls it. During `agent.close()`, the observability manager flushes again, then calls `shutdownAsync()` or `shutdown()` when implemented.

## Flush and clean up

Call `await agent.flush()` before a serverless function or short-lived process exits. It waits for each configured callback's `flushAsync()` method when present.

Always call `await agent.close()` for full cleanup. Closing:

1. flushes and shuts down observability callbacks;
2. clears the LangChain executor and tool list;
3. closes the MCP client or direct connectors; and
4. marks the agent uninitialized.

## Disable callback discovery

Set `observe: false` to disable all observability callbacks, including custom callbacks:

```typescript theme={null}
const agent = new LangChainMCPAgent({
  llm,
  client,
  observe: false,
});

await agent.initialize();
console.log((await agent.observabilityManager.getStatus()).enabled); // false
await agent.close();
```

Set `MCP_USE_LANGFUSE=false` when you want callbacks in general but do not want built-in Langfuse auto-detection.

## Next steps

* [Use structured output](/v2/typescript/agent/langchain/structured-output)
* [Route tools with Server Manager](/v2/typescript/agent/langchain/server-manager)
