
Making MCP Servers Observable with OpenTelemetry
Learn how I built opentel-mcp to bring OpenTelemetry observability to MCP servers using transparent instrumentation,semantic conventions and minimal integration
Your MCP Server Is a Black Box. Here's How I Made Mine Observable
The Story Behind opentel-mcp
A few months ago, I was building a multi-agent AI platform where agents communicated with external tools through the Model Context Protocol (MCP).
Everything worked well—until it didn't.
As the number of tools grew, I started asking questions that were surprisingly difficult to answer.
- Which tool is slowing down my agent?
- Did the tool actually fail, or did the model simply return a poor response?
- How long does each tool execution take?
- Which tool becomes the bottleneck as the workflow grows?
The MCP SDK executed my tools exactly as expected, but it provided very little visibility into what happened during execution.
My first instinct wasn't to build another library.
Instead, I started exploring the existing ecosystem. I found several excellent OpenTelemetry instrumentation libraries for MCP, each solving the problem from a slightly different perspective.
As I read their implementations, one thing became clear: every project had made different architectural trade-offs.
Some prioritized feature breadth.
Some focused on transport-level instrumentation.
Others integrated deeply with specific observability backends.
While studying them, I became curious.
Could I build a smaller library that focused on a few principles I personally cared about?
- Follow the OpenTelemetry MCP semantic conventions.
- Correctly model MCP's
isErrorbehavior.
- Work safely over stdio transports.
- Respect an application's existing OpenTelemetry configuration.
- Keep the API simple enough that developers could understand its entire implementation.
That curiosity eventually became
opentel-mcp .This article isn't about creating "yet another OpenTelemetry library."
It's about the engineering decisions behind building one, what I learned about MCP and observability along the way, and how those decisions compare with the existing ecosystem.
Why Another Library?
Before writing a single line of code, I explored the existing MCP observability ecosystem.
Several excellent libraries already solved this problem from different perspectives, and studying their implementations significantly influenced my own understanding of MCP instrumentation.
Rather than replacing those projects, I wanted to explore a different set of design priorities:
- Follow the MCP semantic conventions closely.
- Correctly distinguish protocol failures from tool failures.
- Keep the implementation intentionally small.
- Respect an application's existing OpenTelemetry configuration.
- Make every architectural decision explicit through ADRs.
The result isn't intended to be the most feature-rich instrumentation library.
Instead, it's an exploration of how a focused, standards-compliant implementation can provide transparent observability while remaining easy to understand and extend.
The problem: agents call tools, and you can't see any of it
The Model Context Protocol (MCP) has quietly become the standard way for AI agents to call external tools. An agent asks your MCP server to run
search_documents , fetch_weather , or generate_advice , your server does the work, and a result comes back. It works — until you need to know why it's slow or why it failed.Because here's the uncomfortable truth: the MCP SDK doesn't instrument any of this. When an agent turn takes three seconds, you have no idea whether the bottleneck was your vector search, an external API, or the language model call. When a tool fails, you get an error message with no context about what the server was doing. When you add a new tool, you have no baseline to measure it against.
These are the same problems every backend service has faced for years, and the industry already solved them: distributed tracing with OpenTelemetry. An MCP server is just a Node process, so the same tooling applies. The only thing missing was a library that wires OpenTelemetry into the MCP request lifecycle without making you hand-write a wrapper around every tool.
That's what I built. This post walks through the actual problem it solves, the design decisions that turned out to matter, and — honestly — how it compares to the other libraries already in this space.
What it looks like
One line, after you construct your server and before you register any tool handlers:
import { Server } from '@modelcontextprotocol/sdk/server/index.js';import { instrumentMcpServer } from 'opentel-mcp';
const server = new Server( { name: 'agri-rag-mcp', version: '1.0.0' }, { capabilities: { tools: {} } });
instrumentMcpServer(server, { serviceName: 'agri-rag-mcp' });From that point on, every tool call emits a standard OpenTelemetry span. Here's a real trace of one agent turn, captured in Jaeger:
agent_turn ............................. 2470ms OK├─ tools/call search_documents ........... 46ms OK├─ tools/call fetch_weather ............. 601ms OK└─ tools/call generate_advice .......... 1802ms OK ← the bottleneckWithout tracing, you'd know only that the turn took ~2.5 seconds. With it, the waterfall shows exactly where the time went:
generate_advice is the cost, and the other two tools are cheap by comparison. That's the difference between guessing and knowing.
Understanding the Architecture
Before diving into implementation details, it's helpful to understand where
opentel-mcp fits within the MCP request lifecycle.An MCP server receives requests from an AI agent, executes the appropriate tool, and returns the result. By default, this entire process is opaque—there's no visibility into which tool executed, how long it took, or whether it failed.
Rather than modifying the MCP SDK or requiring developers to manually instrument every tool,
opentel-mcp intercepts tool registration and transparently wraps each handler with OpenTelemetry instrumentation. AI Agent │ ▼ MCP Client │ ▼ MCP Server │ ▼ instrumentMcpServer(server) │ ▼ Wrapped Tool Handler │ ┌─────────────┴─────────────┐ │ │Start OpenTelemetry Span Execute Original Tool │ │ └─────────────┬─────────────┘ ▼ Detect isError / Exception │ ▼ End OpenTelemetry Span │ ▼ Jaeger / Grafana / ElasticThe important point is that the original tool implementation never changes. The library simply observes execution before and after the tool runs, making instrumentation completely transparent to application code.
The design decision that matters most: the two ways a tool fails
Most of the engineering in this library is unglamorous — wrapping the right method, respecting the host's OpenTelemetry setup, keeping the output stream clean. But one design decision is genuinely worth understanding, because it's the one most instrumentation gets wrong.
An MCP tool can fail in two completely different ways.
It can throw. The handler raises an exception, the SDK catches it, and turns it into a JSON-RPC error. The call failed at the protocol level. Everyone catches this.
Or it can return
isError: true . The handler returns normally — but the object it returns is marked as a failure:return { isError: true, content: [{ type: 'text', text: 'No weather data for that city' }]};Read that carefully. The function did not throw. It returned. As far as the runtime is concerned, this call succeeded. But the tool is telling the agent, in the idiomatic MCP way, "I couldn't do that — decide what to do next." This is the preferred way for a tool to fail, because it keeps the conversation with the agent alive instead of crashing the server.
Here's the trap. Naive instrumentation wraps the handler in a try/catch: if it returns, mark the span OK; if it throws, mark it ERROR. The
isError: true case returns, so it lands in the success path and gets recorded as OK. Your dashboard proudly reports a 100% success rate on a tool that's been failing for every input except one. A silent blind spot.opentel-mcp checks the returned value:js
const result = await handler(request, extra);if (result?.isError === true) { span.setAttribute('error.type', 'tool_error'); span.setStatus({ code: SpanStatusCode.ERROR });} else { span.setStatus({ code: SpanStatusCode.OK });}return result; // returned unchanged; nothing thrownTwo things worth noticing. First, the span is marked ERROR with
error.type = tool_error — a value the OpenTelemetry MCP semantic conventions specify for exactly this case (I didn't invent the name; I read the spec). Second, the result is returned unchanged and nothing is thrown, because the JSON-RPC call genuinely succeeded. Instrumentation observes; it must never interfere with what the agent receives.In a trace, that failure looks like this:
tools/call fetch_weather ................. 605ms ERROR error.type = tool_errorNow your error rate reflects reality instead of reading as a flat, comforting, wrong 100%.
The second decision: never corrupt the protocol stream
MCP's primary transport is stdio — the client spawns your server as a subprocess and they exchange JSON-RPC messages over
stdout , one JSON object per line.OpenTelemetry's built-in
ConsoleSpanExporter writes to stdout . Put those two facts together and you get a disaster: the moment you enable span logging, your diagnostic output lands in the middle of the JSON-RPC stream, the client's parser hits what it thinks is malformed protocol, and the connection dies. The developer just sees their agent disconnect with no explanation.The fix is small and, once you see it, obvious: write span output to
stderr instead. stderr isn't part of the protocol, so it's free for diagnostics. opentel-mcp ships a StderrSpanExporter that does exactly this. I verified it the hard way — drove a real server over a real stdio transport and parsed every single line of stdout as JSON. All clean; every span on stderr .
Why This Design?
The MCP SDK currently doesn't expose an official instrumentation hook.
Rather than modifying SDK internals or requiring developers to wrap every tool manually, I chose to intercept
setRequestHandler() , the single public API through which every tool registration passes.This approach keeps the integration simple, avoids coupling to private SDK internals, and allows existing applications to enable tracing with a single line while preserving their original business logic.
A bug I found in my own library (and why it mattered)
After I published version 0.1.0, I did something I'd recommend to anyone shipping a package: I installed my own published library from the registry into a clean project and used it exactly as a stranger would.
I found a real bug. The
serviceName option was required — the library threw if you omitted it — but in the default production configuration, it was silently ignored. When the library isn't creating its own tracer provider (the default, so it doesn't override your existing OpenTelemetry setup), the resource attributes come from your provider, and the serviceName I demanded had no effect whatsoever.The behavior was actually correct — respecting the host's configuration is right. But the API lied about it. A user would set
serviceName: 'my-service' , see a different name in their dashboard, and have nothing to explain the discrepancy. A required option that's inert is worse than no option at all.I fixed it in 0.1.1:
serviceName is now required only when the library creates its own provider, and if you pass it when it has no effect, you get a one-time diagnostic warning explaining why. The lesson wasn't about a line of code — it was that "it works" and "the API is honest" are different bars, and consumer-testing your own package is how you find the gap between them.
Performance Considerations
One of the design goals of
opentel-mcp was to keep observability lightweight enough for production workloads.The library performs only a small, constant amount of work for each tool invocation before delegating execution to the original handler. In most real-world MCP applications, the dominant latency comes from LLM inference, vector search, database queries, or external API calls—not from the instrumentation itself.
Rather than optimizing for microbenchmarks, I focused on keeping the instrumentation predictable, avoiding unnecessary allocations, reflection, and deep object inspection during request execution.
As the project evolves, I plan to publish reproducible performance benchmarks so developers can better understand the runtime overhead under different workloads.
How it compares to the alternatives
I'll be direct:
opentel-mcp is not the first or only OpenTelemetry instrumentation for MCP. If you're choosing a library, you should know the landscape. Here's an honest map.autotel-mcp-instrumentation is the most feature-rich of the Node options. It instruments tools, resources, and prompts; it does W3C trace-context propagation through the _meta field for distributed tracing across the MCP boundary; and it offers configurable argument capture. If you need breadth today, it has the most surface. Its trade-offs: it uses custom attribute names rather than the semantic conventions, so its spans don't drop cleanly into standard dashboards, and at the time of writing it's on a very high version number with no other packages depending on it.@theharithsa/opentelemetry-instrumentation-mcp takes the idiomatic OpenTelemetry approach — a proper instrumentation class that plugs into the SDK's instrumentations array. It leans toward a specific backend and, by its own documentation, may not always preserve parent-child span relationships, which is the thing that makes a trace a waterfall rather than a flat list.mottibec/opentelemetry-instrumentation-mcp instruments at the transport level, emitting message-granularity spans with generic RPC attributes. That's a different and noisier level of detail than per-tool-call semantics, and it offers little configuration.FastMCP (Python) deserves mention as the benchmark, even though it's not a Node competitor. It ships native OpenTelemetry instrumentation that implements the MCP semantic conventions and uses
error.type = tool_error for tool-level failures. My design converges on FastMCP's almost exactly — spec-compliant span names, the tool_error handling, never overriding the host provider. That convergence was reassuring: it meant the architectural calls held up against the reference implementation.So where does
opentel-mcp fit? It's the small, spec-correct, honest option. It follows the OpenTelemetry MCP semantic conventions, so spans work in existing dashboards without custom mapping. It catches the isError tool-failure case that the other Node libraries don't document. It writes to stderr so it never corrupts a stdio transport. Every non-obvious design decision is written down as an Architecture Decision Record. It has zero native dependencies and passes CI on Windows, macOS, and Linux.If you need resources-and-prompts instrumentation or distributed tracing today, another library has more. If you value standards-compliance, correct failure semantics and a small surface you can actually read and reason about, this one is built for that. I'd rather tell you that honestly than pretend it's the answer to every requirement.
Lessons Learned
Building
opentel-mcp taught me that observability is less about writing tracing code and more about understanding system boundaries.I started this project wanting to instrument MCP servers. I finished it with a much deeper appreciation for API design, OpenTelemetry semantic conventions, compatibility across SDK versions, and the importance of respecting existing application behavior.
Perhaps the biggest lesson was that good instrumentation should be almost invisible. Developers shouldn't have to rewrite business logic to gain observability, and instrumentation should never change how an application behaves.
Finally, this project reminded me that reading specifications, validating assumptions, and testing a published package in a real consumer application often reveal problems that unit tests alone cannot.
What's next
The roadmap follows the spec. Metrics are next — the conventions name
mcp.server.operation.duration and session-duration histograms — followed by the opt-in argument capture with a redaction callback. Further out: W3C trace-context propagation through params._meta (per SEP-414) and client-side instrumentation, which together would give one continuous distributed trace across the agent-to-server boundary. And because most real-world MCP servers — including the ones I build — run on Python and FastMCP, a Python counterpart is the direction with the most leverage.One note on stability: the MCP semantic conventions are currently at Development stage, not Stable, which means attribute names can still change. I aligned to them anyway, because being spec-shaped now beats inventing my own names and renaming later. The package is versioned
0.x to signal that breaking changes can land in minor releases until the conventions settle.
Final Thoughts
Building
opentel-mcp started as an attempt to better understand observability in MCP servers. Along the way, it became an opportunity to explore OpenTelemetry, API design, semantic conventions, and the trade-offs involved in building developer tools.More importantly, it reinforced that good open-source software isn't just about solving a problem—it's about making the solution understandable, predictable, and useful for others.
Regardless of how widely
opentel-mcp is adopted, building it significantly deepened my understanding of MCP internals, OpenTelemetry, and observability-driven software engineering.I hope this article not only introduces the library, but also helps other developers better understand how observability fits into modern AI systems built on MCP.
Try it
Ready to add observability to your MCP server?
bash
npm install opentel-mcp @opentelemetry/apiThe library is on npm as
opentel-mcp , and the source, ADRs, and full documentation are on GitHub . If you're building an MCP server and want to see what it's actually doing, it's one line away.Explore the project:
- 📖 Documentation & ADRs: Available in the GitHub repository.
If you find the library useful, have ideas for improvements, or discover an edge case I haven't considered, I'd genuinely love to hear your feedback. Open-source projects become better through community collaboration, and every issue, discussion or contribution helps improve the project.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article