|
| 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. |
0 commit comments