-
Notifications
You must be signed in to change notification settings - Fork 3.4k
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 3 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,12 +8,14 @@ | |
|
|
||
| import anyio | ||
| from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream | ||
| from opentelemetry import trace | ||
| from pydantic import BaseModel, TypeAdapter | ||
| from typing_extensions import Self | ||
|
|
||
| from mcp.shared.exceptions import MCPError | ||
| from mcp.shared.message import MessageMetadata, ServerMessageMetadata, SessionMessage | ||
| from mcp.shared.response_router import ResponseRouter | ||
| from mcp.shared.tracing import end_span_error, end_span_ok, start_client_span, start_server_span | ||
| from mcp.types import ( | ||
| CONNECTION_CLOSED, | ||
| INVALID_PARAMS, | ||
|
|
@@ -77,6 +79,7 @@ def __init__( | |
| session: BaseSession[SendRequestT, SendNotificationT, SendResultT, ReceiveRequestT, ReceiveNotificationT], | ||
| on_complete: Callable[[RequestResponder[ReceiveRequestT, SendResultT]], Any], | ||
| message_metadata: MessageMetadata = None, | ||
| span: trace.Span | None = None, | ||
| ) -> None: | ||
| self.request_id = request_id | ||
| self.request_meta = request_meta | ||
|
|
@@ -87,6 +90,7 @@ def __init__( | |
| self._cancel_scope = anyio.CancelScope() | ||
| self._on_complete = on_complete | ||
| self._entered = False # Track if we're in a context manager | ||
| self._span = span | ||
|
|
||
| def __enter__(self) -> RequestResponder[ReceiveRequestT, SendResultT]: | ||
| """Enter the context manager, enabling request cancellation tracking.""" | ||
|
|
@@ -126,6 +130,12 @@ async def respond(self, response: SendResultT | ErrorData) -> None: | |
| if not self.cancelled: # pragma: no branch | ||
| self._completed = True | ||
|
|
||
| if self._span is not None: | ||
| if isinstance(response, ErrorData): | ||
| end_span_error(self._span, MCPError(code=response.code, message=response.message)) | ||
| else: | ||
| end_span_ok(self._span) | ||
|
|
||
| await self._session._send_response( # type: ignore[reportPrivateUsage] | ||
| request_id=self.request_id, response=response | ||
| ) | ||
|
|
@@ -139,6 +149,10 @@ async def cancel(self) -> None: | |
|
|
||
| self._cancel_scope.cancel() | ||
| self._completed = True # Mark as completed so it's removed from in_flight | ||
|
|
||
| if self._span is not None: | ||
| end_span_error(self._span, MCPError(code=0, message="Request cancelled")) | ||
|
|
||
| # Send an error response to indicate cancellation | ||
| await self._session._send_response( # type: ignore[reportPrivateUsage] | ||
| request_id=self.request_id, | ||
|
|
@@ -260,6 +274,9 @@ async def send_request( | |
| # Store the callback for this request | ||
| self._progress_callbacks[request_id] = progress_callback | ||
|
|
||
| method: str = request_data["method"] | ||
| span = start_client_span(method, request_data.get("params")) | ||
|
|
||
| try: | ||
| jsonrpc_request = JSONRPCRequest(jsonrpc="2.0", id=request_id, **request_data) | ||
| await self._write_stream.send(SessionMessage(message=jsonrpc_request, metadata=metadata)) | ||
|
|
@@ -278,7 +295,15 @@ async def send_request( | |
| if isinstance(response_or_error, JSONRPCError): | ||
| raise MCPError.from_jsonrpc_error(response_or_error) | ||
| else: | ||
| return result_type.model_validate(response_or_error.result, by_name=False) | ||
| result = result_type.model_validate(response_or_error.result, by_name=False) | ||
| if span is not None: | ||
| end_span_ok(span) | ||
| return result | ||
|
|
||
| except BaseException as exc: | ||
| if span is not None: | ||
| end_span_error(span, exc) | ||
| raise | ||
|
|
||
| finally: | ||
| self._response_streams.pop(request_id, None) | ||
|
|
@@ -339,13 +364,19 @@ async def _receive_loop(self) -> None: | |
| message.message.model_dump(by_alias=True, mode="json", exclude_none=True), | ||
| by_name=False, | ||
| ) | ||
| request_data = message.message.model_dump(by_alias=True, mode="json", exclude_none=True) | ||
| server_span = start_server_span( | ||
| request_data.get("method", ""), | ||
| request_data.get("params"), | ||
| ) | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Single line please. Is the method not always available in |
||
| responder = RequestResponder( | ||
| request_id=message.message.id, | ||
| request_meta=validated_request.params.meta if validated_request.params else None, | ||
| request=validated_request, | ||
| session=self, | ||
| on_complete=lambda r: self._in_flight.pop(r.request_id, None), | ||
| message_metadata=message.metadata, | ||
| span=server_span, | ||
| ) | ||
| self._in_flight[responder.request_id] = responder | ||
| await self._received_request(responder) | ||
|
|
||
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,81 @@ | ||
| 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 start_server_span(method: str, params: dict[str, Any] | None) -> trace.Span | None: | ||
| """Start a SERVER span for an incoming 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.SERVER, | ||
| 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() |
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?