-
Notifications
You must be signed in to change notification settings - Fork 3.3k
feat: add OpenTelemetry tracing for client and server requests #2025
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
40913a7
feat: add OpenTelemetry tracing for client requests
Kludex 6addcbb
address review feedback
Kludex 3796200
feat: add SERVER spans to OpenTelemetry tracing
Kludex bdfa1ee
address review: remove type cast and use direct dict access for method
Kludex File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from typing import Any | ||
|
|
||
| from opentelemetry import trace | ||
| from opentelemetry.trace import StatusCode | ||
|
|
||
| _tracer = trace.get_tracer("mcp") | ||
|
|
||
| _EXCLUDED_METHODS: frozenset[str] = frozenset({"notifications/message"}) | ||
|
|
||
| # Semantic convention attribute keys | ||
| ATTR_MCP_METHOD_NAME = "mcp.method.name" | ||
| ATTR_ERROR_TYPE = "error.type" | ||
|
|
||
| # Methods that have a meaningful target name in params | ||
| _TARGET_PARAM_KEY: dict[str, str] = { | ||
| "tools/call": "name", | ||
| "prompts/get": "name", | ||
| "resources/read": "uri", | ||
| } | ||
|
|
||
|
|
||
| def _extract_target(method: str, params: dict[str, Any] | None) -> str | None: | ||
| """Extract the target (e.g. tool name, prompt name) from request params.""" | ||
| key = _TARGET_PARAM_KEY.get(method) | ||
| if key is None or params is None: | ||
| return None | ||
| value = params.get(key) | ||
| if isinstance(value, str): | ||
| return value | ||
| return None | ||
|
|
||
|
|
||
| def start_client_span(method: str, params: dict[str, Any] | None) -> trace.Span | None: | ||
| """Start a CLIENT span for an outgoing MCP request. | ||
|
|
||
| Returns None if the method is excluded from tracing. | ||
| """ | ||
| if method in _EXCLUDED_METHODS: | ||
| return None | ||
|
|
||
| target = _extract_target(method, params) | ||
| span_name = f"{method} {target}" if target else method | ||
| span = _tracer.start_span( | ||
| span_name, | ||
| kind=trace.SpanKind.CLIENT, | ||
| attributes={ATTR_MCP_METHOD_NAME: method}, | ||
| ) | ||
| return span | ||
|
|
||
|
|
||
| def end_span_ok(span: trace.Span) -> None: | ||
| """Mark a span as successful and end it.""" | ||
| span.set_status(StatusCode.OK) | ||
| span.end() | ||
|
|
||
|
|
||
| def end_span_error(span: trace.Span, error: BaseException) -> None: | ||
| """Mark a span as errored and end it.""" | ||
| span.set_status(StatusCode.ERROR, str(error)) | ||
| span.set_attribute(ATTR_ERROR_TYPE, type(error).__qualname__) | ||
| span.end() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from typing import Any | ||
|
|
||
| import anyio | ||
| import pytest | ||
| from opentelemetry.sdk.trace import TracerProvider | ||
| from opentelemetry.sdk.trace.export import SimpleSpanProcessor | ||
| from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter | ||
| from opentelemetry.trace import SpanKind, StatusCode | ||
|
|
||
| from mcp import Client, types | ||
| from mcp.server.lowlevel.server import Server | ||
| from mcp.shared.exceptions import MCPError | ||
| from mcp.shared.tracing import ATTR_ERROR_TYPE, ATTR_MCP_METHOD_NAME | ||
|
|
||
| # Module-level provider + exporter — avoids the "Overriding of current | ||
| # TracerProvider is not allowed" warning that happens if you call | ||
| # set_tracer_provider() more than once. | ||
| _provider = TracerProvider() | ||
| _exporter = InMemorySpanExporter() | ||
| _provider.add_span_processor(SimpleSpanProcessor(_exporter)) | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def _otel_setup(monkeypatch: pytest.MonkeyPatch) -> InMemorySpanExporter: | ||
| """Patch the module-level tracer to use our test provider and clear spans between tests.""" | ||
| import mcp.shared.tracing as tracing_mod | ||
|
|
||
| monkeypatch.setattr(tracing_mod, "_tracer", _provider.get_tracer("mcp")) | ||
| _exporter.clear() | ||
| return _exporter | ||
|
|
||
|
|
||
| @pytest.mark.anyio | ||
| async def test_span_created_on_send_request(_otel_setup: InMemorySpanExporter) -> None: | ||
| """Verify a CLIENT span is created when send_request() succeeds.""" | ||
| exporter = _otel_setup | ||
|
|
||
| server = Server(name="test server") | ||
| async with Client(server) as client: | ||
| await client.send_ping() | ||
|
|
||
| spans = exporter.get_finished_spans() | ||
| # Filter to only the ping span (initialize also produces one) | ||
| ping_spans = [s for s in spans if s.attributes and s.attributes.get(ATTR_MCP_METHOD_NAME) == "ping"] | ||
| assert len(ping_spans) == 1 | ||
|
|
||
| span = ping_spans[0] | ||
| assert span.name == "ping" | ||
| assert span.kind == SpanKind.CLIENT | ||
| assert span.status.status_code == StatusCode.OK | ||
|
|
||
|
|
||
| @pytest.mark.anyio | ||
| async def test_span_attributes_for_tool_call(_otel_setup: InMemorySpanExporter) -> None: | ||
| """Verify span name includes tool name for tools/call requests.""" | ||
| exporter = _otel_setup | ||
|
|
||
| server = Server(name="test server") | ||
|
|
||
| @server.list_tools() | ||
| async def handle_list_tools() -> list[types.Tool]: | ||
| return [types.Tool(name="echo", description="Echo tool", input_schema={"type": "object"})] | ||
|
|
||
| @server.call_tool() | ||
| async def handle_call_tool(name: str, arguments: dict[str, Any] | None) -> list[types.TextContent]: | ||
| return [types.TextContent(type="text", text=str(arguments))] | ||
|
|
||
| async with Client(server) as client: | ||
| await client.call_tool("echo", {"msg": "hi"}) | ||
|
|
||
| spans = exporter.get_finished_spans() | ||
| tool_spans = [s for s in spans if s.attributes and s.attributes.get(ATTR_MCP_METHOD_NAME) == "tools/call"] | ||
| assert len(tool_spans) == 1 | ||
|
|
||
| span = tool_spans[0] | ||
| assert span.name == "tools/call echo" | ||
| assert span.status.status_code == StatusCode.OK | ||
|
|
||
|
|
||
| @pytest.mark.anyio | ||
| async def test_span_error_on_failure(_otel_setup: InMemorySpanExporter) -> None: | ||
| """Verify span records ERROR status when the request times out.""" | ||
| exporter = _otel_setup | ||
|
|
||
| server = Server(name="test server") | ||
|
|
||
| @server.list_tools() | ||
| async def handle_list_tools() -> list[types.Tool]: | ||
| return [types.Tool(name="slow_tool", description="Slow", input_schema={"type": "object"})] | ||
|
|
||
| @server.call_tool() | ||
| async def handle_call_tool(name: str, arguments: dict[str, Any] | None) -> list[types.TextContent]: | ||
| await anyio.sleep(10) | ||
| return [] # pragma: no cover | ||
|
|
||
| async with Client(server) as client: | ||
| with pytest.raises(MCPError, match="Timed out"): | ||
| await client.session.send_request( | ||
| types.CallToolRequest(params=types.CallToolRequestParams(name="slow_tool", arguments={})), | ||
| types.CallToolResult, | ||
| request_read_timeout_seconds=0.01, | ||
| ) | ||
|
|
||
| spans = exporter.get_finished_spans() | ||
| tool_spans = [s for s in spans if s.attributes and s.attributes.get(ATTR_MCP_METHOD_NAME) == "tools/call"] | ||
| assert len(tool_spans) == 1 | ||
|
|
||
| span = tool_spans[0] | ||
| assert span.status.status_code == StatusCode.ERROR | ||
| assert span.attributes is not None | ||
| assert span.attributes.get(ATTR_ERROR_TYPE) == "MCPError" | ||
|
|
||
|
|
||
| @pytest.mark.anyio | ||
| async def test_no_span_for_excluded_method(_otel_setup: InMemorySpanExporter) -> None: | ||
| """Verify no span is created for excluded methods (notifications/message).""" | ||
| exporter = _otel_setup | ||
|
|
||
| server = Server(name="test server") | ||
| async with Client(server) as client: | ||
| await client.send_ping() | ||
|
|
||
| spans = exporter.get_finished_spans() | ||
| excluded_spans = [ | ||
| s for s in spans if s.attributes and s.attributes.get(ATTR_MCP_METHOD_NAME) == "notifications/message" | ||
| ] | ||
| assert len(excluded_spans) == 0 |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why is the cast needed?