> ## 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 your MCP server

> Trace every tool call on your Model Context Protocol server in LangSmith with the Python and JavaScript SDKs, without changing the agents that call it.

The [Model Context Protocol (MCP)](https://modelcontextprotocol.io) is an open protocol that lets agents call tools that a server exposes. When you build an MCP server, LangSmith helps you understand how agents use your tools in production: trace each tool call, monitor usage and reliability, find failures, and evaluate tool quality.

This guide shows how to trace your MCP server with the LangSmith Python or JavaScript SDK, without changing the agents that call it. To trace a server you do not own, see [Trace servers you do not own](#trace-servers-you-do-not-own).

## Why trace your MCP server

Your MCP server is a product, and agents are its users. Tracing it shows how agents actually use it:

* **See every tool call**: The arguments the agent sent and the result your server returned.
* **Track usage and reliability**: The prebuilt [dashboard](https://docs.langchain.com/langsmith/dashboards.md) charts run counts, error rates, and latency for your most-called tools.
* **Catch failures early**: Calls that return an MCP error result are marked as errors. Set [alerts](https://docs.langchain.com/langsmith/alerts.md) on error rate or latency.
* **Improve your tools**: Score tool results with [online evaluators](https://docs.langchain.com/langsmith/evaluation-concepts.md#online-evaluations) as you change tool descriptions, schemas, or responses.

## How it works

You add tracing to your server with the LangSmith SDK. Each tool call the server runs becomes a `tool` run in LangSmith, whichever agent or client made the call. The agents that call your server need no changes.

```mermaid actions={false} theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
%%{init: {"theme":"base","themeVariables":{"fontFamily":"Inter, system-ui, sans-serif","lineColor":"#40668D","primaryColor":"#E5F4FF","primaryTextColor":"#030710","primaryBorderColor":"#006DDD","clusterBkg":"transparent"}}}%%
flowchart LR
    AG("<div style='padding:2px 6px'><b>Any agent or MCP client</b><br/>No changes needed</div>")
    SV("<div style='padding:2px 6px'><b>Your MCP server</b><br/>Traced with the LangSmith SDK</div>")
    LS("<div style='padding:2px 6px'><b>LangSmith</b><br/>Traces, dashboards, and alerts</div>")

    AG -->|"tools/call"| SV
    SV -->|"One tool run per call"| LS

    classDef neutral fill:#F2FAFF,stroke:#40668D,stroke-width:2px,color:#2F4B68,rx:10,ry:10
    classDef process fill:#E5F4FF,stroke:#006DDD,stroke-width:2px,color:#030710,rx:10,ry:10
    classDef output fill:#EBD0F0,stroke:#885270,stroke-width:2px,color:#441E33,rx:10,ry:10

    class AG neutral
    class SV process
    class LS output
```

> [!NOTE]
>
> [Create an agent](https://docs.langchain.com/langsmith/create-an-agent.md) once before sending traces. Use [agent addressing](https://docs.langchain.com/langsmith/log-traces-to-agent.md) to select its identifier and environment. If an integration requires `project_name`, use the selected environment's [`tracer_session_name`](https://docs.langchain.com/langsmith/create-an-agent#use-an-environment-project).

## Set up tracing

The SDK integrations support servers built with the [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) and the [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk). For other MCP libraries, see [Instrument tool calls manually](#instrument-tool-calls-manually).

> [tab] Python
>
> ### Install the packages
>
> > [!NOTE]
> >
> > Requires `langsmith>=0.16.3` and `mcp>=2`. `configure_mcp` requires `langsmith>=0.16.4`. For servers on `mcp` 1.x, upgrade to `mcp>=2` or [instrument tool calls manually](#instrument-tool-calls-manually).
>
> ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> pip install "langsmith>=0.16.4" "mcp>=2"
> ```
>
> ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> uv add "langsmith>=0.16.4" "mcp>=2"
> ```
>
> ### Configure your environment
>
> Set these variables in the server process:
>
> ```bash Shell theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> export LANGSMITH_TRACING=true
> export LANGSMITH_API_KEY=<your-api-key>
>
> # Select the registered agent and environment
> export LANGSMITH_AGENT_ID="<your-agent-id>"
> export LANGSMITH_AGENT_ENVIRONMENT="local"
>
> # For LangSmith API keys linked to multiple workspaces, set the LANGSMITH_WORKSPACE_ID environment variable to specify which workspace to use.
> export LANGSMITH_WORKSPACE_ID=<your-workspace-id>
> ```
>
> ### Trace your server
>
> Pass an `MCPServer` or a low-level `mcp.server.lowlevel.Server` to `wrap_mcp_server`. Each tool call the server runs becomes a `tool` run:
>
> ```python server.py theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> from mcp.server.mcpserver import MCPServer
>
> from langsmith.integrations.mcp import wrap_mcp_server
>
> mcp = wrap_mcp_server(MCPServer("weather"))
>
>
> @mcp.tool()
> def get_weather(city: str) -> str:
>     """Get the weather for a city."""
>     return f"It is sunny in {city}."
>
>
> if __name__ == "__main__":
>     mcp.run(transport="streamable-http")
> ```
>
> To trace every server in a process without wrapping each one, call `configure_mcp` once at startup instead, before you create the server:
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> from langsmith.integrations.mcp import configure_mcp
>
> configure_mcp()
> ```
>
> `configure_mcp` patches the `mcp` package, so every `MCPServer` or low-level `Server` created after the call is traced. It also traces each `call_tool` on an `mcp.Client` or `mcp.ClientSession` in the same process. It returns `False` when `mcp>=2` is not installed.
>
> ### Run your server and call a tool
>
> Start the server. It listens at `http://localhost:8000/mcp`:
>
> ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> python server.py
> ```
>
> Call a tool from any MCP client, such as your agent. This client has no tracing code:
>
> ```python call_tool.py theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> import asyncio
>
> from mcp import Client
>
>
> async def main():
>     async with Client("http://localhost:8000/mcp") as client:
>         result = await client.call_tool("get_weather", {"city": "Paris"})
>         print(result.content[0].text)
>
>
> asyncio.run(main())
> ```

> [tab] JavaScript
>
> ### Install the packages
>
> > [!NOTE]
> >
> > Requires `langsmith>=0.14.2` and `@modelcontextprotocol/sdk`.
>
> ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> npm install langsmith @modelcontextprotocol/sdk zod
> ```
>
> ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> yarn add langsmith @modelcontextprotocol/sdk zod
> ```
>
> ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> pnpm add langsmith @modelcontextprotocol/sdk zod
> ```
>
> ### Configure your environment
>
> Set these variables in the server process:
>
> ```bash Shell theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> export LANGSMITH_TRACING=true
> export LANGSMITH_API_KEY=<your-api-key>
>
> # Select the registered agent and environment
> export LANGSMITH_AGENT_ID="<your-agent-id>"
> export LANGSMITH_AGENT_ENVIRONMENT="local"
>
> # For LangSmith API keys linked to multiple workspaces, set the LANGSMITH_WORKSPACE_ID environment variable to specify which workspace to use.
> export LANGSMITH_WORKSPACE_ID=<your-workspace-id>
> ```
>
> ### Trace your server
>
> Pass an `McpServer` or a low-level `Server` to `wrapMcpServer`. Each tool call the server runs becomes a `tool` run, including tools registered after the wrap:
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
> import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
> import { wrapMcpServer } from "langsmith/wrappers/mcp";
> import { z } from "zod";
>
> const server = wrapMcpServer(
>   new McpServer({ name: "weather", version: "1.0.0" })
> );
>
> server.registerTool(
>   "get_weather",
>   { inputSchema: { city: z.string() } },
>   async ({ city }) => ({
>     content: [{ type: "text", text: `It is sunny in ${city}.` }],
>   })
> );
>
> await server.connect(new StdioServerTransport());
> ```
>
> To trace every server in a process without wrapping each one, call `configureMcp` once at startup instead, before you register tools:
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> import { configureMcp } from "langsmith/wrappers/mcp";
>
> await configureMcp();
> ```
>
> `configureMcp` patches both the ESM and CommonJS builds of `@modelcontextprotocol/sdk`, so each tool call on an `McpServer` or low-level `Server` is traced. It also traces each `Client.callTool` in the same process. It resolves to `false` when `@modelcontextprotocol/sdk` is not installed.
>
> ### Run your server and call a tool
>
> Call a tool from any MCP client, such as your agent. This client has no tracing code. It starts the compiled server from `server.js` over stdio:
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> import { Client } from "@modelcontextprotocol/sdk/client/index.js";
> import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
>
> const client = new Client({ name: "weather-agent", version: "1.0.0" });
> await client.connect(
>   new StdioClientTransport({
>     command: "node",
>     args: ["server.js"],
>     // Pass LANGSMITH_* variables through to the server process
>     env: process.env as Record<string, string>,
>   })
> );
>
> const result = await client.callTool({
>   name: "get_weather",
>   arguments: { city: "Paris" },
> });
> console.log(result.content);
> await client.close();
> ```
>
> > [!NOTE]
> >
> > A stdio client passes only a few default environment variables, such as `PATH` and `HOME`, to the server process it starts. Pass `env` as shown, or set the `LANGSMITH_*` variables in the client's server configuration. Otherwise the server does not trace.

## View traces in LangSmith

Open the [LangSmith UI](https://smith.langchain.com?utm_source=docs\&utm_medium=cta\&utm_campaign=langsmith-signup\&utm_content=langsmith-trace-with-mcp) and view the traces for your agent's environment. Each call to `get_weather` appears as its own trace with one `tool` run:

```txt theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
get_weather      tool run from your MCP server
```

Each tool run shows:

* **Inputs and outputs**: The tool arguments, and the full tool result.
* **Latency**: How long the tool call took.
* **Errors**: Tool results with `isError` set appear as errors, with the message `MCP tool returned an error`.

Runs from the SDK integrations carry the metadata `ls_integration: mcp`. Filter on it to see only MCP tool calls in a project. To see trends across calls, open the environment's prebuilt [dashboard](https://docs.langchain.com/langsmith/dashboards.md), which includes run counts, error rates, and latency for your five most-called tools.

When the server issues an MCP session ID, as a stateful streamable HTTP server can, each tool run that starts its own trace gets a `thread_id` derived from that session, so the session's calls group into one [thread](https://docs.langchain.com/langsmith/threads.md). Calls over stdio, stateless requests, and runs that continue a client's trace get no thread ID from the server. The example server on this page does not issue a session ID, so each call appears as a separate trace.

## Advanced tracing

The setup above is all you need to trace your server. If you also own the MCP client, trace it too, and connect the client's and the server's runs into one trace. The client sends its trace context with each request, and the server continues the same trace, even when the two run in separate processes:

```mermaid actions={false} theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
%%{init: {"theme":"base","themeVariables":{"fontFamily":"Inter, system-ui, sans-serif","lineColor":"#40668D","primaryColor":"#E5F4FF","primaryTextColor":"#030710","primaryBorderColor":"#006DDD","clusterBkg":"transparent"}}}%%
flowchart LR
    AG("<div style='padding:2px 6px'><b>Your agent</b></div>")
    CL("<div style='padding:2px 6px'><b>MCP client</b><br/>Traced with the LangSmith SDK</div>")
    SV("<div style='padding:2px 6px'><b>MCP server</b><br/>Traced with the LangSmith SDK</div>")
    LS("<div style='padding:2px 6px'><b>LangSmith</b><br/>One trace</div>")

    AG --> CL
    CL -->|"tools/call + trace context"| SV
    CL -.->|"Client tool run"| LS
    SV -.->|"Server tool run"| LS

    classDef neutral fill:#F2FAFF,stroke:#40668D,stroke-width:2px,color:#2F4B68,rx:10,ry:10
    classDef process fill:#E5F4FF,stroke:#006DDD,stroke-width:2px,color:#030710,rx:10,ry:10
    classDef output fill:#EBD0F0,stroke:#885270,stroke-width:2px,color:#441E33,rx:10,ry:10

    class AG neutral
    class CL,SV process
    class LS output
```

With both sides traced and connected, a call to `get_weather` produces this trace:

```txt theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
weather_agent            your agent
└── get_weather          tool run from the MCP client
    └── get_weather      tool run from the MCP server
```

> [tab] Python
>
> ### Trace your client
>
> Pass an `mcp.Client` or `mcp.ClientSession` to `wrap_mcp_client`. Each `call_tool` becomes a `tool` run. When the call happens inside a traced function, the run nests under that function's run:
>
> ```python client.py theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> import asyncio
>
> from mcp import Client
>
> from langsmith import traceable
> from langsmith.integrations.mcp import wrap_mcp_client
>
>
> @traceable(name="weather_agent")
> async def main():
>     async with Client("http://localhost:8000/mcp") as client:
>         client = wrap_mcp_client(client)
>         result = await client.call_tool("get_weather", {"city": "Paris"})
>         print(result.content[0].text)
>
>
> asyncio.run(main())
> ```
>
> Set the `LANGSMITH_*` variables from [Configure your environment](#configure-your-environment) in the client process too.
>
> ### Connect client and server traces
>
> By default, the client's and the server's runs land in separate traces. When you own both sides, set `distributed_tracing=True` on both. The client sends its trace context in the request's `_meta` field, and the server continues that trace:
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> # client.py
> client = wrap_mcp_client(client, distributed_tracing=True)
>
> # server.py
> mcp = wrap_mcp_server(MCPServer("weather"), distributed_tracing=True)
> ```
>
> With this change, the server's `get_weather` run appears under the client's `get_weather` run, inside the `weather_agent` trace.
>
> `configure_mcp` also accepts `distributed_tracing`, which applies to every server and client in the process. A `wrap_mcp_server` or `wrap_mcp_client` call on top of `configure_mcp` records each tool call once, and its `distributed_tracing` setting takes precedence.
>
> > [!WARNING]
> >
> > The trace context includes the client's project, tags, and metadata. Turn on `distributed_tracing` on a client only for servers you own. On a server, it is off by default, so a client cannot place the server's runs in another trace or project. Turn it on only when you own the clients too.
>
> If a request carries trace context that does not parse, the server ignores it and starts a new trace. The tool call still runs. For more on how LangSmith propagates trace context, see [Implement distributed tracing](https://docs.langchain.com/langsmith/distributed-tracing.md).

> [tab] JavaScript
>
> ### Trace your client
>
> Pass a `Client` from `@modelcontextprotocol/sdk` to `wrapMcpClient`. Each `callTool` becomes a `tool` run. When the call happens inside a `traceable` function, the run nests under that function's run:
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> import { Client } from "@modelcontextprotocol/sdk/client/index.js";
> import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
> import { traceable } from "langsmith/traceable";
> import { wrapMcpClient } from "langsmith/wrappers/mcp";
>
> const client = wrapMcpClient(
>   new Client({ name: "weather-agent", version: "1.0.0" })
> );
> await client.connect(
>   new StdioClientTransport({
>     command: "node",
>     args: ["server.js"],
>     env: process.env as Record<string, string>,
>   })
> );
>
> const weatherAgent = traceable(
>   async (city: string) => {
>     const result = await client.callTool({
>       name: "get_weather",
>       arguments: { city },
>     });
>     return result.content;
>   },
>   { name: "weather_agent" }
> );
>
> console.log(await weatherAgent("Paris"));
> await client.close();
> ```
>
> Set the same `LANGSMITH_*` variables in the client process too.
>
> ### Connect client and server traces
>
> By default, the client's and the server's runs land in separate traces. When you own both sides, set `distributedTracing: true` on both. The client sends its trace context in the request's `_meta` field, and the server continues that trace:
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> // Client
> const client = wrapMcpClient(
>   new Client({ name: "weather-agent", version: "1.0.0" }),
>   { distributedTracing: true }
> );
>
> // Server
> const server = wrapMcpServer(
>   new McpServer({ name: "weather", version: "1.0.0" }),
>   { distributedTracing: true }
> );
> ```
>
> With this change, the server's `get_weather` run appears under the client's `get_weather` run, inside the `weather_agent` trace.
>
> `configureMcp` accepts the same options as `wrapMcpServer` and `wrapMcpClient`, applied to every server and client in the process. A `wrapMcpServer` or `wrapMcpClient` call on top of `configureMcp` records each tool call once, and its settings take precedence.
>
> > [!WARNING]
> >
> > The trace context includes the client's project, tags, and metadata. Turn on `distributedTracing` on a client only for servers you own. On a server, it is off by default, so a client cannot place the server's runs in another trace or project. Turn it on only when you own the clients too.
>
> If a request carries trace context that does not parse, the server ignores it and starts a new trace. The tool call still runs. For more on how LangSmith propagates trace context, see [Implement distributed tracing](https://docs.langchain.com/langsmith/distributed-tracing.md).
>
> ### Configure the wrappers
>
> `wrapMcpServer`, `wrapMcpClient`, and `configureMcp` accept run options such as `client`, `project_name`, `tags`, and `metadata`, in addition to `distributedTracing`. For example, pass a LangSmith `Client` to flush traces before a short-lived process exits:
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
> import { Client as McpClient } from "@modelcontextprotocol/sdk/client/index.js";
> import { Client } from "langsmith";
> import { wrapMcpClient } from "langsmith/wrappers/mcp";
>
> const langsmith = new Client();
> const client = wrapMcpClient(
>   new McpClient({ name: "weather-agent", version: "1.0.0" }),
>   { client: langsmith, tags: ["mcp"] }
> );
>
> // ... call tools ...
>
> await langsmith.awaitPendingTraceBatches();
> ```
>
> For more on flushing, see [Trace JS functions in serverless environments](https://docs.langchain.com/langsmith/serverless-environments.md).

## Instrument tool calls manually

If your server uses an MCP library the SDK integrations do not support, such as `mcp` 1.x, trace tool calls with `traceable`. Put the tool's work in a function marked `run_type="tool"`, and call it from the tool handler. This example uses `MCPServer` for illustration. The pattern is the same in any library:

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from mcp.server.mcpserver import MCPServer

from langsmith import traceable

mcp = MCPServer("weather")


@traceable(run_type="tool", name="get_weather")
def lookup_weather(city: str) -> str:
    return f"It is sunny in {city}."


@mcp.tool()
def get_weather(city: str) -> str:
    """Get the weather for a city."""
    return lookup_weather(city)
```

Keep `traceable` off the tool handler itself. It adds a `config` parameter to the function signature, which then appears in the tool's input schema. For more on `traceable`, see [Custom instrumentation](https://docs.langchain.com/langsmith/annotate-code.md).

## Trace servers you do not own

The SDK integrations trace servers and clients that you run. To trace an agent's calls to a third-party MCP server, use one of these instead:

* **[LangSmith CLI proxy](https://docs.langchain.com/langsmith/langsmith-cli.md#trace-an-mcp-server)**: Run `langsmith mcp proxy` in front of any local or remote MCP server, with no code changes.
* **[Tool Gateway](https://docs.langchain.com/langsmith/tool-gateway-traces.md)**: Agents that call MCP servers through Tool Gateway get a trace for each call. These traces record metadata only, not tool arguments or results.

## See also

* [Implement distributed tracing](https://docs.langchain.com/langsmith/distributed-tracing.md)
* [Custom instrumentation](https://docs.langchain.com/langsmith/annotate-code.md)
* [Set up alerts](https://docs.langchain.com/langsmith/alerts.md) on tool error rate or latency
* [Score tool results with online evaluators](https://docs.langchain.com/langsmith/evaluation-concepts.md#online-evaluations)
* [Trace Claude Code sessions](https://docs.langchain.com/langsmith/trace-claude-code.md), including the MCP tool calls the agent makes
* [Trace LangChain agents](https://docs.langchain.com/langsmith/trace-with-langchain.md), including tools loaded with `langchain-mcp-adapters`

***

[Connect these docs](https://docs.langchain.com/use-these-docs.md) to your agent of choice via MCP for real-time answers.

[Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/langsmith/trace-with-mcp.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
