Skip to content

Commit 1e608ca

Browse files
authored
feat: built-in OpenTelemetry tracing and metrics (modelcontextprotocol#3115)
1 parent 39ae8e6 commit 1e608ca

36 files changed

Lines changed: 3060 additions & 110 deletions
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@modelcontextprotocol/core-internal': minor
3+
'@modelcontextprotocol/client': minor
4+
'@modelcontextprotocol/server': minor
5+
---
6+
7+
`Client`, `Server` and `McpServer` now emit OpenTelemetry spans and `mcp.client.operation.duration` / `mcp.server.operation.duration` histograms for every MCP request and notification except `notifications/message`, following the OpenTelemetry semantic conventions for MCP, and propagate W3C trace context through `params._meta` (SEP-414). There is nothing to configure: register an OpenTelemetry SDK and MCP traffic shows up. Pass `openTelemetry: false` to a `Client`, `Server` or `McpServer` to turn its instrumentation off. Without one, the OpenTelemetry API is a no-op, nothing is recorded and messages are unchanged.
8+
9+
`@opentelemetry/api` (`^1.9.0`) is a new required peer dependency of `@modelcontextprotocol/client` and `@modelcontextprotocol/server`, so the SDK uses the same copy as the application's OpenTelemetry SDK. npm 7+, pnpm 8+ and Bun install it automatically. Setups that don't install peers must add `@opentelemetry/api` to their dependencies, or importing either package fails: Yarn (classic, and Berry with any linker), `npm --legacy-peer-deps`, and pnpm with `auto-install-peers=false`.
10+
11+
What changes for applications that already run an OpenTelemetry SDK:
12+
13+
- MCP spans and metrics appear under the `@modelcontextprotocol/client` and `@modelcontextprotocol/server` instrumentation scopes. If you already trace MCP, pass `openTelemetry: false`, or with Sentry remove its `McpServer` integration, to avoid duplicate spans. Filtering the MCP scopes instead leaves handler spans parented on spans that are never exported.
14+
- Outgoing requests and notifications carry whatever your global propagator writes, in `params._meta`, as HTTP requests carry it in headers: `traceparent` and `tracestate`, plus `baggage` if the propagator includes W3C Baggage (the `NodeSDK` default), so baggage entries reach MCP peers, including third-party servers. Register `W3CTraceContextPropagator` alone to send trace context only.
15+
- Servers that validate a custom method's params with a strict schema need an optional `_meta` member, as they already do for callers that pass `onprogress`.
16+
17+
Spans do not record tool arguments, tool results or prompt arguments. They do record JSON-RPC error messages, handler exception messages and resource URIs. The span and attribute names are experimental while the MCP semantic conventions are in development.

‎docs/.vitepress/nav.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,8 @@ export const guideSidebar: DefaultTheme.SidebarItem[] = [
7171
{ text: 'Schema libraries', link: '/advanced/schema-libraries' },
7272
{ text: 'Custom transports', link: '/advanced/custom-transports' },
7373
{ text: 'Wire schemas', link: '/advanced/wire-schemas' },
74-
{ text: 'Gateway', link: '/advanced/gateway' }
74+
{ text: 'Gateway', link: '/advanced/gateway' },
75+
{ text: 'OpenTelemetry', link: '/advanced/opentelemetry' }
7576
]
7677
},
7778
{ text: 'Testing', link: '/testing' },

