|
| 1 | +import contextlib |
| 2 | +from collections.abc import Iterator |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +from opentelemetry.trace import Span, SpanKind, StatusCode, Tracer |
| 6 | + |
| 7 | +from mcp import types |
| 8 | +from mcp.shared.exceptions import MCPError |
| 9 | + |
| 10 | +# OTel Semantic Conventions for MCP and GenAI |
| 11 | +# See: https://github.com/open-telemetry/semantic-conventions/blob/v1.40.0/docs/gen-ai/mcp.md |
| 12 | +MCP_METHOD_NAME = "mcp.method.name" |
| 13 | +MCP_RESOURCE_URI = "mcp.resource.uri" |
| 14 | +JSONRPC_REQUEST_ID = "jsonrpc.request.id" |
| 15 | + |
| 16 | +GEN_AI_TOOL_NAME = "gen_ai.tool.name" |
| 17 | +GEN_AI_OPERATION_NAME = "gen_ai.operation.name" |
| 18 | +GEN_AI_PROMPT_NAME = "gen_ai.prompt.name" |
| 19 | + |
| 20 | +ERROR_TYPE = "error.type" |
| 21 | +RPC_RESPONSE_STATUS_CODE = "rpc.response.status_code" |
| 22 | + |
| 23 | + |
| 24 | +def _get_span_name( |
| 25 | + request: types.ClientRequest | types.ServerRequest | types.ClientNotification | types.ServerNotification, |
| 26 | +) -> str: |
| 27 | + """Computes the span name based on the request type and parameters.""" |
| 28 | + target = None |
| 29 | + match request: |
| 30 | + case types.CallToolRequest(): |
| 31 | + target = request.params.name |
| 32 | + case types.GetPromptRequest(): |
| 33 | + target = request.params.name |
| 34 | + case _: |
| 35 | + pass |
| 36 | + |
| 37 | + if target: |
| 38 | + return f"{request.method} {target}" |
| 39 | + return request.method |
| 40 | + |
| 41 | + |
| 42 | +def _get_common_attributes( |
| 43 | + request: types.ClientRequest | types.ServerRequest | types.ClientNotification | types.ServerNotification, |
| 44 | + *, |
| 45 | + json_rpc_request_id: int | str | None = None, |
| 46 | +) -> dict[str, Any]: |
| 47 | + """Computes common attributes for both client and server spans.""" |
| 48 | + attributes = {MCP_METHOD_NAME: request.method} |
| 49 | + |
| 50 | + if json_rpc_request_id is not None: |
| 51 | + attributes[JSONRPC_REQUEST_ID] = str(json_rpc_request_id) |
| 52 | + |
| 53 | + match request: |
| 54 | + case types.CallToolRequest(): |
| 55 | + attributes[GEN_AI_TOOL_NAME] = request.params.name |
| 56 | + attributes[GEN_AI_OPERATION_NAME] = "execute_tool" |
| 57 | + case types.GetPromptRequest(): |
| 58 | + attributes[GEN_AI_PROMPT_NAME] = request.params.name |
| 59 | + case ( |
| 60 | + types.ReadResourceRequest() |
| 61 | + | types.SubscribeRequest() |
| 62 | + | types.UnsubscribeRequest() |
| 63 | + | types.ResourceUpdatedNotification() |
| 64 | + ): |
| 65 | + attributes[MCP_RESOURCE_URI] = request.params.uri |
| 66 | + case _: |
| 67 | + pass |
| 68 | + return attributes |
| 69 | + |
| 70 | + |
| 71 | +_ERROR_NAMES = { |
| 72 | + types.INVALID_PARAMS: "invalid_params", |
| 73 | + types.METHOD_NOT_FOUND: "method_not_found", |
| 74 | + types.CONNECTION_CLOSED: "connection_closed", |
| 75 | + types.REQUEST_TIMEOUT: "timeout", |
| 76 | + types.PARSE_ERROR: "parse_error", |
| 77 | + types.INTERNAL_ERROR: "internal_error", |
| 78 | + types.INVALID_REQUEST: "invalid_request", |
| 79 | + types.URL_ELICITATION_REQUIRED: "url_elicitation_required", |
| 80 | +} |
| 81 | + |
| 82 | + |
| 83 | +def _record_error_data(span: Span, e: types.ErrorData, record_status: bool = True) -> None: |
| 84 | + """Record an MCP protocol error on the span set status |
| 85 | +
|
| 86 | + https://github.com/open-telemetry/semantic-conventions/blob/v1.40.0/docs/general/recording-errors.md |
| 87 | + """ |
| 88 | + if not span.is_recording(): |
| 89 | + return |
| 90 | + |
| 91 | + span.set_attribute(ERROR_TYPE, _ERROR_NAMES.get(e.code, str(e.code))) |
| 92 | + span.set_attribute(RPC_RESPONSE_STATUS_CODE, str(e.code)) |
| 93 | + span.set_status(status=StatusCode.ERROR, description=e.message) |
| 94 | + |
| 95 | + |
| 96 | +@contextlib.contextmanager |
| 97 | +def mcp_client_span( |
| 98 | + tracer: Tracer, |
| 99 | + request: types.ClientRequest | types.ServerRequest | types.ClientNotification | types.ServerNotification, |
| 100 | + *, |
| 101 | + json_rpc_request_id: int | str | None = None, |
| 102 | +) -> Iterator[Span]: |
| 103 | + """Starts an MCP client span as current span |
| 104 | +
|
| 105 | + https://github.com/open-telemetry/semantic-conventions/blob/v1.40.0/docs/gen-ai/mcp.md#client |
| 106 | + """ |
| 107 | + span_name = _get_span_name(request) |
| 108 | + attributes = _get_common_attributes(request, json_rpc_request_id=json_rpc_request_id) |
| 109 | + |
| 110 | + reraise_exc = None |
| 111 | + with tracer.start_as_current_span( |
| 112 | + span_name, |
| 113 | + kind=SpanKind.CLIENT, |
| 114 | + attributes=attributes, |
| 115 | + set_status_on_exception=False, |
| 116 | + ) as span: |
| 117 | + try: |
| 118 | + yield span |
| 119 | + except MCPError as mcp_error: |
| 120 | + _record_error_data(span, mcp_error.error) |
| 121 | + span.record_exception(mcp_error) |
| 122 | + # re-raise outside of with block to avoid overwriting span status |
| 123 | + reraise_exc = mcp_error |
| 124 | + |
| 125 | + if reraise_exc: |
| 126 | + raise reraise_exc |
0 commit comments