Make OpenTelemetry tracing the single default middleware

Merged
KL
5mo ago
+260-238

The SDK shipped two server-side OpenTelemetry span mechanisms:

  • a dispatch-tier otel_middleware, wired on by default (dispatch_middleware=(otel_middleware,)), span MCP handle <method>;
  • a context-tier OpenTelemetryMiddleware the docs told you to append, span <method>, plus the GenAI semantic-convention attributes.

So a server already emitted a span out of the box, and following the docs (server.middleware.append(OpenTelemetryMiddleware())) added a second, nested span. The "you must append it for tracing" instruction was simply wrong.

This collapses the two into one tier:

  • remove otel_middleware (and its __all__ export); dispatch_middleware now defaults to () but stays a usable extension point;
  • seed Server.middleware with OpenTelemetryMiddleware() in Server.__init__, so both Server and MCPServer trace on by default through the richer context-tier span (mcp.protocol.version + GenAI attrs). Drop it from the list to opt out.
  • it remains a no-op until an OpenTelemetry exporter is installed.

Docs: a dedicated docs/advanced/opentelemetry.md page replaces the misleading section on the middleware page (which now just points to it), plus a tested example.

No migration.md entry: v1 ships no OpenTelemetry, so for a v1->v2 migrant this is a new feature, not a break; MCP handle / otel_middleware only ever lived on v2 main.

Verification

  • ./scripts/test: all pass, 100% coverage, strict-no-cover clean.
  • ruff, pyright, markdownlint, mkdocs build --strict all pass.

AI Disclaimer

This PR was developed with the assistance of either Claude or Codex. I've reviewed and verified the changes.