‎docs/advanced/opentelemetry.md‎

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
---
2+
shape: how-to
3+
---
4+
5+
# OpenTelemetry
6+
7+
`Client`, `McpServer` and `Server` emit OpenTelemetry spans and metrics for every MCP request and notification (except `notifications/message`), following the [OpenTelemetry semantic conventions for MCP](https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/mcp.md). Register an OpenTelemetry SDK and they show up.
8+
9+
```ts source="../../examples/guides/advanced/opentelemetry.examples.ts#sdk_setup"
10+
import { context, metrics, propagation, trace } from '@opentelemetry/api';
11+
import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
12+
import { W3CTraceContextPropagator } from '@opentelemetry/core';
13+
import { InMemorySpanExporter, SimpleSpanProcessor, TracerProvider } from '@opentelemetry/sdk-trace';
14+
15+
// Swap the in-memory exporter for an OTLP exporter to send spans to a backend.
16+
const exporter = new InMemorySpanExporter();
17+
const tracerProvider = new TracerProvider({ spanProcessors: [new SimpleSpanProcessor({ exporter })] });
18+
19+
context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable());
20+
propagation.setGlobalPropagator(new W3CTraceContextPropagator());
21+
trace.setGlobalTracerProvider(tracerProvider);
22+
metrics.setGlobalMeterProvider(new MeterProvider({ readers: [metricReader] }));
23+
```
24+
25+
::: warning Experimental
26+
The MCP semantic conventions are still in development. Span and attribute names can change in a minor release.
27+
:::
28+
29+
## Register an OpenTelemetry SDK
30+
31+
The SDK packages talk to the OpenTelemetry API, which does nothing until an application registers an SDK. Without one, nothing is recorded and nothing is added to `params._meta`.
32+
33+
```sh
34+
npm install @opentelemetry/api @opentelemetry/sdk-trace @opentelemetry/context-async-hooks @opentelemetry/core
35+
```
36+
37+
The server needs no telemetry configuration of its own.
38+
39+
```ts source="../../examples/guides/advanced/opentelemetry.examples.ts#server_traced"
40+
import { McpServer } from '@modelcontextprotocol/server';
41+
import * as z from 'zod/v4';
42+
43+
const server = new McpServer({ name: 'weather', version: '1.0.0' });
44+
45+
server.registerTool('get-weather', { inputSchema: z.object({ city: z.string() }) }, async ({ city }) => {
46+
// Spans started here are children of the "tools/call get-weather" server span.
47+
const forecast = await trace.getTracer('weather').startActiveSpan('fetch forecast', async span => {
48+
span.end();
49+
return 'sunny';
50+
});
51+
return { content: [{ type: 'text', text: `${city}: ${forecast}` }] };
52+
});
53+
```
54+
55+
The context manager is what makes the MCP span active inside your handlers, so spans you start there nest under it.
56+
57+
## See the spans
58+
59+
Make a call inside a span of your own, here an agent run.
60+
61+
```ts source="../../examples/guides/advanced/opentelemetry.examples.ts#callTool_traced"
62+
await trace.getTracer('agent').startActiveSpan('invoke_agent', async agentSpan => {
63+
await client.callTool({ name: 'get-weather', arguments: { city: 'Lisbon' } });
64+
agentSpan.end();
65+
});
66+
```
67+
68+
The client's span carries its trace context to the server in `params._meta`, so both sides land in one trace:
69+
70+
```
71+
invoke_agent (internal)
72+
tools/call get-weather (client)
73+
tools/call get-weather (server)
74+
fetch forecast (internal)
75+
```
76+
77+
The server span comes from the `@modelcontextprotocol/server` instrumentation scope (client spans from `@modelcontextprotocol/client`) and carries the conventions' attributes, plus `jsonrpc.request.id`, left out here:
78+
79+
```
80+
@modelcontextprotocol/server {
81+
'mcp.method.name': 'tools/call',
82+
'mcp.protocol.version': '2025-11-25',
83+
'gen_ai.operation.name': 'execute_tool',
84+
'gen_ai.tool.name': 'get-weather'
85+
}
86+
```
87+
88+
::: warning
89+
`params._meta` gets whatever your global propagator writes, as HTTP headers do. If it includes W3C Baggage (the `NodeSDK` default), baggage entries reach every MCP server you call, including third-party ones. Register `W3CTraceContextPropagator` on its own to send trace context only.
90+
91+
On Cloudflare Workers, a span's trace flags don't reflect sampling, so a W3C propagator sends `traceparent` with flags `00` and peers may treat the request as unsampled.
92+
:::
93+
94+
::: info
95+
Any SDK that follows [SEP-414](https://modelcontextprotocol.io/community/seps/414-request-meta) reads the same `traceparent`, `tracestate` and `baggage` keys, so a Python or C# peer joins the trace too.
96+
:::
97+
98+
## Read the duration metrics
99+
100+
Register a meter provider and each instance records `mcp.client.operation.duration` for what it sends and `mcp.server.operation.duration` for what it receives, in seconds, with the conventions' bucket boundaries. The tool call above recorded:
101+
102+
```
103+
mcp.client.operation.duration (s) {
104+
'mcp.method.name': 'tools/call',
105+
'mcp.protocol.version': '2025-11-25',
106+
'gen_ai.operation.name': 'execute_tool',
107+
'gen_ai.tool.name': 'get-weather'
108+
}
109+
```
110+
111+
Metrics never carry session ids, request ids or resource URIs. A server records any method that is neither a spec method nor registered with its own handler as `_OTHER`, keeps a tool or prompt name only once its handler has recognised it, and only records protocol versions it supports, so a client can't grow your metric cardinality.
112+
113+
## Know what counts as an error
114+
115+
Failed operations set `error.type` and an `ERROR` status:
116+
117+
- A JSON-RPC error records its code, such as `-32603`, in `error.type` and `rpc.response.status_code`. On the server, `-32700`, `-32600`, `-32601`, `-32602` and `-32002` mean the caller sent something unservable and are not errors.
118+
- A tool result with `isError: true` records `tool_error`. Its content stays out of the span.
119+
- Local failures record `timeout`, `cancelled`, `connection_closed`, or the SDK error code (`SEND_FAILED`, `INVALID_RESULT`).
120+
- A handler that throws something other than a `ProtocolError` also gets an exception event on the server span.
121+
122+
Spans don't record tool arguments, tool results or prompt arguments. They do record JSON-RPC error messages, handler exception messages and resource URIs.
123+
124+
## Serve over HTTP
125+
126+
With HTTP instrumentation active too, the MCP server span stays a child of the client's MCP span and links to the HTTP server span. `createMcpHandler` needs nothing extra.
127+
128+
::: tip
129+
Already tracing MCP yourself? Pass `openTelemetry: false` to that `Client`, `McpServer` or `Server` to turn its instrumentation off. Sentry's `McpServer` integration also traces MCP; remove it with `integrations: defaults => defaults.filter(integration => integration.name !== 'McpServer')` to keep the SDK's spans instead. Don't filter the `@modelcontextprotocol/*` scopes in a span processor: handler spans and the peer's spans would point at parents that are never exported.
130+
:::
131+
132+
The `examples/opentelemetry` story runs a traced client and server in separate processes over stdio and Streamable HTTP, and checks the trace crosses the wire.
133+
134+
## Recap
135+
136+
- Register an OpenTelemetry SDK; `Client`, `McpServer` and `Server` need no configuration. `openTelemetry: false` turns one instance off.
137+
- Without a registered SDK, nothing is recorded and `params._meta` is untouched.
138+
- Trace context travels in `params._meta`, so client and server spans join one trace and handler spans nest under the server span.
139+
- Each instance records `mcp.client.operation.duration` and `mcp.server.operation.duration` with low-cardinality attributes.
140+
- Spans don't record tool arguments, tool results or prompt arguments.

‎docs/servers/logging-progress-cancellation.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ Only the result comes back:
7474
## Log to the client
7575

7676
::: warning Deprecated — SEP-2577
77-
Log to `stderr` (stdio servers) or use OpenTelemetry instead. **MCP logging** is deprecated as of protocol version 2026-07-28 (SEP-2577) and stays functional through the deprecation window (at least twelve months) — see the [deprecated features registry](https://modelcontextprotocol.io/specification/2026-07-28/deprecated).
77+
Log to `stderr` (stdio servers) or use [OpenTelemetry](../advanced/opentelemetry.md) instead. **MCP logging** is deprecated as of protocol version 2026-07-28 (SEP-2577) and stays functional through the deprecation window (at least twelve months) — see the [deprecated features registry](https://modelcontextprotocol.io/specification/2026-07-28/deprecated).
7878
:::
7979

8080
Declare the `logging` capability when you construct the server.

‎examples/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ The one exception to the generic commands is the reference pair: [`cli-client/`]
4343
| [`todos-server/`](./todos-server/README.md) | **Reference server** (pairs with cli-client): every server feature with a real job — CRUD tools, sampling, multi-round elicitation, subscriptions, progress | stdio + http | dual |
4444
| [`caching/`](./caching/README.md) | `cacheHints` stamping on cacheable results (2026-07-28) | stdio + http | modern |
4545
| [`gateway/`](./gateway/README.md) | `connect({ prior })` — probe once, zero-round-trip connect for every worker (gateway pattern) | http | modern |
46+
| [`opentelemetry/`](./opentelemetry/README.md) | OpenTelemetry traces and duration metrics with no MCP-side configuration; trace context crosses the wire in `params._meta` | stdio + http | dual |
4647
| [`custom-methods/`](./custom-methods/README.md) | Vendor-prefixed methods + custom notifications | stdio + http | dual |
4748
| [`extension-capabilities/`](./extension-capabilities/README.md) | Declaring `capabilities.extensions` and reading the negotiated map | stdio + http | dual |
4849
| [`skills/`](./skills/README.md) | Skills over MCP (SEP-2640): `loadSkills` a folder, `SkillsClient` lists, loads and verifies | stdio + http | dual |
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
/**
2+
* Companion example for `docs/advanced/opentelemetry.md`.
3+
*
4+
* Every `ts` fence on that page is synced from a `//#region` in this file
5+
* (`pnpm sync:snippets --check`). The file also runs: the harness below the
6+
* regions connects an in-memory client and server and prints the spans and
7+
* metrics the page quotes verbatim.
8+
*
9+
* pnpm --filter @modelcontextprotocol/examples typecheck
10+
* npx tsx guides/advanced/opentelemetry.examples.ts # from examples/
11+
*
12+
* @module
13+
*/
14+
/* eslint-disable no-console */
15+
import type { DataPoint, Histogram } from '@opentelemetry/sdk-metrics';
16+
import { MeterProvider, MetricReader } from '@opentelemetry/sdk-metrics';
17+
import type { ReadableSpan } from '@opentelemetry/sdk-trace';
18+
19+
class CollectingMetricReader extends MetricReader {
20+
protected async onShutdown(): Promise<void> {}
21+
protected async onForceFlush(): Promise<void> {}
22+
}
23+
const metricReader = new CollectingMetricReader();
24+
25+
// "Register an OpenTelemetry SDK" — the application's job, once, before any MCP traffic.
26+
//#region sdk_setup
27+
import { context, metrics, propagation, trace } from '@opentelemetry/api';
28+
import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
29+
import { W3CTraceContextPropagator } from '@opentelemetry/core';
30+
import { InMemorySpanExporter, SimpleSpanProcessor, TracerProvider } from '@opentelemetry/sdk-trace';
31+
32+
// Swap the in-memory exporter for an OTLP exporter to send spans to a backend.
33+
const exporter = new InMemorySpanExporter();
34+
const tracerProvider = new TracerProvider({ spanProcessors: [new SimpleSpanProcessor({ exporter })] });
35+
36+
context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable());
37+
propagation.setGlobalPropagator(new W3CTraceContextPropagator());
38+
trace.setGlobalTracerProvider(tracerProvider);
39+
metrics.setGlobalMeterProvider(new MeterProvider({ readers: [metricReader] }));
40+
//#endregion sdk_setup
41+
42+
// "Register an OpenTelemetry SDK" — the server needs no telemetry configuration.
43+
//#region server_traced
44+
import { McpServer } from '@modelcontextprotocol/server';
45+
import * as z from 'zod/v4';
46+
47+
const server = new McpServer({ name: 'weather', version: '1.0.0' });
48+
49+
server.registerTool('get-weather', { inputSchema: z.object({ city: z.string() }) }, async ({ city }) => {
50+
// Spans started here are children of the "tools/call get-weather" server span.
51+
const forecast = await trace.getTracer('weather').startActiveSpan('fetch forecast', async span => {
52+
span.end();
53+
return 'sunny';
54+
});
55+
return { content: [{ type: 'text', text: `${city}: ${forecast}` }] };
56+
});
57+
//#endregion server_traced
58+
59+
// ---------------------------------------------------------------------------
60+
// Harness (not shown on the page). Connects a client in memory, makes one tool
61+
// call inside an agent span, and prints what was recorded.
62+
// ---------------------------------------------------------------------------
63+
64+
const { SpanKind } = await import('@opentelemetry/api');
65+
const { Client, InMemoryTransport } = await import('@modelcontextprotocol/client');
66+
const client = new Client({ name: 'agent', version: '1.0.0' });
67+
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
68+
await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
69+
exporter.reset();
70+
71+
// "See the spans" — the call the page's span tree comes from.
72+
//#region callTool_traced
73+
await trace.getTracer('agent').startActiveSpan('invoke_agent', async agentSpan => {
74+
await client.callTool({ name: 'get-weather', arguments: { city: 'Lisbon' } });
75+
agentSpan.end();
76+
});
77+
//#endregion callTool_traced
78+
79+
const spans = exporter.getFinishedSpans();
80+
const kinds: Record<number, string> = { [SpanKind.INTERNAL]: 'internal', [SpanKind.SERVER]: 'server', [SpanKind.CLIENT]: 'client' };
81+
const printTree = (parent: ReadableSpan | undefined, depth: number) => {
82+
const children = spans
83+
.filter(span => span.parentSpanContext?.spanId === parent?.spanContext().spanId)
84+
.toSorted((a, b) => a.startTime[0] - b.startTime[0] || a.startTime[1] - b.startTime[1]);
85+
for (const child of children) {
86+
console.log(`${' '.repeat(depth)}${child.name} (${kinds[child.kind]})`);
87+
printTree(child, depth + 1);
88+
}
89+
};
90+
printTree(undefined, 0);
91+
92+
const toolServerSpan = spans.find(span => span.name === 'tools/call get-weather' && span.kind === SpanKind.SERVER);
93+
if (toolServerSpan === undefined) throw new Error('opentelemetry.md claim failed: no tools/call server span');
94+
const { 'jsonrpc.request.id': _requestId, ...stableAttributes } = toolServerSpan.attributes;
95+
console.log(toolServerSpan.instrumentationScope.name, stableAttributes);
96+
97+
const { resourceMetrics } = await metricReader.collect();
98+
const clientDuration = resourceMetrics.scopeMetrics
99+
.filter(scope => scope.scope.name === '@modelcontextprotocol/client')
100+
.flatMap(scope => scope.metrics)
101+
.find(metric => metric.descriptor.name === 'mcp.client.operation.duration');
102+
const toolCallPoint = (clientDuration?.dataPoints as DataPoint<Histogram>[] | undefined)?.find(
103+
point => point.attributes['mcp.method.name'] === 'tools/call'
104+
);
105+
if (toolCallPoint === undefined) throw new Error('opentelemetry.md claim failed: no tools/call duration was recorded');
106+
console.log(`${clientDuration!.descriptor.name} (${clientDuration!.descriptor.unit})`, toolCallPoint.attributes);
107+
108+
await client.close();
109+
await tracerProvider.shutdown();

‎examples/opentelemetry/README.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# opentelemetry
2+
3+
Trace and measure MCP traffic with OpenTelemetry. Both processes register an OpenTelemetry SDK and configure nothing on the MCP side; the client's `tools/call` span carries its trace context to the server in `params._meta`, so the server span and anything the tool does land in the same trace. The client asserts the trace crossed the wire, the span parenting on both sides, and that `mcp.client.operation.duration` was recorded.
4+
5+
```bash
6+
pnpm --filter @mcp-examples/opentelemetry client
7+
```
8+
9+
Sample output (ids differ per run):
10+
11+
```
12+
trace 4bf92f3577b34da6a3ce929d0e0e4736
13+
invoke_agent (client process)
14+
tools/call trace-info (client process)
15+
tools/call trace-info (server process)
16+
```
17+
18+
The server and client keep spans in memory to stay self-contained. In an application, add a span processor with an exporter (for example `OTLPTraceExporter`) to the tracer provider. See [the OpenTelemetry guide](../../docs/advanced/opentelemetry.md).

0 commit comments

Comments
 (0)