Skip to main content
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:
Set credentials before the process imports @mcp-use/agent/langchain:
Then initialize and run the agent:
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.
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:
Set MCP_USE_LANGFUSE=false when you want callbacks in general but do not want built-in Langfuse auto-detection.

Next steps